Chapter 14 / 24 · System Design

Identity, time and unique IDs

Designing Dabba’s order id: unique without coordination, sorted by time, able to find its own shard, and careful about what it reveals.

An ID scheme decides three things: who is allowed to create identifiers without asking anyone, what an identifier reveals to whoever sees it, and how new identifiers behave in an index. This chapter designs Dabba’s order id with all three in view, because once order ids are printed on receipts, stored in other teams’ tables and pasted into support chats, changing the scheme is a multi-year project.

The trigger is the sharding chapter. Until now, order ids came from the one database’s auto-increment column. After the split, eight databases each have their own counter, and on the first evening two of them both issue order 48,213,007. The event log, the search index and the support tool all treat order id as unique, so the second order overwrites the first wherever they meet.

What an order id has to do

It helps to write the requirements down before comparing schemes, because each scheme is good at a different subset.

RequirementWhy Dabba needs it
Unique across all shards, without a network call per idPlacing an order should not depend on one more service being up
Tells us which shard holds the orderThe sharding chapter promised lookups by order id stay on one shard
Roughly ordered by creation timeIndex locality, and “newest first” lists without a separate sort
Fits in 64 bitsIt appears in every order, item, event and index row
Does not reveal business volumeCompetitors and journalists can place orders too
Can be read over the phoneSupport conversations start with “what is your order number?”

What auto-increment gets right, and what it leaks

The single-database counter was not a bad choice. It is compact, it is ordered by creation time, and new rows always go to the end of the primary-key index, which keeps inserts cheap. Its first problem is the one we hit: it needs one authority. There is a workaround, giving each database a different starting offset and a step equal to the number of databases (db-1 issues 1, 9, 17…, db-2 issues 2, 10, 18…). It works until we add a ninth database and have to change the step on every server without overlap.

Its second problem existed all along. Sequential public ids reveal volume. Someone who places an order at 19:00 on Monday and gets #41,220,118, then orders at 19:00 on Tuesday and gets #42,210,407, has learned that Dabba took about 990,000 orders that day. Two orders a week is enough to chart Dabba’s growth more accurately than any analyst. This is the same reasoning the Allies used in the Second World War to estimate German tank production from the serial numbers on captured tanks.

Sequential ids also invite enumeration. If the order page is /orders/41220118, someone will try 41220119. Authorisation should stop them, but one missing check on one endpoint becomes a leak of every customer’s address. Guessable ids turn small authorisation bugs into large ones.

Random UUIDs and the index that stops fitting in memory

A version-4 UUID is 122 random bits plus a few fixed ones. Any server can create one without asking anyone, the chance of two colliding is negligible at any volume Dabba will see, and it reveals nothing. It is the obvious fix, and for many tables it is fine. For a high-volume, ever-growing table it has a cost that shows up months later.

Predict first

The order_events table receives about 250 new rows a second at peak, one per status change, and its primary-key index is several times larger than the memory available to cache it. Index leaf pages are 8 KB and hold a few hundred keys each. How many different leaf pages does a second of inserts touch if keys are sequential? And if they are random UUIDs?

Show the worked answer

With sequential keys, every new key is larger than all existing ones, so it goes into the rightmost leaf page. A few hundred keys fill a page, so 250 inserts touch one or two pages a second, all of them already in memory.

With random keys, each insert lands in a random leaf somewhere in the index. 250 inserts touch about 250 different pages. If only a fraction of the index fits in memory, most of those pages must first be read from disk, then written back dirty. Pages also split when a random insert lands in a full one, leaving both halves partly empty, so the index grows larger than the data requires. In Postgres there is one more cost: the first change to each page after a checkpoint writes the whole 8 KB page into the write-ahead log, so 250 scattered changes can produce a couple of megabytes of log a second where sequential inserts produce a fraction of that.

That answer is the reason time-ordered ids matter. They keep the working set of an insert-heavy index small: only the newest pages are hot, and older pages can stay on disk until someone reads an old order. In MySQL’s InnoDB the effect is stronger, because the table itself is stored in primary-key order and every secondary index stores a copy of the primary key: a random 16-byte key scatters the rows and doubles the key’s cost in every other index.

Random UUIDs also fail two of our other requirements. They say nothing about which shard holds the order, and a 36-character string is not something anyone reads aloud to support.

Packing time, shard and sequence into 64 bits

Twitter’s Snowflake scheme showed how to get uniqueness and time order without coordination per id. A 64-bit id is split into fields: the time in milliseconds since a chosen epoch in the high bits, the id of the machine that made it in the middle, and a counter for ids made by that machine within the same millisecond in the low bits. Because time is in the high bits, ids sort by creation time. Because each machine has its own id, no two machines can produce the same value.

Instagram adapted this for sharded Postgres by replacing the machine id with the logical shard number, and generating the id inside the shard’s database as part of the insert. Dabba copies that layout, because it uses the same 8,192 logical shards from the sharding chapter.

64 bits · fits a BIGINT · sorts by creation time41 bitsmilliseconds since Dabba epoch~69 years of range13 bitslogical shard8,192 shards10 bitssequence1,024 per ms per shardthe shard bits route the id · the time bits keep the B-tree appending at its right edge
Dabba’s 64-bit order id. The time bits keep the index appending at its right edge; the shard bits route any lookup by order id to one database.

41 bits of milliseconds covers about 69 years (2 to the power 41 milliseconds), so from a 2024 epoch the scheme lasts until the 2090s. 13 bits hold the logical shard, 0 to 8,191, numbered in the per-city blocks the sharding chapter chose. 10 bits allow 1,024 distinct values per millisecond per shard. Each logical shard sees about 122 orders a day (1 million ÷ 8,192), so the low bits are never close to running out.

id    = (ms_since_epoch << 23) | (logical_shard << 10) | low_bits
shard = (id >> 10) & 0x1FFF          -- 8,191: which logical shard
when  = (id >> 23) + EPOCH_MS        -- creation time, to the millisecond

The routing promise from the sharding chapter is now kept: given any order id, the application extracts the logical shard with a shift and a mask, looks up the physical database in its map, and goes straight there. No lookup table of order to shard is needed. And because the id is minted inside the shard’s own insert, there is no separate id service to keep available.

What goes in the low 10 bits deserves its own question.

Predict first

Instagram’s published version fills the low 10 bits with the shard’s sequence counter, modulo 1,024. Suppose Dabba does the same. A competitor places two orders from the same restaurant, one day apart, and decodes both ids. What can they learn?

Show the worked answer

Both orders come from the same restaurant, so they are in the same logical shard. The low bits are that shard’s counter modulo 1,024. The shard sees about 122 orders a day, so the counter wraps only about once a week and has not wrapped between two orders a day apart: the difference between the two low-bit values is the number of orders that shard took in a day.

Multiply by 8,192 shards, and the competitor has Dabba’s daily volume again, the very leak we were trying to remove. The fix is to fill the low bits with random values instead of a counter. Two orders in the same shard in the same millisecond are already rare at 122 a day; when it happens, the chance that they also draw the same 10 random bits is 1 in 1,024, and the primary-key index rejects the second insert, which retries with fresh bits.

After that change, an order id reveals the time it was created, to the millisecond, and the logical shard of its restaurant, which, because of the city blocks from the sharding chapter, also says which city the order belongs to. Dabba decides all of this is acceptable: the customer knows when and where she ordered, and the shard number means nothing else outside our systems. That decision is worth writing down, because the next person to look at the layout will ask.

Where clocks break the scheme

Any id that contains time inherits the clock’s faults. Here is how that plays out. At 20:22 the virtual machine running db-5 is live-migrated to another host, and when it resumes, its clock is 2 seconds ahead. NTP notices and steps it back. For the next 2 seconds, db-5 mints order ids with timestamps earlier than ids it issued just before the correction.

Uniqueness survives, thanks to the random low bits and the primary-key check. Ordering does not. The restaurant tablet app syncs by asking for “orders for this restaurant with id greater than the last id I saw”. A tablet that synced at 20:22:01, after receiving an id stamped 20:22:02 from the fast clock, now ignores any order stamped earlier, including the three placed during the correction window. Those three orders never ring. Nobody gets an error.

Two changes fix it, at two levels. The generator stores the last millisecond it issued for each logical shard and uses the larger of that and the current clock. If the clock steps back, ids keep increasing and their time bits run slightly ahead of the wall clock until real time catches up. Twitter’s Snowflake chose differently: it refuses to issue ids until the clock passes the last value, which stalls inserts instead of skewing timestamps. Either choice is defensible; failing to choose is what causes the outage.

The second change is in the tablet. Time-ordered ids are approximately ordered, and a sync protocol should not depend on approximate order. The tablet now syncs with a per-restaurant change sequence that the shard database increments in the same transaction as each order change. It costs one more column and one more index, and it is correct regardless of clocks.

A dedicated id service using machine ids, rather than shard ids, has one more failure worth knowing. If two instances are started with the same machine id, perhaps from a copied configuration, they produce duplicate ids whenever they mint in the same millisecond with the same counter value. The usual protection is to lease machine ids from a coordination service such as etcd or ZooKeeper at start-up, with an expiry, so that no two running instances can hold the same one. Dabba avoids this by minting inside the shard, where the shard number is already unique.

Comparing the schemes

SchemeCoordination per idTime orderedSizeFinds the shardReveals
Auto-incrementOne databaseYes64 bitsNoExact volume
UUID v4NoneNo128 bitsNoNothing
UUID v7NoneYes, to the millisecond128 bitsNoCreation time
Snowflake (machine id)Machine id leased onceYes64 bitsNoTime; volume if the counter is exposed
Dabba’s layout (shard id, random low bits)None beyond the shard insertYes64 bitsYesCreation time and logical shard

UUID version 7, standardised in RFC 9562, deserves a mention as the default for tables that do not need shard routing or 64-bit compactness. It puts a 48-bit millisecond timestamp in front of 74 random bits, so it sorts by time, needs no coordination at all, and can be generated by a client. Dabba uses it for the rider app’s offline events: a rider in a basement can record “picked up” with a UUIDv7 and upload it later, and the id is still unique and roughly ordered when it arrives.

The order id is not the retry key

One confusion is worth clearing up because it causes duplicate orders. The order id is minted by the server when the order row is inserted, so the client does not know it until the request succeeds. If the customer taps “Place order”, the request reaches the server, the order is created, and the response is lost on a weak connection, the app sees a timeout. It retries, and the server, seeing a new request, creates a second order with a new id. The customer is charged twice.

The protection is a separate idempotency key: a random value (a UUID is fine) that the app generates when the customer first taps the button and sends with every retry of that same attempt. The order service stores the key with the order, under a unique index scoped to the customer. A retry with the same key finds the existing order and returns it instead of creating another. The chapter on getting writes right covers the pattern in detail; the point here is that it needs its own identifier. The order id answers “which order is this?”; the idempotency key answers “is this the same attempt as before?”, and only the client can create the second one, because only the client knows when it is retrying.

The id on the outside

A 64-bit id has two practical problems at the edges of the system. The first is JavaScript, which represents all numbers as 64-bit floating point and can store integers exactly only up to 2 to the power 53. Dabba’s ids pass that limit for any order created more than about 12 days after the epoch, since 2 to the power 53 divided by 2 to the power 23 is about a billion milliseconds. A web client that parses 7234567890123456789 as a number silently rounds it to a different order id and fetches the wrong order or none. The API therefore sends ids as strings, always.

The second is people. Nineteen digits read over the phone go wrong. The app shows a short display code for each order, derived from the id, and support looks orders up by the customer’s phone number plus that code. The display code is unique only within one customer’s orders, which is all a support conversation needs.

When this is more than the problem needs

A product on one database does not need any of this inside its own walls. A bigserial primary key is compact, ordered and simple. The one thing worth doing from day one is to never expose it: give the outside world a separate random token for each order, so that the internal key can change later without breaking links, and so that volume does not leak while the company is small and the numbers are most sensitive.

The city blocks matter again later. Because every order id carries a logical shard, and every logical shard belongs to exactly one city, any order id identifies its city without a lookup. The multi-region chapter relies on this when it homes each city in one region: routing an order lookup to the right region needs nothing but the id. We would revisit the layout if a single city’s orders ever had to be created in two regions at once, because clocks in different regions disagree by more than a millisecond and ids from the two would interleave imperfectly.

Orders now have ids that route, sort and reveal only what we chose. The next thing every order screen needs is pictures: menus with dish photos, uploaded from restaurant owners’ phones. The next chapter, on blob storage, covers where those bytes live, how they get there without passing through our servers, and why resizing them is not optional.