Sub topic 10
Allocating unique IDs across many servers
This chapter assumes you have read the earlier chapters on base62 encoding and short code generation. You should be comfortable with a relational table, an atomic UPDATE, and basic threading in Python.
The counter-based strategy from the previous chapter has one requirement: every new link needs an integer that nobody else has used. That is easy with one server. It gets harder when ten write servers run at once.
Why a single counter stops working
With one application server, a database AUTO_INCREMENT column or a Redis INCR hands out unique numbers. Every write request asks the same counter for the next value. That design has three problems once you scale out:
- Throughput. Every create request makes a network round trip to the counter. The counter's write rate caps your write rate.
- Single point of failure. If the counter is down, nobody can create links, even though redirects still work from the cache and replicas.
- Latency. In a multi-region deployment, a counter in one region adds a cross-region round trip to every write in the others.
You can't fix this by letting each server keep its own local counter. Two servers that both start at 1 will both issue code 1, and the second insert will fail.
The practical answers are all variations on one idea: partition the ID space so servers can work without talking to each other on every request.
Four ways to partition the ID space
| Approach | How it avoids duplicates | Coordination needed | Main drawback |
|---|---|---|---|
| Single counter | One place issues all IDs | Every request | Bottleneck and single point of failure |
| Range allocation | Each server leases a block of IDs | Once per block | IDs lost on crash, sequential output |
| Embedded worker ID (Snowflake style) | Server number is part of the ID | Once, at startup | IDs are 64 bits, so codes are long |
| Random or hash codes | Probability, plus a unique constraint | None, but retry on collision | Collisions rise as the table fills |
The last row is covered in the collision chapter, so this chapter focuses on the first three.
Range allocation
In range allocation, a small coordinator service owns the "next free ID". A server does not ask for one ID. It asks for a block, for example 1,000 IDs, then hands them out from memory. When the block runs out, it asks for another.
The coordinator can be a single row in your database:
CREATE TABLE id_ranges (
name VARCHAR(32) PRIMARY KEY,
next_id BIGINT NOT NULL
);
INSERT INTO id_ranges (name, next_id) VALUES ('urls', 1);
-- Lease 1000 IDs atomically (PostgreSQL). The returned start_id is
-- the first ID of the block [start_id, start_id + 1000).
UPDATE id_ranges
SET next_id = next_id + 1000
WHERE name = 'urls'
RETURNING next_id - 1000 AS start_id;The UPDATE is atomic, so two servers calling it at the same moment get different blocks. The coordinator now sees one request per 1,000 links instead of one per link.
Here is a runnable version of the server-side allocator. RangeStore stands in for the database row.
import threading
ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
def encode(n: int) -> str:
if n == 0:
return ALPHABET[0]
digits = []
while n > 0:
n, r = divmod(n, 62)
digits.append(ALPHABET[r])
return "".join(reversed(digits))
class RangeStore:
"""Stands in for the shared id_ranges row."""
def __init__(self, start: int = 1):
self._next = start
self._lock = threading.Lock()
def lease(self, size: int):
with self._lock:
start = self._next
self._next += size
return start, start + size # half-open range [start, end)
class IdAllocator:
def __init__(self, store: RangeStore, block_size: int = 1000):
self._store = store
self._block = block_size
self._cur = 0
self._end = 0 # empty block, so the first call leases
self._lock = threading.Lock()
def next_id(self) -> int:
with self._lock:
if self._cur >= self._end:
self._cur, self._end = self._store.lease(self._block)
n = self._cur
self._cur += 1
return n
store = RangeStore()
server_a = IdAllocator(store, block_size=3)
server_b = IdAllocator(store, block_size=3)
print([encode(server_a.next_id()) for _ in range(4)]) # ['1', '2', '3', '7']
print([encode(server_b.next_id()) for _ in range(2)]) # ['4', '5']Server A's fourth ID is 7 because its second lease started after server B had taken 4 to 6. IDs are unique, but they are not globally ordered.
Gaps and crashes
If a server crashes with 600 unused IDs in memory, those IDs are gone. Nothing will reissue them, because the coordinator has already moved past them. This is the correct behavior. Reissuing an ID that might already have been used is far worse than skipping one.
The loss is small. With 7-character codes you have about 3.5 trillion IDs. Even if ten servers each crash once a day with a full 1,000-ID block lost, that is 10,000 IDs per day.
Choosing a block size
- Too small: the coordinator gets many requests, which is the original problem again.
- Too large: each crash wastes more IDs, and a freshly started server holds a large share of the space.
A block sized to a few seconds to a few minutes of that server's peak write rate is a reasonable starting point.
Making the coordinator reliable
The coordinator is still a single point of failure, but its failure mode is milder. Servers keep issuing IDs from their current blocks, so a short coordinator outage does not stop writes. Run the coordinator on a replicated database, or use a consensus store such as ZooKeeper or etcd. You must ensure that after a failover the new primary never hands out a block that the old primary already leased. Asynchronous replication can violate this, so use synchronous replication for this one row, or add a safety margin when promoting a replica.
Snowflake-style IDs
A different approach removes the coordinator from the write path entirely. Each ID is built from parts that are unique by construction. The Twitter Snowflake layout packs a 64-bit integer like this:
| Field | Bits | Purpose |
|---|---|---|
| Sign | 1 | Always 0, keeps the number positive |
| Timestamp | 41 | Milliseconds since a custom epoch, about 69 years |
| Worker ID | 10 | Identifies the server, up to 1,024 workers |
| Sequence | 12 | Counter within one millisecond, up to 4,096 IDs |
Two servers cannot produce the same ID because their worker IDs differ. One server cannot repeat an ID because the timestamp and sequence only move forward.
import threading
import time
class Snowflake:
EPOCH_MS = 1_700_000_000_000 # custom epoch, choose once and never change
WORKER_BITS = 10
SEQ_BITS = 12
def __init__(self, worker_id: int):
if not 0 <= worker_id < (1 << self.WORKER_BITS):
raise ValueError("worker_id out of range")
self._worker = worker_id
self._last_ms = -1
self._seq = 0
self._lock = threading.Lock()
def next_id(self) -> int:
with self._lock:
now = int(time.time() * 1000)
if now < self._last_ms:
raise RuntimeError("clock moved backwards")
if now == self._last_ms:
self._seq = (self._seq + 1) & ((1 << self.SEQ_BITS) - 1)
if self._seq == 0: # sequence exhausted this ms
while now <= self._last_ms:
now = int(time.time() * 1000)
else:
self._seq = 0
self._last_ms = now
return (
((now - self.EPOCH_MS) << (self.WORKER_BITS + self.SEQ_BITS))
| (self._worker << self.SEQ_BITS)
| self._seq
)
gen = Snowflake(worker_id=7)
a, b = gen.next_id(), gen.next_id()
print(a < b, a.bit_length()) # True, and about 52 bits for a recent epochThe cost for a URL shortener
Snowflake IDs are excellent for tweets and orders, but they fit short links poorly. A 41-bit timestamp plus 22 more bits gives numbers near 2^52 to 2^63. In base62 that is 9 to 11 characters, well beyond the 7 you planned. Short links exist to be short.
Snowflake also depends on clocks. If NTP steps a server's clock backwards, the generator above refuses to issue IDs. A worse design would carry on and risk duplicates. You also need a way to assign worker IDs without clashes, which brings back a small coordinator.
For a URL shortener, range allocation usually wins because the codes stay short.
Sequential codes are guessable
Counter-based codes have a side effect. If your code is aZ3 today, aZ4 exists and belongs to someone else. Anyone can walk the whole space and read other people's links. The abuse chapter covers this in more detail. The usual fix is to scramble the number before encoding it. Multiply by a constant that is coprime to 62^7, then take the result modulo 62^7. This gives a one-to-one mapping, so uniqueness is preserved while the output looks random.
Choosing between them
- Pick range allocation when you want short, collision-free codes and can run a small, reliable coordinator.
- Pick Snowflake IDs when you need roughly time-ordered IDs and do not care about code length.
- Pick random or hash codes when you want zero coordination and can afford a unique-constraint retry on collision.
Exercise
Your service has 20 write servers, each leasing blocks of 5,000 IDs. Each server restarts once per day and loses, on average, half a block. How many IDs are lost per day, and about how many days of this loss would it take to use up 1% of the 62^7 (about 3.5 trillion) code space?
Show answer
Each server loses about 2,500 IDs per day, so 20 servers lose about 50,000 per day. One percent of 3.5 trillion is 35 billion. Dividing 35,000,000,000 by 50,000 gives 700,000 days, nearly 1,900 years. Lost blocks are not a practical concern at this scale. The real costs of large blocks are IDs concentrated on one server and larger gaps in the sequence.
Exercise
A Snowflake-style generator sees its server clock jump backwards by 2 seconds. Why does the code above raise an error instead of continuing, and what is one safe way to recover?
Show answer
After a backwards jump, the timestamp and sequence could repeat a combination that was already issued, which produces duplicate IDs. Raising an error avoids that. Safe recoveries include waiting until the clock passes the last-used timestamp before issuing again, or removing the worker from rotation until the clock is corrected.