Sub topic 4
Handing out blocks of IDs to reduce coordination
This chapter assumes you have read the previous chapter on central counters. You should know why a single database sequence is simple but becomes a bottleneck and a single point of failure. It also assumes you can read basic Python and SQL.
A central counter hands out one ID per network round trip. Block allocation changes that. A generator asks the counter for a whole range of IDs in one call, then hands those IDs out locally with no further network traffic. Coordination happens once per block instead of once per ID.
The core idea
Suppose the counter currently stores 1. A generator asks for 1,000 IDs. The counter atomically moves its value to 1001 and replies "you own 1 up to, but not including, 1001". From then on the generator increments a local variable. It contacts the counter again only when it has used all 1,000 IDs.
Two properties make this safe:
- The counter's update is atomic, so two generators can never receive overlapping ranges.
- Each generator hands out IDs only from a range it owns exclusively, so no two generators can produce the same ID.
Uniqueness therefore reduces to one narrow guarantee: the allocation step never gives the same range twice.
A ticket server in SQL
A ticket server is a small, dedicated service whose only job is to hand out numbers. The best-known design comes from Flickr. It uses a database table with an auto-increment column and a trick that keeps the table at one row:
CREATE TABLE tickets (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
stub CHAR(1) NOT NULL DEFAULT '',
PRIMARY KEY (id),
UNIQUE KEY stub (stub)
) ENGINE = InnoDB;
REPLACE INTO tickets (stub) VALUES ('a');
SELECT LAST_INSERT_ID();REPLACE INTO deletes the old row with stub = 'a' and inserts a new one. The auto-increment counter keeps climbing, so the table never grows. LAST_INSERT_ID() returns the value for your own connection, so concurrent clients do not see each other's numbers.
That example still allocates one ID per call. To allocate blocks, advance the counter by the block size in a single atomic statement. In PostgreSQL:
CREATE TABLE id_blocks (
name TEXT PRIMARY KEY,
next_id BIGINT NOT NULL
);
INSERT INTO id_blocks (name, next_id) VALUES ('orders', 1);
UPDATE id_blocks
SET next_id = next_id + 1000
WHERE name = 'orders'
RETURNING next_id - 1000 AS first_id, next_id AS end_id;The UPDATE takes a row lock, so concurrent callers queue and each receives a distinct range. The first caller gets first_id = 1, end_id = 1001, and the range is half-open: it includes 1 and excludes 1001. The name column lets one table serve several independent ID sequences.
A working generator
The Python below simulates the pattern in one process. TicketServer stands in for the durable counter. BlockIdGenerator is the client that caches a block.
import threading
class TicketServer:
"""Stands in for a durable counter such as one database row."""
def __init__(self, start=1):
self._next = start
self._lock = threading.Lock()
self.calls = 0
def allocate(self, size):
# Atomic: returns the half-open range [first, first + size).
with self._lock:
first = self._next
self._next += size
self.calls += 1
return first, first + size
class BlockIdGenerator:
def __init__(self, server, block_size=1000):
self._server = server
self._block_size = block_size
self._next = 0
self._end = 0 # empty block, so the first call fetches one
self._lock = threading.Lock()
def next_id(self):
with self._lock:
if self._next >= self._end:
self._next, self._end = self._server.allocate(self._block_size)
value = self._next
self._next += 1
return value
server = TicketServer()
gen_a = BlockIdGenerator(server)
gen_b = BlockIdGenerator(server)
ids = []
for _ in range(2500):
ids.append(gen_a.next_id())
ids.append(gen_b.next_id())
print("ids issued:", len(ids))
print("unique ids:", len(set(ids)))
print("server calls:", server.calls)Running it prints:
ids issued: 5000
unique ids: 5000
server calls: 6Compare this with a plain central counter. That design would have made 5,000 server calls. Here each generator needed three blocks, so the server saw six calls. The load on the counter dropped by a factor of roughly the block size.
Notice the order of the interleaved calls. gen_a and gen_b alternate, but the IDs they return do not alternate in value: one draws from a range near 1 and the other from a range near 1001. Section "What you give up" returns to this.
Choosing a block size
Block size trades coordination cost against waste and ordering.
| Block size | Server calls | Wasted IDs after a crash | Rough ordering across generators |
|---|---|---|---|
| Small (10) | Frequent | Few | Close to creation order |
| Medium (1,000) | Occasional | Up to 999 per generator | Loosely ordered |
| Large (1,000,000) | Rare | Up to about a million per generator | Poorly ordered |
Pick a block size from the numbers in your system, not by habit:
- Estimate the peak ID rate per generator, for example 2,000 IDs per second.
- Decide how long a generator may keep running if the ticket server is down. If you want 60 seconds of tolerance, the block must hold at least 120,000 IDs.
- Check that the wasted range after a crash is acceptable for your ID width. Waste is trivial in a 64-bit space and a real concern in a 32-bit one.
A larger block also gives you outage tolerance. A generator holding a nearly full block can keep serving IDs while the ticket server is unreachable. That is a real availability gain over a one-ID-per-call counter.
What you give up
Block allocation reduces coordination but does not remove it. These costs come with the pattern:
- Gaps. If a generator crashes or restarts, the unused part of its block is lost. IDs are unique but not contiguous. Never build logic that assumes "no gaps means no missing records".
- Weaker ordering. Within one generator, IDs increase. Across generators they do not follow creation time, because each generator draws from a different range. An ID of 2,050 may have been created before an ID of 1,010.
- A remaining single point of failure. The ticket server is still one component. If it fails permanently with no replica, no generator can get a new block.
- Predictability. IDs are small consecutive integers, so anyone who sees two of them can estimate how many records exist. The security chapter covers this.
Making the counter durable
The one rule that cannot bend: the counter's new value must be durably recorded before the old range is given to a client. If the server hands out 1 to 1000, crashes, and restarts with its counter still at 1 because the update was only in memory, it will give 1 to 1000 to someone else. That produces duplicates, the exact failure the pattern exists to avoid.
Use a database transaction, or a write that is flushed to disk, before replying. The UPDATE ... RETURNING statement above satisfies this, because the row change is committed with the transaction.
A crash in the other direction is harmless. If the server records the new value and then dies before replying, the client simply retries and receives a fresh range. The lost range is a gap, which is acceptable.
Scaling the ticket server
One ticket server limits both availability and throughput. The two usual remedies stay inside the block-allocation idea.
Several servers with interleaved ranges. Flickr ran two ticket servers, one issuing only odd numbers and one only even numbers. In MySQL this is configured with auto_increment_increment = 2 on both servers and auto_increment_offset = 1 on one and 2 on the other. Clients alternate between the servers, and if one is down, the other still works. Uniqueness holds because the two servers never produce the same parity. The cost is that the combined sequence is only roughly ordered, and adding a third server later means changing the increment, which is awkward on a live system.
Hi/lo allocation. The generator fetches a "hi" value from the counter, for example 7, and computes its own "lo" values locally from 0 to 999. IDs are hi * 1000 + lo. This is the same idea expressed as arithmetic, and some ORMs implement it for you. Fetching hi = 7 is equivalent to receiving the block 7000 to 7999.
Common errors
- Using a non-atomic read then write. Reading the counter and then writing it back as two statements lets two callers read the same value. Always use a single atomic update or a transaction with a lock.
- Treating gaps as bugs. Gaps from discarded blocks are normal. Do not retry or "fill" them.
- Sharing one block between threads without a lock. In the example,
next_idtakes a lock. Without it, two threads can read the same_nextand return duplicates. - Returning a block to the pool after a crash. Recovering and reusing the unused part of a block requires knowing exactly which IDs were used. Because that knowledge is usually lost with the process, discard the block.
- Sizing the block for the average rate. Size it for the peak rate and the outage window you want to survive.
When block allocation fits
Block allocation suits systems that want compact, integer, database-friendly IDs and can tolerate one small, replicated coordination service. It fits well when:
- IDs should be small, such as 64-bit integers, and keep good index locality within each generator.
- A brief ticket-server outage must not stop writes, so a cached block provides a buffer.
- Gaps are acceptable and global time ordering is not required.
It fits poorly when generators must work with no network access to anything, or when you need IDs that sort by creation time across the whole fleet. Random and time-based schemes serve those cases and are covered next.
Exercise
Four application servers each use a block size of 500 and each issue 1,200 IDs from a shared ticket server that started at 1. How many calls does the ticket server receive in total, and at most how many IDs are wasted if all four servers shut down now?
Show answer
Each server needs ceil(1200 / 500) = 3 blocks, so the ticket server receives 4 x 3 = 12 calls. Each server has used 1,200 of 1,500 reserved IDs, so 300 are unused per server. In total at most 4 x 300 = 1,200 IDs are wasted, and no more than that because each server's last block is partially used.
Exercise
A ticket server updates its counter in memory and writes it to disk only every 10 seconds. It crashes and restarts. Explain the failure and name a fix.
Show answer
After restart the counter reloads the last value written to disk, which may be up to 10 seconds old. Ranges handed out in that window are issued a second time, so two generators can produce the same IDs. The fix is to commit the new counter value durably, for example in a database transaction or a flushed write, before replying to the client with the range.
Exercise
Two generators each hold a block. Generator A holds 1 to 1000 and generator B holds 1001 to 2000. B creates a record, then A creates a record a second later. Which record has the larger ID, and what does this show about block allocation?
Show answer
B's record has the larger ID, since B draws from the higher range, even though A's record was created later. It shows that block allocation gives unique IDs that increase within one generator but do not sort by creation time across generators.