Sub topic 4
Handing Out Blocks of IDs to Reduce Coordination
This chapter assumes you know why a single central counter becomes a bottleneck and a single point of failure. It also assumes you are comfortable with relational primary keys and basic Python. Block allocation keeps the simplicity of a counter but contacts the central service far less often.
The idea
Instead of asking the central counter for one ID at a time, each node asks for a whole block. For example, a node requests 1,000 IDs. The counter reserves the range 5001 to 6000 and returns it. The node then hands out IDs from that range using only local memory. When the range runs out, the node asks for another block.
The central service now takes one call per 1,000 IDs instead of one call per ID. The load on it drops by a factor equal to the block size.
A ticket server
A service that only hands out ranges is often called a ticket server. Its state is one number: the next unreserved ID. Reserving a block means advancing that number by the block size, atomically.
In a relational database this is one row and one statement. The UPDATE makes the reservation atomic, because the database serializes concurrent updates to the same row.
import sqlite3
import threading
class TicketServer:
def __init__(self):
self.db = sqlite3.connect(":memory:", check_same_thread=False)
self.db.execute("CREATE TABLE ticket (next_id INTEGER NOT NULL)")
self.db.execute("INSERT INTO ticket VALUES (1)")
self.db.commit()
self.lock = threading.Lock()
def reserve(self, size):
with self.lock:
(start,) = self.db.execute("SELECT next_id FROM ticket").fetchone()
self.db.execute("UPDATE ticket SET next_id = next_id + ?", (size,))
self.db.commit()
return start, start + size - 1
class BlockAllocator:
def __init__(self, server, block_size=1000):
self.server = server
self.block_size = block_size
self.current = 0
self.last = -1
self.lock = threading.Lock()
def next_id(self):
with self.lock:
if self.current > self.last:
self.current, self.last = self.server.reserve(self.block_size)
value = self.current
self.current += 1
return value
server = TicketServer()
node_a = BlockAllocator(server, block_size=3)
node_b = BlockAllocator(server, block_size=3)
print(node_a.next_id(), node_a.next_id()) # 1 2
print(node_b.next_id()) # 4
print(node_a.next_id(), node_a.next_id()) # 3 7The last line shows the main property. Node A finishes its block (1 to 3) and then fetches the next free one (7 to 9), because node B already holds 4 to 6.
What you gain and what you give up
Block allocation reduces coordination but does not remove it. The trade-offs:
| Aspect | Effect |
|---|---|
| Load on the allocator | Divided by the block size |
| Availability | A node can keep issuing IDs while the allocator is down, until its block runs out |
| Uniqueness | Guaranteed, since ranges never overlap |
| Global ordering | Lost. IDs from different nodes interleave by block, not by time |
| Gaps | A node that crashes loses the unused part of its block |
| Size | Compact integers, like a counter |
Gaps are normal. If a node reserves 1,000 IDs, uses 10, and restarts, the other 990 are skipped. Do not treat IDs as gap-free, and do not rely on them to count rows.
Common errors
- Persisting the pointer too late. The allocator must durably record the new
next_idbefore returning the range. If it returns first and crashes, a restart can hand out the same range twice. - Reusing a block after restart. A node that saves its in-memory range and resumes it is safe only if the allocator also remembers that the range was given away. The simplest rule is to discard the old block and fetch a new one.
- Block size too small. You keep most of the original load.
- Block size too large. You waste more IDs on each crash, and in a fixed-width column you exhaust the space sooner.
- Assuming time order. A node holding an old block can issue a low ID after another node has issued a higher one created earlier. Never sort by ID to recover creation order.
The ticket server is still a single dependency, so run it with replication or failover. A common variation runs several ticket servers, each handing out IDs with a different offset and step (one issues odd numbers, one even). This removes the single point of failure at the cost of strict ordering.
Exercise
A node reserves the block 2001 to 3000, issues 40 IDs, and then crashes. After restart it asks the ticket server for a new block. Which range does the server return if no other node has reserved anything since, and what happens to IDs 2041 to 3000?
Show answer
The server returns 3001 to 4000, because its pointer was already advanced past 3000 when the first block was reserved. IDs 2041 to 3000 are never issued. They become a gap, which is acceptable because uniqueness is preserved and only gap-free numbering is lost.
Exercise
Why must the ticket server persist its new pointer before it replies with a range?
Show answer
If it replied first and then crashed before saving, it would restart with the old pointer and could give the same range to another node. That produces duplicate IDs.