flock

Thread-safe, cross-platform file locking for Go, with blocking and non-blocking lock acquisition.

Library
Go
vv0.13.1
756stars
BSD 3-Clause License

Repository Health

Pre-computed score based on development activity, maintenance, community, maturity, and trend momentum.How we score it →
68/100Good
Development Activity72
Maintenance48
Community64
Maturity60
Momentum28

Technical Analysis

AI-assessed by reading the actual repository — architecture, code quality, innovation, and documentation.How we score it →
73/100Good
Architecture82
Code Quality90
Innovation55
Learning Curve65

flock implements a thread-safe file lock for Go programs, wrapping the native OS locking primitive on each supported platform behind one consistent API. It exposes blocking Lock()/RLock() calls, non-blocking TryLock()/TryRLock() variants, and context-aware TryLockContext()/TryRLockContext() helpers that poll on an interval until the lock is acquired, the context is canceled, or it times out.

Under the hood, the same Flock type dispatches to flock(2) on Unix-like systems, LockFileEx on Windows, and POSIX fcntl record locks on AIX/Solaris/Illumos, selected at compile time via Go build tags. Originally created as github.com/theckman/go-flock, the project was transferred to the gofrs organization and is now a de facto standard dependency across the Go ecosystem for coordinating exclusive access to a resource across processes — used by CLIs to prevent duplicate runs, daemons to guard shared state files, and job schedulers enforcing single-instance execution.

What You Get

  • A Flock type wrapping a single lock file with blocking (Lock/RLock) and non-blocking (TryLock/TryRLock) acquisition methods
  • Context-aware polling helpers (TryLockContext/TryRLockContext) for retrying lock acquisition with a timeout or cancellation
  • Automatic dispatch to the correct OS locking primitive at compile time via Go build tags, with no runtime platform detection needed
  • Path(), Locked(), RLocked(), and Stat() accessors for introspecting lock state without external tooling
  • SetFlag() and SetPermissions() options for controlling how the lock file itself is created or opened

Common Use Cases

  • Preventing duplicate concurrent runs of a CLI tool or cron job
  • Coordinating safe reads and writes to a shared file between multiple processes
  • Enforcing a single running instance of a background service per host
  • Bounding lock-acquisition attempts with a context deadline in request-handling code

Under The Hood

Architecture The library centers on the Flock struct (flock.go), which holds the lock path, a sync.RWMutex, an *os.File handle, and boolean exclusive/shared lock-state flags. Build-tag-selected files (flock_unix.go, flock_windows.go, flock_unix_fcntl.go, flock_others.go) each implement the identical exported method surface (Lock, RLock, Unlock, TryLock, TryRLock) against the same *Flock receiver, keeping the platform-agnostic code in flock.go — constructors, TryLockContext/TryRLockContext, accessors, and file-handle lifecycle helpers (setFh, resetFh, ensureFhState) — free of any OS-specific branching. The in-memory sync.RWMutex only serializes concurrent goroutines sharing one *Flock instance; the real lock is the OS primitive itself. On AIX/Solaris, flock_unix_fcntl.go layers a second package-level lock table (inodes/locks maps guarded by their own mutex) on top of POSIX fcntl locks to correctly emulate flock-style per-file semantics, since POSIX locks apply per inode-and-process rather than per descriptor. It’s a tightly scoped, modular design: every platform file shares one method contract, so swapping the underlying *os.File abstraction would touch each platform implementation identically.

Tech Stack Pure Go targeting Go 1.25 (go.mod), with zero required runtime dependencies beyond golang.org/x/sys for its unix and windows syscall wrappers; github.com/stretchr/testify and go.yaml.in/yaml/v3 are test-only dependencies. There’s no web framework, ORM, or database involved — this is a low-level OS-facing library. Build tooling is minimal: a Makefile wraps golangci-lint run and go test -race, plus a build.sh cross-compilation smoke test iterating every GOOS/GOARCH pair from go tool dist list (explicitly skipping plan9/js-wasm/wasip1, which fall back to an “unsupported platform” stub in flock_others.go). CI workflows for testing, linting, releases, and an OpenSSF Scorecard, plus Dependabot, round out conventional, well-maintained Go OSS tooling.

Code Quality Tests use testify’s suite package for a full external black-box suite (flock_test.go, package flock_test) covering New, Lock, RLock, TryLock, TryRLock, TryLockContext, TryRLockContext, and Stat, plus a smaller internal white-box test file exercising file-handle cleanup after a failed TryLock. Runnable Example* functions double as verified documentation. Errors are wrapped in *fs.PathError with the operation name attached, and the fcntl backend carries extensive comments explaining a spurious-EDEADLK workaround ported from the Go standard library’s own internal lockedfile package, citing the upstream issue it addresses — a strong signal of correctness-focused engineering rather than copy-pasted code. An extensive .golangci.yml linter configuration runs in CI, and go test -race is a defined Make target given the concurrency-sensitive subject matter.

What Makes It Unique flock doesn’t invent a new locking concept — flock(2)/fcntl/LockFileEx are well-established OS facilities — but its value is correctly and portably unifying three genuinely incompatible platform locking APIs behind one Go interface, including edge cases most wrappers skip: AIX/Solaris process-vs-inode fcntl semantics, spurious EDEADLK handling ported from Go’s own stdlib, and stale file-handle recovery via reopenFDOnError after a transient EIO/EBADF. That correctness work, more than novelty, is what has made it a de facto standard for this problem across the Go ecosystem.

Used by 7 apps in this directory

Go
75%
AGPL 3.0

Coder

Devops · Developer Tools · Code Editors

14,299

Self-hosted cloud development environments and AI coding agents — defined in Terraform, connected via WireGuard, automatically shut down when idle.

View details
93
Repo Health
90
Technical
69
Dependency
Built with
Go75%
TypeScript23%
Updated today
Go
59%
Apache 2.0

Cog

AI Development · Devops · Developer Tools

9,464

An open-source CLI that packages machine learning models into standard, production-ready Docker containers — no Dockerfile wrangling, no CUDA version hell.

View details
90
Repo Health
88
Technical
69
Dependency
Built with
Go59%
Rust17%
HTML13%
Updated 4 days ago
Shell
48%
MIT

Dokku

Devops · Hosting Control Panel

32,114

The smallest PaaS implementation you've ever seen — deploy apps via git push using Docker and Heroku buildpacks on your own server.

View details
93
Repo Health
85
Technical
71
Dependency
Built with
Shell48%
Go48%
Updated today
Go
97%
Apache 2.0

kopia

File Storage

13,990

Fast, encrypted, deduplicated backups to any cloud or local storage with full client-side control.

View details
90
Repo Health
83
Technical
70
Dependency
Built with
Go97%
Updated 5 days ago
Go
95%
MIT

cli

Developer Tools · Team Chat

16,854

The official Lark/Feishu CLI tool built for both humans and AI agents, delivering 200+ commands and 26 AI agent skills across 18 business domains from messaging and calendar to docs, sheets, and approvals.

View details
83
Repo Health
83
Technical
76
Dependency
Built with
Go95%
Updated today
Go
44%
GPL 3.0

Netdata

Monitoring · Devops

80,357

Real-time per-second metrics, ML-powered anomaly detection, and zero-config observability for any infrastructure.

View details
93
Repo Health
86
Technical
71
Dependency
Built with
Go44%
C32%
Rust15%
Updated today
Go
75%
AGPL 3.0

Teleport

Security · Authentication

20,860

Zero-trust infrastructure access platform that replaces credentials and VPNs with short-lived certificates, SSO, and identity-aware proxies for SSH, Kubernetes, databases, RDP, and AI agents.

View details
94
Repo Health
81
Technical
69
Dependency
Built with
Go75%
TypeScript16%
Updated 2 days ago

Join founders buildingwith open source

Opinionated takes, migration guides, cost-saving tips, and insights from the open source ecosystem.

Subscribe on Substack
Join 750+ subscribers

Search