Courses / System Design Interview / Chapter 11
Module 2 · Building Blocks I: Names, Traffic and Data · Chapter 11 of 49
Unique IDs: Sequencers, UUIDs and Snowflake IDs
Builds on Core Concepts: RPCs, Consistency, Failures and Time, Building Blocks: The Parts Every Design Reuses and Design a Distributed Key-Value Store. Next up: Distributed Monitoring: Metrics, Logs and Traces.
Part 1 · What an ID must guarantee
Why IDs are a design problem
Every order, message, post and payment needs an identifier, and in a system with many servers the question is who hands them out. A unique ID names exactly one record and never repeats, and a program that creates IDs is called a sequencer or an ID generator.
On one database with one table the answer is easy: let the database count. The trouble starts when several application servers, several database shards or several data centres all create records at the same moment. They cannot ask one central counter for every ID without that counter becoming a bottleneck and a single point of failure. So the design question is how to produce IDs that stay unique across many machines with little or no coordination.
Requirements differ by product, and writing them down narrows the choices. A payment id must never repeat. A feed of posts is read newest first, so IDs that sort by creation time save a separate time column and a sort. A public link should not let a visitor guess the next order. Database indexes work best when new keys land at the end and not scattered around the table. And size matters: a 64-bit number fits in a machine word and takes half the space of a 128-bit one, in every index and every row that refers to it.
| Property | Why it matters |
|---|---|
| Unique | Two records must never share an ID, across all machines and over time |
| Roughly time-ordered | Newest-first reads and range scans on a time window need no extra sort |
| Compact | A 64-bit key is half the size of a 128-bit one in every index |
| No central coordination | Generation keeps working when one machine or link is down |
| Hard to guess | Sequential public IDs let anyone enumerate your records |
When random IDs collide
The simplest way to avoid coordination is to pick IDs at random. Two machines that never talk can still create IDs, and a collision is possible only if two random picks happen to match. How likely that is follows the birthday bound: with n IDs drawn uniformly from 2 to the power b possible values, the chance that at least two match is about 1 - e^(-n(n-1) / 2^(b+1)). It grows with the square of n, which is why random IDs of the wrong size fail sooner than intuition suggests.
import math def p_collision(n_ids, bits): """Chance that two of n_ids random IDs match (birthday bound).""" return -math.expm1(-n_ids * (n_ids - 1) / 2 / 2.0**bits) for bits in (32, 64, 122): for n in (10**5, 10**9): print(f"{bits:3} bits, {n:>13,} IDs: " f"chance of a duplicate {p_collision(n, bits):.3g}")
birthday.py: chance of any duplicate among random IDs
32 bits, 100,000 IDs: chance of a duplicate 0.688 32 bits, 1,000,000,000 IDs: chance of a duplicate 1 64 bits, 100,000 IDs: chance of a duplicate 2.71e-10 64 bits, 1,000,000,000 IDs: chance of a duplicate 0.0267 122 bits, 100,000 IDs: chance of a duplicate 9.4e-28 122 bits, 1,000,000,000 IDs: chance of a duplicate 9.4e-20
Python 3.12.10 on this machine. Deterministic arithmetic.
A random 32-bit ID is hopeless: with only 1 lakh IDs issued the chance of a duplicate is already 69 percent. A random 64-bit ID is safe for small systems and uncomfortable for large ones, with a 2.7 percent chance of a duplicate after 100 crore IDs. A random 122-bit value, the number of random bits in a version 4 UUID, has a chance of about 9 in 10^20 after 100 crore, which is negligible.
The calculation shows what coordination-free generation costs. Either the ID is big enough that collisions do not happen, as with UUIDs, or part of the ID is assigned to the generator and time so that collisions cannot happen, as with Snowflake-style IDs. The middle ground, a random ID that is too short to be safe, is the one that fails in production.
A team plans random 48-bit IDs for a table that will reach 1 crore rows. Is that safe?
- No. The birthday bound gives about a 16 percent chance of at least one duplicate: 1 - e^(-n(n-1)/2^49) with n = 1 crore is 0.163.
- The chance grows with the square of the row count, so a 64-bit or 122-bit random ID, or a coordinated scheme, is needed.
Part 2 · Auto-increment and range allocation
A counter in the database
The oldest approach is a counter in a database. A column declared as auto-increment, or a database sequence, hands out 1, 2, 3 and so on. IDs are small, ordered, and perfect for range scans. The database serialises the increments, so uniqueness is guaranteed as long as there is one counter.
The limits are the ones above. There is a single counter, so there is one machine that every insert depends on. IDs reveal how many records exist, which leaks business volume and invites enumeration. And when data is split across shards, each shard counting for itself produces the same IDs on different shards, which collide when the data is merged.
A common patch is to give each of several databases a different starting point and a step equal to the number of databases: database 1 hands out 1, 4, 7 and database 2 hands out 2, 5, 8. IDs stay unique, but they are no longer in time order across the machines, and adding a database later means changing the step for all of them. Note also that databases do not promise gapless sequences. In PostgreSQL, for example, a value taken from a sequence is not returned if the transaction rolls back, so gaps appear. Use IDs for identity, not for counting rows.
import sqlite3 db = sqlite3.connect(":memory:", isolation_level=None) db.execute( "CREATE TABLE orders " "(id INTEGER PRIMARY KEY AUTOINCREMENT, item TEXT)" ) for item in ["dosa", "idli", "vada"]: cur = db.execute("INSERT INTO orders (item) VALUES (?)", (item, )) print("auto-increment gave", cur.lastrowid)
counter.py: auto-increment in SQLite
Allocating ranges
A better answer keeps a central counter but touches it rarely. In range allocation, each application server asks the counter for a whole block of IDs, say 1,000, and then hands them out from memory with no further network calls. The central counter is hit once per thousand IDs instead of once per ID, so it is no longer a bottleneck, and a short outage of the counter is invisible while servers still have IDs left.
The block is reserved by one atomic update. The program below keeps a table with the next free start value. A server runs UPDATE ... RETURNING to move the start forward by the block size and read back the new value, in one statement, so two servers can never be given the same block. SQLite supports RETURNING from version 3.35, and Python 3.12 ships with a newer SQLite.
db.execute(
"CREATE TABLE id_ranges (name TEXT PRIMARY KEY, next_start INTEGER)"
)
db.execute("INSERT INTO id_ranges VALUES ('orders', 1)")
class RangeAllocator:
"""An app server takes a block of IDs, then serves from memory."""
def __init__(self, name, size=1000):
self.name, self.size, self.cur, self.end = name, size, 0, 0
def next_id(self):
if self.cur >= self.end:
row = db.execute(
"UPDATE id_ranges SET next_start = next_start + ? "
"WHERE name = ? RETURNING next_start",
(self.size, self.name)).fetchone()
self.cur, self.end = row[0] - self.size, row[0]
print(f" fetched block [{self.cur}, {self.end})")
self.cur += 1
return self.cur - 1
counter.py: a range allocator
a, b = RangeAllocator("orders"), RangeAllocator("orders") print("server A:", a.next_id(), a.next_id()) print("server B:", b.next_id(), b.next_id()) print("server A:", a.next_id()) print("A restarts, its block is lost:") a = RangeAllocator("orders") print("server A after restart:", a.next_id())
counter.py: two servers and a restart
auto-increment gave 1 auto-increment gave 2 auto-increment gave 3 fetched block [1, 1001) server A: 1 2 fetched block [1001, 2001) server B: 1001 1002 server A: 3 A restarts, its block is lost: fetched block [2001, 3001) server A after restart: 2001
Python 3.12.10 on this machine. Deterministic.
What the run shows
The first three lines of output come from the auto-increment table: 1, 2 and 3. Then server A asked the counter once, received IDs 1 to 1,000, and handed out 1 and 2 locally. Server B asked next and received 1,001 to 2,000. Server A's third ID was 3, and B's were 1,001 and 1,002. The IDs from the two servers interleave in time but not in number, so they are unique and only roughly ordered.
The last lines show the cost. When server A restarted, it asked for a new block and received 2,001 to 3,000. The remaining 997 unused IDs of its first block were never used again. Gaps of that kind are harmless for an identifier, and the unused IDs cannot be reclaimed safely, because the restarted server does not know which ones it had already handed out.
Range allocation is simple and keeps IDs compact. It still needs a central counter that must itself be made reliable, with replication and failover, and it still orders IDs only by block. Systems that need IDs to sort by time without any central service use the schemes in the next lessons.
How many requests does a server send to the central counter per 1,000 IDs with a block size of 1,000?
- One. All other IDs are handed out from the block in memory.
Why must the block reservation be one atomic statement?
- If two servers could read the same start value before either wrote the new one, they would receive overlapping blocks and produce duplicate IDs.
What happened to IDs 4 to 1,000 of server A's first block when A restarted?
- They were never used. A asked for a new block, 2,001 to 3,000, because it could not know which IDs it had already issued.
Part 3 · UUIDs: version 4 and version 7
Random and time-ordered UUIDs
A UUID (universally unique identifier) is a 128-bit value, written as 32 hexadecimal digits in groups, defined in RFC 9562. Any server can create one without asking anyone. The specification defines several versions that fill the bits differently.
Version 4 is almost entirely random. Of the 128 bits, 6 are fixed to mark the version and the variant, and the remaining 122 are random. With 122 bits, the collision chance in the previous lesson's table is negligible, and nobody can guess a UUID. Version 4 is the default in many libraries, and Python's uuid.uuid4() creates one.
Version 7 keeps the idea and puts time first. Its layout is a 48-bit Unix timestamp in milliseconds, then 4 bits for the version, 12 random bits, 2 bits for the variant and 62 more random bits. The RFC allows some of the bits after the timestamp to carry a counter, to keep IDs created in the same millisecond in order. Because the timestamp is in the most significant bits, version 7 IDs sort by creation time, whether compared as bytes or as text.
Python 3.12, used here, has no uuid7. The function was added to the uuid module in Python 3.14, and its documentation says it uses a 42-bit counter to stay monotonic within a millisecond. The program below builds one by hand from the layout in the RFC. It fills the timestamp, sets the version bits to 7 and the variant bits to binary 10, and fills the rest from the operating system's random source. It then decodes the timestamp back from the ID and tests whether IDs created in order also sort in order.
import os, time, uuid from datetime import datetime, timezone def uuid7(ms=None): """RFC 9562 UUIDv7: 48-bit Unix ms, version, random bits.""" ms = int(time.time() * 1000) if ms is None else ms # 80 random bits rand = int.from_bytes(os.urandom(10), "big") rand_a = (rand >> 68) & 0xFFF # 12 bits rand_b = rand & ((1 << 62) - 1) # 62 bits value = (ms << 80) | (0x7 << 76) | (rand_a << 64) | ( 0b10 << 62) | rand_b return uuid.UUID(int=value) def timestamp_of(u): return datetime.fromtimestamp((u.int >> 80) / 1000, tz=timezone.utc)
uuids.py: UUIDv7 by hand
a = uuid.uuid4() print("uuid4 :", a, "version", a.version) b = uuid7(1_790_000_000_000) print("uuid7 :", b, "version", b.version) print("variant:", b.variant) print("decoded:", timestamp_of(b).isoformat()) ids = [uuid7(1_790_000_000_000 + 7 * i) for i in range(5)] print("created in order, sorted as text:", [str(x) for x in ids] == sorted(str(x) for x in ids)) shuffled = [uuid.uuid4() for _ in range(5)] print("uuid4 created in order, sorted: ", [str(x) for x in shuffled] == sorted(str(x) for x in shuffled))
uuids.py: the sorting test
Reading the output
The version 4 ID reports version 4. The version 7 ID reports version 7, and decoding its first 48 bits gives back the millisecond we put in, 2026-09-21 14:13:20 UTC. Python labels the variant 'specified in RFC 4122'. That is its name for the standard variant, the one with the bits 10, and RFC 9562 keeps the same variant.
Five version 7 IDs created in time order sorted into the same order as text. Five version 4 IDs created in order did not, because they carry no time. This test uses five IDs, so a random sample could pass by luck once in 120 runs; the point is the structure, not the sample.
Only the timestamp gives order. Two version 7 IDs created in the same millisecond have random bits after the timestamp and can sort either way. The RFC gives ways to fix this with a counter in the random bits, and says implementations should check that each new ID is greater than the previous one. A generator that follows those rules is monotonic within one process. Across machines, IDs are ordered only to millisecond accuracy, and to the accuracy of their clocks.
Why ordering matters to the database
Time order is not only about sorting. Most databases store a table or an index as a B-tree, a sorted tree of pages. Inserting a random key lands in a random leaf page. Over time every page is touched, the working set no longer fits in memory, and pages split in the middle. Inserting keys that increase puts each new row at the right edge, so the same few pages stay in memory. RFC 9562 makes this point: time-ordered UUIDs benefit from better index locality than random ones.
The next program measures a version of this in SQLite. It inserts 3 lakh rows into a table keyed by a 16-byte value, once with random keys and once with keys that start with a millisecond timestamp. The table is in memory, so the effect is smaller than it would be on a disk with memory pressure.
import random, sqlite3, time, uuid def make(kind, n): r = random.Random(1) return [ (uuid.UUID( int=r.getrandbits(128)).bytes if kind == "random" else (1_790_000_000_000 + i).to_bytes(6, "big") + r.randbytes(10)) for i in range(n) ] for kind in ("random", "time-ordered"): db = sqlite3.connect(":memory:") db.execute( "CREATE TABLE t (id BLOB PRIMARY KEY, body BLOB) WITHOUT ROWID" ) rows = make(kind, 300_000) t = time.perf_counter() db.executemany("INSERT INTO t VALUES (?, zeroblob(100))", [(r, ) for r in rows]) db.commit() print( f"{kind:13} 300,000 inserts: {time.perf_counter() - t:.2f} s") pages = db.execute("PRAGMA page_count").fetchone()[0] print(f"{'':13} pages used: {pages}")
uuidindex.py: random keys against time-ordered keys
random 300,000 inserts: 0.56 s pages used: 10249 time-ordered 300,000 inserts: 0.27 s pages used: 10359
Python 3.12.10 on this machine. The timings vary from run to run.
On this machine, the time-ordered inserts finished in about half the time of the random ones, 0.27 s against 0.56 s. In three more runs the time-ordered inserts took between a half and two thirds of the random time. The page counts are nearly equal, so the saving comes from where the inserts land and not from the size of the data. The difference would be larger on a database whose index no longer fits in memory.
Which bits make a version 7 UUID sortable by time?
- The first 48 bits are the Unix time in milliseconds, in the most significant position, so comparing the IDs compares their timestamps first.
Part 4 · Snowflake-style IDs
Time, machine and sequence
A Snowflake-style ID packs three fields into a 64-bit number: a timestamp, a machine number and a per-millisecond counter. The design is from a Twitter service, Snowflake, whose README states the layout: 41 bits of time in milliseconds from a custom epoch, 10 bits for a configured machine ID, and 12 bits for a sequence number. The project has since been archived, and the layout remains a widely used pattern.
Putting the timestamp in the highest bits makes the IDs sort by time, as with version 7 UUIDs, in half the size. The machine bits make two generators produce different IDs even in the same millisecond, with no communication. The sequence is a counter that starts at 0 in each new millisecond, so one machine can produce several IDs per millisecond. Together the three fields make an ID unique as long as no two generators share a machine number.
Fleet capacity at full rate: 4.2 B /s (far above what a product needs)
Read it as steps
Each field's width fixes how long the IDs last and how fast they can be made.
The widths set the limits. 41 bits of milliseconds is about 69.7 years from the epoch, so the epoch is chosen near the system's launch and not at 1970. 10 bits allow 1,024 generators. 12 bits allow 4,096 IDs per millisecond per generator, or about 41 lakh per second. The fleet as a whole could issue far more than any real product needs.
ms_per_year = 365.25 * 24 * 3600 * 1000 print( f"41 bits of ms : {2**41:,} ms = {2**41 / ms_per_year:.1f} years" ) print(f"10 machine bits: {2**10:,} generators") print(f"12 sequence bits: {2**12:,} IDs per ms per generator") print(f"per generator : {2**12 * 1000:,} IDs per second") print(f"whole fleet : {2**12 * 1000 * 2**10:,} IDs per second") print( f"total bits : {1 + 41 + 10 + 12} (one sign bit stays unused)" )
bits.py: the bit budget
A generator you can read
The program below is a generator in 35 lines. It takes the current time in milliseconds from a clock function, so the next lesson can replace the clock with a controlled one. If the clock still reads the same millisecond as the last ID, the sequence goes up by one, and when it wraps past 4,095 the generator waits for the next millisecond. If the clock has moved forward, the sequence restarts at 0. If the clock has moved backward, the generator refuses to issue an ID, which is the same policy the Snowflake README describes.
EPOCH = 1_788_000_000_000 # our own custom epoch, in Unix ms TIME_BITS, MACHINE_BITS, SEQ_BITS = 41, 10, 12 class Snowflake: def __init__(self, machine, clock): # clock() returns ms self.machine, self.clock = machine, clock self.last, self.seq = -1, 0 def next_id(self): now = self.clock() if now < self.last: raise RuntimeError( f"clock moved back {self.last - now} ms, refusing") if now == self.last: self.seq = (self.seq + 1) & ((1 << SEQ_BITS) - 1) # 4,096 used this ms: wait if self.seq == 0: while now <= self.last: now = self.clock() else: self.seq = 0 self.last = now return ((now - EPOCH) << (MACHINE_BITS + SEQ_BITS)) \ | (self.machine << SEQ_BITS) | self.seq
snowflake.py: the 41/10/12 generator
def decode(i): return { "ms": (i >> 22) + EPOCH, "machine": (i >> 12) & 0x3FF, "seq": i & 0xFFF }
snowflake.py: decoding an ID
decode reverses the packing with shifts and masks. The demo below runs the generator against a fake clock that stays on one millisecond, to see the sequence count up, and later against a clock that stays still for 4,097 reads, to see the rollover.
from snowflake import Snowflake, decode, EPOCH # a fake clock we control t = [EPOCH + 5_000] gen = Snowflake(machine=7, clock=lambda: t[0]) a = gen.next_id() b = gen.next_id() print(a, decode(a)) print(b, decode(b)) t[0] += 1 c = gen.next_id() print(c, decode(c)) print("increasing:", a < b < c)
snowdemo.py: IDs in one millisecond and the next
Sequence rollover
# 4,096 IDs in one millisecond: the 4,097th needs the clock to move. now = [EPOCH + 6_000] reads = [0] def clock(): reads[0] += 1 if reads[0] > 4097: # stuck for 4,097 reads now[0] += 1 return now[0] g2 = Snowflake(1, clock) ids = [g2.next_id() for _ in range(4097)] print("distinct IDs from 4,097 calls:", len(set(ids))) print("last ID is later than the first by:", decode(ids[-1])["ms"] - decode(ids[0])["ms"], "ms") print("last seq:", decode(ids[-1])["seq"])
snowdemo.py: 4,097 IDs in one millisecond
20971548672 {'ms': 1788000005000, 'machine': 7, 'seq': 0} 20971548673 {'ms': 1788000005000, 'machine': 7, 'seq': 1} 20975742976 {'ms': 1788000005001, 'machine': 7, 'seq': 0} increasing: True distinct IDs from 4,097 calls: 4097 last ID is later than the first by: 1 ms last seq: 0
Python 3.12.10 on this machine. Deterministic: the clock is simulated.
The first two IDs share the millisecond 1,788,000,005,000 and machine 7, and differ only in the sequence, 0 and 1. After the clock moved one millisecond, the next ID had sequence 0 again and was larger. The three IDs are increasing.
In the second part, 4,097 calls arrived while the clock was stuck on one millisecond. The first 4,096 used sequence values 0 to 4,095. The 4,097th wrapped the sequence to 0, so the generator waited until the clock advanced, and its ID carries the next millisecond, one later than the first. All 4,097 IDs are distinct.
Watch for the machine number inside each ID: it keeps generators apart
Read it as steps
Part 5 · Clocks that go backwards, and causal order
When the clock steps back
A time-based generator trusts its clock, and clocks are adjusted. The time service that keeps machines in step can move a clock backwards by a few milliseconds when it finds the machine was ahead. If the generator then read the smaller time and issued an ID with the same sequence it used before, it could produce a duplicate or an ID that sorts earlier than one it had already issued.
The generator has to choose a policy. It can refuse to issue IDs until the clock catches up, which is what the Snowflake README describes: it refuses to generate IDs until a time after the last one it generated. It can wait for the clock itself in a loop. It can keep using the last timestamp and increase the sequence, which keeps IDs unique and increasing but risks running out of sequence values if the clock stays behind. For UUIDs, RFC 9562 says implementations should check that each new ID is greater than the previous one, and that if it is not they may reuse the previous timestamp and increment the counter. Whatever the choice, the rule is the same: never issue an ID at or below the last one.
The program below uses the generator from the previous lesson with a controlled clock. It issues one ID, moves the clock back by 4 ms, and asks for another, which is refused. A second function then applies a waiting policy: it retries while the clock advances until it reaches the last timestamp.
from snowflake import Snowflake, EPOCH t = [EPOCH + 10_000] gen = Snowflake(3, lambda: t[0]) print("id 1:", gen.next_id()) # the time service steps the clock back 4 ms t[0] -= 4 try: gen.next_id() except RuntimeError as e: print("error:", e) def next_id_waiting(gen, t): """Wait policy: let our fake clock advance until it catches up.""" while True: try: return gen.next_id() except RuntimeError: t[0] += 1 # time passing print("id 2 after waiting:", next_id_waiting(gen, t), "clock now", t[0] - EPOCH, "ms")
clockback.py: refuse, then wait
id 1: 41943052288 error: clock moved back 4 ms, refusing id 2 after waiting: 41943052289 clock now 10000 ms
Python 3.12.10 on this machine. Deterministic: the clock is simulated.
Reading the run
The first ID came out normally. When the clock went back by 4 ms, the generator raised an error that said so, and issued nothing. After the waiting function let the clock advance, the second ID was issued, one more than the first. That is possible because the clock read the same millisecond as the first ID again, so the sequence went from 0 to 1.
Refusing is the safest policy and the one to prefer when callers can retry. Waiting is friendlier but blocks the caller for as long as the step, which is short for the small adjustments of a time service and long after a bad correction or a virtual machine restored from a snapshot. The Snowflake README adds that it is better still to run the time service in a mode that never moves the clock backwards.
Notice what the clock gives and does not give. It gives IDs that sort in the order of real time, as far as the clocks agree. Two machines with clocks that differ by 20 ms can assign a smaller ID to an event that happened later in real time. For identity this is fine. For deciding whether one event could have caused another, it is not.
Causal order with Lamport clocks
The core concepts chapter defined the happened-before relation and the Lamport clock: a counter per process that every message carries, where a receiver sets its counter above the one it received. A Snowflake-style generator can borrow that receive rule for its time field. When a service reads an ID from a message, it never issues an ID below that ID's millisecond plus one, even if its own clock reads earlier.
The program below sets machine A's clock 20 ms fast and machine B's clock right. A posts a question. Five milliseconds later in real time, B receives it and posts a reply. The plain generator stamps the reply with B's own clock. The causal one first observes the question's ID. The class leaves out sequence overflow to stay short.
from snowflake import Snowflake, decode, EPOCH, MACHINE_BITS, SEQ_BITS class Causal(Snowflake): """Snowflake plus Lamport's receive rule on the time field.""" floor = 0 def observe(self, seen): # never issue below an ID we have seen: at least its ms + 1 self.floor = max(self.floor, decode(seen)["ms"] + 1) def next_id(self): # sequence overflow left out to keep it short now = max(self.clock(), self.floor, self.last) self.seq = self.seq + 1 if now == self.last else 0 self.last = now return ((now - EPOCH) << (MACHINE_BITS + SEQ_BITS)) \ | (self.machine << SEQ_BITS) | self.seq
causal.py: a generator with Lamport's receive rule
for kind in (Snowflake, Causal): real = [EPOCH + 50_000] # true time; A's clock runs 20 ms fast a = kind(1, lambda: real[0] + 20) b = kind(2, lambda: real[0]) q = a.next_id() # A posts a question real[0] += 5 # 5 ms later, B receives it and replies if kind is Causal: b.observe(q) r = b.next_id() q_ms, r_ms = decode(q)["ms"] - EPOCH, decode(r)["ms"] - EPOCH print(f"{kind.__name__:9} question {q_ms} ms, reply {r_ms} ms,", "reply sorts after:", r > q)
causal.py: a question and its reply, with both generators
Snowflake question 50020 ms, reply 50005 ms, reply sorts after: False Causal question 50020 ms, reply 50021 ms, reply sorts after: True
Python 3.12.10 on this machine. Deterministic: the clocks are simulated.
Reading the Lamport run
With plain clocks the question carried millisecond 50,020, from A's fast clock, and the reply carried 50,005, from B's correct clock. The reply was written later and because of the question, yet its ID is smaller, so a thread sorted by ID shows the answer above the question. With the receive rule, B stamped the reply 50,021, one past the question, and the reply sorted after it.
The fix has a cost and a limit. B's next IDs carry a time ahead of its own clock until its own clock reaches 50,021, 16 ms later here, so the time in an ID is no longer exactly the creation time. The jump is about the skew of the fastest clock whose IDs reach B, plus a millisecond. And the rule orders only what B has seen: two posts on machines that never exchanged a message still sort by their clocks, which is the best any ID can do for concurrent events.
This is the same trade the key-value store chapter makes with vector clocks, from the other side. Vector clocks detect that two writes were concurrent. A Lamport-style rule cannot detect that, but it fits in the 64 bits an ID already has and keeps every reply after the message it answers.
Why must a generator refuse an ID when its clock reads less than the last timestamp?
- Issuing one could repeat an ID or place it before IDs already issued. Refusing keeps IDs unique and increasing.
In the run, why did the plain reply sort before the question it answered?
- A's clock ran 20 ms fast, so the question carried 50,020. B's correct clock gave the reply 50,005. Sorting by ID follows the clocks, not cause and effect.
A service applies the receive rule and starts issuing IDs ahead of its own clock. What limits how far ahead they run?
- It only raises its floor to an ID it has seen plus one millisecond, so it runs ahead by about the skew of the fastest clock whose IDs reach it.
- Once its own clock passes that floor, it uses its own clock again.