The Desi Architect
Notes / Docker Sandboxes / Distributed Lock Fencing Tokens & Lease Expiration
Docker Sandboxes · Tier 4: Architect & Chaos · Lab 50

Distributed Lock Fencing Tokens & Lease Expiration

Watch a distributed lock fail when a worker pauses, then make the storage layer reject the stale write. Acquire a lock with a monotonic fencing token in Redis, freeze Worker A past its TTL, let Worker B commit, and watch Postgres reject Worker A when it wakes up.

Time30 minutes
StackRedis 7Ports 16392, 15439
MemoryAbout 50 MB
Before thisLab 07Lua in Redis
Verified runWindows, Mac, LinuxBash and PowerShell
  1. 1PrepareWhat you will learn
  2. 2PredictGuess before you run
  3. 3RunStep by step
  4. 4ObserveWhat you should see
  5. 5Break itChange one thing
  6. 6Clean upLeave nothing running
On this page
  1. 00 / What You Will Learn
  2. 01 / Why It Matters
  3. 02 / What We Are Building
  4. 03 / Words You Need
  5. 04 / Predict First
  6. 05 / Step by Step
  7. 06 / What You Should See
  8. 07 / Look Inside
  9. 08 / Break It, Fix It
  10. 09 / In Real Projects
  11. 10 / Interview Corner
  12. 11 / Clean Up

00 /What You Will Learn

By the end you will be able to
  • Explain why a distributed lock alone cannot guarantee safety when clients can pause for garbage collection or disk stalls.
  • Use Martin Kleppmann's fencing token to make the database the final authority that rejects delayed writes.
  • Acquire a lock and monotonic token together in Redis using an atomic Lua script.
  • Enforce the fencing check in PostgreSQL with a guarded UPDATE ... WHERE last_fencing_token < token.
  • Explain why Redlock without fencing tokens cannot prevent split-brain overwrites at the database layer.

Before you start

Finish Lab 06 (Redis Basics) and Lab 08 (Race Conditions) first. You should know what a TTL is and how uncoordinated concurrent writes corrupt data. Docker Desktop and Python 3 are needed.