Guide
Premium
Intermediate
Real Projects

Distributed Locks and Leader Election: Fencing Tokens, Kubernetes Leases, PostgreSQL Advisory Locks, and Why Redlock Isn't Enough for Correctness

A practical guide to the mechanism almost everyone gets wrong: why every TTL-based lock has a window where two processes both believe they own it (GC pauses, cgroup throttling, network partitions), the question to answer before picking a tool —are you locking for efficiency or for correctness?—, a Redis lock done properly with SET NX PX and a Lua compare-and-delete release, the Redlock controversy and what it actually buys you, PostgreSQL transaction-level advisory locks (and why session-level ones break under PgBouncer transaction pooling), queues with FOR UPDATE SKIP LOCKED, leader election with Kubernetes Leases and etcd —including the fact that client-go does not fence and the leaseTransitions field that does work as a token—, end-to-end fencing with UPDATE ... WHERE fence_token < $1, and the most valuable chapter: the five designs that remove the need for a lock entirely. With production-ready code in Python, SQL, Go, Lua and YAML, eight recurring mistakes, Prometheus observability, a checklist, FAQ and glossary. Expanded on 18 September 2026: the clocks that decide whether your TTL is a promise or a fiction (CLOCK_MONOTONIC vs CLOCK_BOOTTIME, why you subtract the whole RTT, and the point of no return before every write), the watchdog that renews the lease and why renewal does not close the window unless it is a CAS on the token, the full arithmetic of Kubernetes leader election (LeaseDuration, RenewDeadline and RetryPeriod, the mandatory os.Exit(1) in OnStoppedLeading, and the leaseTransitions field that hands you a fencing token for free), a Redis failover told second by second in which a lock is lost with nobody at fault and what WAIT and min-replicas-to-write actually fix, two more backends that work (DynamoDB conditional writes with the rvn trick that avoids comparing clocks, and Consul sessions with lock-delay and ModifyIndex), scheduled jobs with the concurrencyPolicy Forbid that is not mutual exclusion and the hundred missed schedules that stop the controller for good, granularity and cost with the three metrics that make contention visible and the convoy that takes the system down, and three tests that prove your lock is broken before production does (SIGSTOP, Toxiproxy and the assertion on the fence).

47 minutes read
1 views

Verificando acceso...

Loading comments...

Related Resources

Guía
PREMIUM

API Versioning and Contract Testing: Safe Changes, OpenAPI in CI, Pact, and Retiring Endpoints with Sunset

A practical guide to changing your APIs without breaking the people who consume them: why compatibility rules invert between the request and the response —and why widening a returned enum breaks clients even though you are "only adding"—, the tolerant reader pattern in Pydantic with an escape hatch and a metric, OpenAPI generated from the code and diffed on every pull request with oasdiff (including the git diff --exit-code step without which the whole check is theatre), consumer-driven contract testing with Pact: type matchers instead of literal values, well-designed provider states, version selection with deployed_or_released, and the gate that actually makes it safe, can-i-deploy paired with record-deployment. It also covers rolling this out without stopping the factory using pending and WIP pacts, bi-directional contracts when the provider is a third party, the three versioning strategies with their real operational costs, why versioning the whole API for a single endpoint guarantees nobody migrates, retiring versions with the Deprecation (RFC 9745) and Sunset (RFC 8594) headers plus the migration Link, the per-consumer metric without which no sunset date is ever met, brownouts returning 410 Gone before the final shutdown, and the BACKWARD, FORWARD and FULL compatibility modes for event schemas. With production-ready code in Python, YAML, Bash and PromQL, eight recurring mistakes, a production checklist, FAQ and glossary. It also extends the contract beyond the happy path: errors with RFC 9457 (problem+json), cursor pagination and defaults as part of the contract, the expand/contract pattern for renaming a field across database and API with no maintenance window, governance with Spectral, buf breaking for gRPC and Protobuf, GraphQL schema evolution with @deprecated and real per-field usage, and semantic versioning of generated SDKs. It also covers the contracts that never show up in the schema and break just as hard: outbound webhooks with the version pinned on the subscription, HMAC signing with a timestamp window and key rotation, Idempotency-Key for safe POST retries, the RateLimit and RateLimit-Policy headers —and why lowering a limit is a breaking change—, and OAuth scopes, the blind spot no OpenAPI diff will ever catch.

Guía
PREMIUM

asyncio in Production: Never Block the Event Loop — TaskGroups, Cancellation and Bounded Concurrency

A practical asyncio guide for Python services in production: why blocking the event loop degrades the whole process without raising a single exception, how to catch it by measuring loop lag and with Python 3.14 introspection, structured concurrency with TaskGroup and handling ExceptionGroup via except*, the task the garbage collector makes vanish, timeouts with a deadline budget propagated across services, correct cancellation with cleanup and shield, bounded concurrency with semaphores and backpressured queues, synchronization primitives, and what changes with eager tasks, python -m asyncio pstree and free-threading. With production-ready code and a deployment checklist.

Guía
PREMIUM

Cache-Aside in Production: TTLs, Invalidation, and How to Prevent Cache Stampedes

The complete guide to the cache-aside pattern with Redis: jittered TTLs, correct invalidation, and the three defenses against cache stampedes (distributed lock, single-flight, and XFetch). Expanded with stale-while-revalidate, fail-open and circuit breakers, two-tier caching with RESP3 invalidation, delayed double delete and CDC, hot keys, eviction and memory management, observability with Prometheus, testing, choosing an engine (Redis, Valkey, Memcached), and a complete TypeScript implementation. With production-ready code in Python and TypeScript.