October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk7 min

Distributed Locks in Go: Correctness, Failure Modes, and Production Patterns

A Go distributed lock coordinates workers, but correctness-critical writes need resource-side fencing so an expired or paused holder cannot act as a valid owner.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A distributed lock can coordinate Go processes, but it cannot by itself guarantee that an expired or disconnected holder has stopped working. If overlapping writes could corrupt data or violate an invariant, the protected resource must reject stale writes—typically by validating a fencing token or version. If a duplicate run is merely wasteful, a lease may be a useful efficiency measure when paired with idempotency and recovery.

Start with the failure your lock must prevent

Before choosing Redis, etcd, or a Go client library, decide what happens if two workers act on the same resource at once. The answer determines whether a lock is a convenience or part of your correctness boundary.

As an Amazon Associate I earn from qualifying purchases.

  • Duplicate work is harmless: A time-limited lock can reduce concurrent runs. Make the operation idempotent where possible, and provide a way to reconcile or retry work that was interrupted.
  • Overlap can damage state: Do not trust a worker’s local belief that it still owns the lock. The database, service, or other resource receiving the write must validate that the worker’s ownership is still current.

A lock service controls who may attempt work according to its coordination state. It cannot reach into a paused Go process and prevent that process from resuming later. This distinction is the central design constraint for correctness-critical locking.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What happens when a lease expires while a Go process is paused?

A lease is ownership that lasts only for a bounded period. If a process is paused, loses network connectivity, or cannot renew its lease, the lease may expire while the process remains alive. Another worker can then acquire the lock and begin work. If the old worker resumes, both may issue writes unless the resource has its own stale-holder check.

The etcd Go lock package’s example demonstrates this failure mode: one client is paused and its lease is revoked or expires; a second client acquires a newer version and writes; when the first client resumes, its stale version is rejected by the storage layer. That rejection depends on the resource checking the version. Acquiring an etcd lock does not automatically fence writes sent to an unrelated database or service.

How fencing tokens prevent stale writes

A fencing token is an ordered value—often a monotonically increasing version—that accompanies each protected write. The resource records the newest accepted token and rejects a request carrying an older one. For example, if worker A holds token 41, its lease expires, and worker B receives token 42, the resource can accept B’s write and refuse A’s later request with token 41.

  1. The coordinator grants an owner a token or version that is newer than previously issued tokens.
  2. The worker includes that token with every write made under the lock.
  3. The protected resource checks the token against its latest accepted value and rejects stale requests.

The check must be enforced at the resource that can be harmed, and it must cover every relevant write path. A lock client’s lease-health check is useful for stopping work promptly, but it cannot replace resource-side validation: a process can be paused between checking its lease and sending a write. Martin Kleppmann’s 2016 argument for correctness-critical locks makes this same distinction and recommends enforcing fencing tokens on resource accesses under the lock.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Using Redis locks in Go

Single-instance acquisition and release

Redis documents a single-instance pattern that creates a lock key only if it is absent and sets an expiry at acquisition time. The value should be a unique owner token, so the client can distinguish its lock from a later holder’s lock. Release must compare the stored value with the caller’s token and delete only on a match.

A plain delete is unsafe. If a worker runs beyond its TTL, another worker may acquire the key; the original worker’s unguarded delete could then remove the successor’s lock. Conditional release prevents that particular mistake, but it does not stop the original worker from continuing to mutate an external resource after its lease expires. Use fencing or an equivalent resource-side version check when stale writes matter.

What Redlock assumes

Redis describes Redlock as acquiring a majority of independent Redis masters within a validity window. The usable time is reduced by the time spent acquiring the lock and an allowance for clock drift. The documented operational guidance includes promptly releasing partial acquisitions, retrying after randomized delays, and bounding extensions rather than renewing indefinitely.

Those mechanics do not make Redlock assumption-free. Redis’ documentation presents it as safer than a basic asynchronous-replication failover pattern, while Kleppmann argues that Redlock relies on bounded timing assumptions and does not itself provide fencing tokens. His criticism is a specific position in an engineering debate, not a universal consensus. Redis’ own documentation says fencing tokens should be implemented. For correctness-sensitive work, assess whether the timing and failure assumptions fit your system, and make the resource reject stale writes regardless of the lock algorithm.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Redis also documents availability penalties during partitions and caveats related to restart and persistence assumptions. A design that waits for a lock’s expiry before progress resumes may favor safety over availability; a design that permits progress under weaker assumptions may increase stale-holder risk. Make that trade-off explicit rather than equating a configured number of Redis servers with guaranteed correctness.

Using etcd leases and versions

etcd provides leases for expiring keys and a KV API whose documented operations are durable and strictly serializable. Its revisions form an increasing logical clock that can be used in version-aware coordination patterns. These properties provide a different basis for coordination than relying only on expiring keys across Redis replicas, but they do not eliminate the need to enforce stale-write protection at a separate resource.

Lease expiry is based on wall-clock time. Also, a client that times out or loses its connection may not know whether an operation completed. Treat a transport error as an ambiguous outcome, not proof that the server did nothing; make retries safe and design cleanup to tolerate repetition.

The etcd API documentation page for v3.4 identifies that version as unsupported and points to v3.7 as the latest stable version on that page. Check the documentation and Go client API for the exact etcd version you deploy before relying on method signatures or version-specific behavior.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

A production workflow for a Go worker

  1. Set a bounded acquisition deadline. Use the selected lock library’s context-aware API where available, and propagate cancellation from the request or worker lifecycle.
  2. Record ownership state. Keep the owner or lease identity and the fencing token/version needed for protected writes.
  3. Bound the work and monitor lease health. Stop or abandon work when ownership is lost. If you extend a lease, bound the extension policy so a stalled worker cannot renew forever and starve contenders.
  4. Fence every protected write. Include the token with writes and have the receiving resource reject stale values. Do not assume a successful lock acquisition makes an unrelated storage system enforce this rule.
  5. Release conditionally and safely. Cleanup should be repeatable and must release only a lock still owned by this worker. For Redis, compare the unique owner value before deleting.
  6. Make side effects recoverable. Use idempotency keys, durable work state, transactions, or reconciliation as appropriate. A lock coordinates contenders; it does not provide exactly-once execution across a workflow.

Under contention, jittered retries reduce synchronized retry attempts. With Redis-style multi-node acquisition, promptly clean up partial acquisitions. When an operation’s result is ambiguous because of a timeout or broken connection, reconcile state or retry through an idempotent path rather than assuming either success or failure.

Choosing between Redis, etcd, and a resource-native transaction

Approach What the documented approach provides Key correctness question Operational consideration
Redis single-instance lock Conditional key creation with an expiry and owner value; conditional release is needed to avoid deleting a successor’s lock. Can the protected resource reject writes from a holder whose TTL has expired? Account for expiry, retry behavior, and the Redis instance’s failure and restart assumptions.
Redis Redlock Majority acquisition across independent masters within a calculated validity window, with clock-drift allowance. Do the timing assumptions fit, and does the resource enforce fencing independently? Partial acquisitions, randomized retries, bounded extensions, partitions, and persistence/restart behavior require deliberate handling.
etcd lease and KV operations Leases for expiring keys; the documented KV API describes durable, strictly serializable operations and increasing revisions. Does the protected resource validate a current version, especially if it is outside etcd? Plan for wall-clock lease expiry and ambiguous outcomes when clients time out or disconnect; verify the API for the deployed version.
Transaction or version check in the resource Can make ownership or update validation part of the same resource operation when the data model supports it. Can the invariant be enforced atomically where the protected state lives? Whether this avoids a separate lock service depends on the application’s state model and transaction capabilities.

No universal backend winner follows from these properties. Compare stale-holder enforcement, consistency and failure assumptions, partition behavior, and the operational burden your team can support. Measure latency and throughput in your own deployment; the cited documentation does not provide a directly comparable performance benchmark.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.