Designing a Distributed Lock Service with etcd v3.5, gRPC, and Go on Kubernetes 1.30: Lease Expiration, Fencing Tokens, and Failure Modes

User avatar placeholder
Written by Tamzid Ahmed

November 7, 2026

Designing a distributed lock service with etcd requires more than acquiring a key; it requires reasoning about lease expiration, fencing tokens, and failure modes before a production incident teaches those lessons. This guide explains a practical Go and gRPC design running on Kubernetes 1.30 and highlights the tradeoffs that matter in real systems.

What a distributed lock service with etcd actually guarantees

A distributed lock is a mutual-exclusion primitive shared across processes. It guarantees that only one caller acts as owner at a time and that ownership can transfer after a failure. In etcd, that guarantee comes from leased keys and compare-and-swap transactions, not from key existence alone.

Lock semantics vs queue semantics

Use a lock to protect short critical sections such as leader election, schema migration, or singleton scheduling. Do not use it as a general job queue; a lock guards an action, while a queue manages units of work.

Why fencing tokens are mandatory

A lock protects the lock service, not the protected resource. If a holder pauses beyond lease expiry, the service can grant the same key to another owner. A fencing token lets the protected resource reject writes from a stale owner even when that owner still thinks it holds the lock.

Architecture: etcd v3.5, gRPC, and Go

The service has three runtime parts: a highly available etcd cluster, a Go gRPC API, and the protected resource that validates tokens. The Go service translates client requests into etcd transactions and keeps leases alive until unlock or expiry.

Acquire path

  1. The client calls Acquire with a resource name and requested TTL.
  2. The Go service grants an etcd lease and writes the lock key only if the key does not already exist.
  3. It stores a unique holder ID and returns the successful transaction revision as the fencing token.
  4. It starts lease keepalive traffic for the active holder.
  5. The client performs work while annotating downstream requests with the token.
  6. Release compares the holder ID before deleting the key.

Keepalive path

The service maintains etcd keepalive streams and marks a lock unhealthy when renewal responses stop arriving. On application restart, lease expiry removes stale locks without manual cleanup or operator intervention.

Lease expiration design

Choose a TTL that is longer than expected garbage-collection pauses and retry storms, but short enough for acceptable failover time. A practical starting point is 10 to 30 seconds, with keepalive requests issued at roughly one third of the TTL.

Lease expiration is not an instant failure signal; it is a delayed ownership revocation. Every dependent write should treat token rejection as normal control flow rather than an unexpected error.

Tuning tradeoffs

  • Shorter TTLs reduce failover time but increase false expiry during transient latency.
  • Longer TTLs improve stability but delay recovery after a crashed holder.
  • Keepalive traffic adds load; batching several lock leases under one etcd lease can reduce overhead but couples their lifetimes.
  • Keep timeout logic server-side where possible, because clock skew and client pauses create subtle ownership errors.

Fencing tokens and stale writes

A fencing token is a monotonically increasing value issued with each lock grant. The protected resource records the highest token it has accepted and rejects any request carrying an equal or lower token.

In etcd, the revision returned by the successful compare-and-swap transaction is a practical token because the cluster assigns revisions in a strict order. Application code should treat tokens as opaque integers and never fabricate or reuse them.

Token generation choices

  • Use the etcd revision from the successful lock transaction when a cluster-global order is sufficient.
  • Use a dedicated counter when tokens must be compact or scoped to a single lock.
  • Store and compare tokens at the protected-resource boundary, such as a database row or object metadata.
  • Return validation errors explicitly so clients know to stop and reacquire.

Failure modes

The dangerous cases are not clean crash-stop failures, which etcd handles well. The dangerous cases are slow or delayed processes that incorrectly believe their lease is still valid.

  • Process crash: keepalive stops, the lease expires, and another holder can acquire safely.
  • Network partition: a minority-side holder cannot renew, while the majority can grant a new owner after expiry.
  • GC pause or scheduler stall: holder time exceeds the TTL, causing ownership loss even when the process later resumes.
  • etcd leader change: clients retry; the lease survives in the cluster, but keepalive streams may need reconnection.
  • Expired-but-working holder: stale writes occur unless the protected resource enforces fencing tokens.
  • Thundering herd: many waiters retry together after expiry; use watchers or exponential backoff to smooth acquisition.

Recovery behavior

On token rejection, clients should abort the critical section, avoid repeating side effects, and reacquire before retrying. Replaying the same operation after a fencing failure can duplicate writes and corrupt state.

Deploying on Kubernetes 1.30

Run etcd as a separately operated, highly available cluster rather than embedding it in the application workload. Deploy the Go service as a Kubernetes Deployment with multiple replicas behind a Service, and expose readiness through the gRPC health protocol.

  • Set CPU and memory requests because keepalive latency affects correctness, not only performance.
  • Use separate readiness and liveness probes; a live but partitioned pod should stop receiving traffic.
  • Configure graceful shutdown to release locks and cancel keepalive streams when SIGTERM arrives.
  • Place etcd members across failure domains, configure quorum, and maintain backups.

Recommended runtime settings

Start with a 15-second lease TTL, keepalive every 5 seconds, acquisition retries with exponential backoff capped at 2 seconds, and a token validation timeout below the lock TTL.

Tradeoffs and alternatives

etcd is strongly consistent and provides mature lease primitives, but it is not the lowest-latency choice for every workload. Redis locks are faster and simpler for soft coordination, while database advisory locks reuse existing operational skills. ZooKeeper remains mature for hierarchical coordination but adds another operational estate.

If operations can be made idempotent with explicit versions, optimistic concurrency may remove the need for a separate distributed lock entirely.

Conclusion

A robust distributed lock service with etcd combines leased ownership, monotonic fencing tokens, and explicit failure handling. Start with conservative TTLs, validate tokens at every protected resource, and exercise partitions and long pauses before calling the design production-ready.

Actionable tip: Add a chaos test that pauses a lock holder beyond TTL, confirms token rejection at the protected resource, and measures recovery time before shipping.

Leave a Comment