Interview's MateSystem Design
Interview's Mate

System Design

Architecture & trade-offs

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
System Design topics
Lesson 18/ 31
Distributed Systems & Architecture

Distributed Locks & Unique IDs

Coordinate mutually exclusive jobs safely with fencing tokens and generate sortable 64-bit IDs at scale.

IntermediateFencing Tokens · Snowflake IDs3 quiz questions0/2 subtopics done
Practice in AI HLD
In plain wordsDiagramTheorySubtopics (2)Step by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice
Deep-dive subtopics (2) - 0/2 completed
Distributed Locks & Fencing Tokens

Avoid deadlocks and zombie writers using leases and monotonic fencing tokens.

Intermediate
Snowflake IDs, UUIDv7 & Ticket Servers

Generate billions of globally unique, time-sortable 64-bit IDs without central bottlenecks.

Intermediate

In plain words

A distributed lock makes sure only one server does a task at a time, like a single key to a shared room. Unique ID generators give every record a number no other server will ever reuse.

Think of it like…

A fencing token is a numbered ticket stamped on every lock checkout: the vault rejects anyone holding yesterday’s expired ticket number even if they swear they still hold the key.

Where you’ve seen it

Twitter’s Snowflake IDs combine a timestamp, a machine number, and a counter, so thousands of servers can create tweet IDs without talking to each other.

Words you’ll hear

Lock lease
A lock that expires automatically if the holder crashes.
Fencing token
An increasing number that stops an old, expired lock holder from writing.
Snowflake ID
A 64-bit ID made from time + machine ID + sequence.
UUID
A random 128-bit ID that is practically never duplicated.

Visual diagram

Loading interactive diagram
Loading interactive exercise

Theory & deep dive

Distributed Locks: Leases + Fencing Tokens

A naive lock without an expiry TTL deadlocks forever if the holder crashes. Adding a lease TTL fixes crashed holders, but introduces a subtle bug: if Worker A freezes during a long garbage-collection pause, its lease expires, Worker B gets the lock, and then Worker A wakes up and overwrites Worker B’s work!

The true fix is a fencing token: an ever-increasing number (33, 34, 35...) handed out with each lock. The database checks incoming_token >= last_seen_token and rejects stale zombies.

Unique IDs at Scale: Why Auto-Increment Breaks

A single SQL AUTO_INCREMENT column breaks as soon as you shard across multiple databases or need IDs generated without hitting one central bottleneck. Snowflake IDs solve this cleanly in 64 bits: [41 bits timestamp | 10 bits machine ID | 12 bits sequence] - fitting inside a standard SQL BIGINT, sortable by creation time, and generating 4,096 IDs per millisecond per worker with zero coordination!

How it works, step by step

Step 1 of 4
Lock Service (etcd/Redis)

1. Acquire lock with a bounded Lease TTL

Always attach a TTL/lease so if a worker crashes mid-task, the lock automatically releases instead of deadlocking the system forever.

Never grant an infinite lock across a network
Key numbers at this step
Lease TTL
e.g. 10–30s
Renew
Background heartbeat

When to use it & trade-offs

What it is

Distributed locks coordinate mutual exclusion across servers using time-bounded leases and fencing tokens, while distributed ID generators (like Snowflake) mint unique, roughly time-sorted 64-bit IDs with zero central DB bottleneck.

Why it matters: Naive locks fail when a paused worker wakes up after its lock expires; naive auto-increment DB IDs become a single-point write bottleneck.

When to reach for it

  • Fencing tokens on leader election, cron job locking, and inventory leases
  • Snowflake or UUIDv7 for primary keys in sharded SQL/NoSQL tables
  • DB-allocated ID blocks (ticket server caching 1,000 IDs in RAM) for simple setups

When to avoid or be careful

  • Using Redis SET NX EX alone for strict correctness without fencing tokens (if a GC pause outlives EX, two workers write concurrently)
  • Using single-DB AUTO_INCREMENT as a shared ID generator across 64 database shards

Unique ID Generation Strategies

UUIDv4 (128-bit Random)
Best for: Low-coordination client-side IDs where DB index locality isn’t critical

Strengths: Zero central coordination; negligible collision risk.

Watch out: 128-bit size and random order cause severe B-Tree page fragmentation at scale.

Snowflake ID (64-bit)
Best for: High-QPS tweets, orders, messages needing compact sortable BIGINT PKs

Strengths: Fits in 64-bit integer, roughly time-sorted, zero cross-node sync per ID.

Watch out: Requires assigning unique worker IDs and handling NTP backward clock jumps.

UUIDv7 / ULID (128-bit Time-Sorted)
Best for: Modern apps wanting zero worker-ID management plus B-Tree friendliness

Strengths: 48-bit millisecond timestamp prefix + randomness; no worker registry needed.

Watch out: Twice as wide as 64-bit Snowflake IDs (16 bytes vs. 8 bytes).

Interview signals & numbers to know

When this topic comes up

  • unique ID generator
  • 64-bit sortable ID
  • distributed lock
  • prevent duplicate cron
  • clock skew

Benchmarks & rules of thumb

Snowflake 41-bit ms span -
~69 years
Snowflake 12-bit seq/ms -
4,096 IDs/ms per node
UUIDv4 bits -
128 bits (122 random)
Typical lock lease -
10–30 seconds

Common mistakes & follow-ups

Common interview mistakes

  • Thinking a Redis TTL lock guarantees mutual exclusion when a client pauses longer than the TTL
  • Using AUTO_INCREMENT on sharded tables without step offsets or Snowflake IDs
  • Ignoring NTP clock stepping backward in Snowflake generators

Likely interviewer follow-ups

  • Walk through the exact failure scenario where two workers both think they hold a Redis lock, and how fencing tokens prevent data corruption.
  • Why does Snowflake use 41 bits for timestamps and 12 bits for sequences?
  • What happens if NTP moves the system clock backward by 50 ms on a Snowflake worker?
Interview tip: Whenever you draw a distributed lock, immediately add “plus a monotonic fencing token checked by the downstream store”.

Knowledge check

Loading quiz

Put it into practice

Design full architectures with AI feedback

Apply Distributed Locks & Unique IDs inside real High-Level Design prompts or review Q&A flashcards.

Open AI HLD Practice →SD Interview Q&A
Previous topic
Distributed Consensus & Coordination
Next topic
API Design & Gateways