Sub topic 10
Allocating unique IDs across many servers
This chapter assumes you have read the chapters on base62 encoding and counter-based code generation. It also assumes you know basic database transactions.
The problem
A counter-based generator gives each new URL the next integer and encodes it in base62. That works on one server. With ten API servers behind a load balancer, each one running its own counter, two servers will soon hand out ID 41 and create the same short code.
You need a way for many servers to produce IDs that never overlap, without making every request wait on one machine.
Three approaches
Central counter (ticket server). One database row or service increments atomically and returns the next number. It is simple and the IDs are gapless. Every write pays a network round trip, and the counter is a single point of failure.
Range allocation. Each server asks a coordinator for a block of IDs, for example 1,000,000 at a time. It then hands out IDs from that block in memory. It contacts the coordinator only when the block runs out. The coordinator can be a database row updated in a transaction, or a store such as etcd or ZooKeeper.
Snowflake-style IDs. Each server builds a 64-bit ID from three parts: a timestamp, a machine number, and a per-millisecond sequence. Servers never talk to each other, so no coordinator is needed.
A range allocator
The coordinator below uses a lock to stand in for a database transaction. The allocator is thread-safe within one server.
import threading
class Coordinator:
"""Stands in for a database row or etcd key that hands out ID blocks."""
def __init__(self, block_size: int = 1000):
self.block_size = block_size
self._next = 0
self._lock = threading.Lock()
def lease_block(self) -> range:
with self._lock:
start = self._next
self._next += self.block_size
return range(start, start + self.block_size)
class IdAllocator:
def __init__(self, coordinator: Coordinator):
self.coordinator = coordinator
self._block = iter(())
self._lock = threading.Lock()
def next_id(self) -> int:
with self._lock:
try:
return next(self._block)
except StopIteration:
self._block = iter(self.coordinator.lease_block())
return next(self._block)
coord = Coordinator(block_size=1000)
a, b = IdAllocator(coord), IdAllocator(coord)
print(a.next_id(), b.next_id(), a.next_id()) # 0 1000 1The coordinator is the only shared state, and it is touched once per block. With a block of 1,000,000, a server writing 100 links per second contacts it about once every three hours.
Trade-offs
| Approach | Coordinator needed | Code length | Main risk |
|---|---|---|---|
| Central counter | Every request | Short | Bottleneck, single point of failure |
| Range allocation | Once per block | Short | Wasted IDs after a crash |
| Snowflake | None | Long | Clock problems |
A crashed server loses the unused part of its block. This is acceptable. Seven base62 characters hold 62**7, about 3.5 trillion IDs, so losing a few million is negligible. Do not try to recover them. Recovery needs extra bookkeeping, and that bookkeeping is a common source of duplicate IDs.
Snowflake IDs use up to 63 bits, which is about 11 base62 characters. That defeats the goal of short links. They also depend on clocks. If a server's clock moves backwards, it can repeat a timestamp and produce a duplicate. Snowflake suits systems where ID length matters less than avoiding a coordinator. For a URL shortener, range allocation is usually the better fit.
Make the coordinator durable and replicated, because it is the one component range allocation cannot do without. Short outages are tolerable, since servers keep serving from their current blocks.
Exercise
Three servers each lease blocks of 1,000,000 IDs. One server crashes after using 10,000 IDs from its block. How many IDs are wasted, and why is that acceptable with 7-character base62 codes?
Show answer
990,000 IDs are wasted (1,000,000 minus 10,000). The code space is 62**7, about 3.5 trillion, so this loses roughly 0.00003% of it. Skipping the lost IDs is cheaper and safer than tracking them for reuse.