flock
Thread-safe, cross-platform file locking for Go, with blocking and non-blocking lock acquisition.
Repository Health
Technical Analysis
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
Flocktype 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(), andStat()accessors for introspecting lock state without external toolingSetFlag()andSetPermissions()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
Coder
Devops · Developer Tools · Code Editors
Self-hosted cloud development environments and AI coding agents — defined in Terraform, connected via WireGuard, automatically shut down when idle.
Cog
AI Development · Devops · Developer Tools
An open-source CLI that packages machine learning models into standard, production-ready Docker containers — no Dockerfile wrangling, no CUDA version hell.
Dokku
Devops · Hosting Control Panel
The smallest PaaS implementation you've ever seen — deploy apps via git push using Docker and Heroku buildpacks on your own server.
kopia
File Storage
Fast, encrypted, deduplicated backups to any cloud or local storage with full client-side control.
cli
Developer Tools · Team Chat
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.
Netdata
Monitoring · Devops
Real-time per-second metrics, ML-powered anomaly detection, and zero-config observability for any infrastructure.
Teleport
Security · Authentication
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.