Ch.83: System Design: Auto-Increment vs UUID vs Snowflake
Outline
- 0:00 One record, one label
- 0:32 The regional create path
- 1:00 What the label must do
- 1:45 What the system requires
- 2:23 When a database counter fits
- 3:26 Generate a UUID locally
- 4:21 Why the database cares about order
- 5:10 What Snowflake puts in 64 bits
- 5:57 When worker identities collide
- 6:44 What happens when the clock goes backward
- 7:32 Why UUIDv7 starts with time
- 8:45 Two clocks give two orders
- 9:27 When restored copies repeat an ID
- 10:13 Store once and handle retries separately
- 11:00 Carry the full ID through the API
- 11:53 Choose against the requirements
- 12:34 Trace the complete design
- 13:12 Three questions to take into an interview
Transcript
0:00 Record identifiers let a system find the same note, order or message again. With several servers assigning them, a duplicate label can send a later request to the wrong record. We'll design that ID path across two regions, separate places running our application, the program handling notes. Then we'll compare each approach's promises about uniqueness, order and storage. Now take the two separate counters, one in each region. Both reach 41, then give different notes the label 42. When those notes meet, the matching label no longer tells them apart.
0:31 With that duplicate-label failure in view, look at the complete design. Each region receives a new note, generates its label locally, stores the record and returns that same label. The small inputs above each generator are its clock and secure source of random values. There's no trip to a shared ID server for every creation. We'll test the choices piece by piece, then return to this same map. Could the generator do everything correctly and the caller still receive a damaged label? Yes. Storage and the reply path can still damage it.
1:05 First, our functional requirements, what the ID path must do, are to assign a stable key, meaning the stored identifier used to find a note, preserve its full value and reject duplicates in that store. That last check protects an existing note in that store. It is not a worldwide search before each create. We need a defined namespace, meaning the set of records where labels must be distinct. For this design, notes from either region belong to that set. Their labels can meet later even though the notes were created independently.
1:38 That leaves us with a coordination choice, how much the generators must agree before choosing labels. Those functions still leave conditions the system has to work under, our non-functional requirements. Each region must create without a request to one shared ID service. We'll accept a wider key and an extraordinarily small chance of duplicates. For this made-up note service, assume 10,000 new notes per second in total. That's the rate we're designing for, rather than a measured result. Do we need those labels to prove which action happened first?
2:13 No. We'd like IDs from nearby creation times to sort together. They don't have to prove exact action order across the world. Let's test those promises. Now test the first pair against those requirements. Locally, neither counter made a mistake. A database engineer could ask: why not use one shared counter, a database sequence, for both callers? A shared sequence does solve that case. PostgreSQL, a database, documents its next-value operation as atomic: callers asking that same sequence at the same time receive distinct values.
2:45 I think that shared authority should stay when it meets the requirements. 42 and 43 are safe results there; a more distributed diagram isn't a reason to replace it. For example, if a region loses its connection to that counter, it can't create another note. That fails our requirement for independent creation. We could allocate non-overlapping blocks in advance, like the two ranges below. That removes a call per note, but someone still has to assign and safely reuse the blocks. Gaps can be normal, too.
3:16 A sequence doesn't promise consecutive invoice numbers, which means the business numbering requirement needs its own design rather than an assumption about this counter. But reserving ranges isn't the only route. UUIDs give each program creating records an enormous set of possible labels, so each can choose locally without registering its choice. UUID stands for Universally Unique Identifier. It's a standard 128-bit format; version 4 uses a random value with a few bits reserved for its format. Of that space, 122 bits are random.
3:48 Imagine two regional programs making independent choices from it; each depends on a working secure random generator. A name like “universally unique” sounds absolute, though. Are we relying on two programs never choosing the same label? No, we're accepting an extremely small probability under those assumptions. If we need rules that guarantee different labels, we must choose a design that proves that. The decision turns on that accepted risk. If the requirement rules it out, arguing about a prettier random-ID format won't make this approach eligible.
4:20 Now that generation can happen independently, consider storage. An ordered index, the database's sorted lookup structure, keeps neighboring keys together, so insertion position affects which parts we touch. For example, follow the scattered arrivals in the upper schematic row. Each new key can land... ...in a different patch of the index, while nearby values tend to cluster. That's index locality: related insertion work stays closer together. Which can help, but it doesn't give us a speed multiplier to quote.
4:49 The database, workload and actual measurements still decide the benefit. The wider format also costs space: 16 bytes of ID value instead of eight when we limit the label to 64 bits. Those are raw values, before the database adds its own storage. We accept the extra width; we still want a friendlier insertion pattern. Next, for a smaller label with time near the front, Snowflake-style IDs combine three pieces: time, the generator's identity, and a counter for IDs created during one clock tick. That layout separates two sources of overlap.
5:23 A worker's assigned identity distinguishes it from other workers; its counter separates requests handled within one tick, here 1 millisecond. The diagram shows Twitter's archived 2010 code. Its datacenter and worker fields identify the generator; its 12-bit sequence counts within the tick. Those 12 bits allow 4,096 counter values per worker per millisecond. Our 10,000-per-second load averages 10 creates per millisecond across both regions. That average doesn't hit the limit, but one worker could still receive too many requests in the same millisecond.
5:57 Now test that assignment with the duplicated worker on screen. Both copies use data center zero and worker seven, with counters starting at zero during the same millisecond. Each copy is a separate process, a running program. Their time, generator identity and counter all match, so the arithmetic produces an equal ID. That's the cost of this compact layout: safe assignment and reuse of worker identities, including what happens around a restart. Would giving the worker a lease, a time-limited claim to that identity, settle it?
6:27 Only if the rules for replacing a worker stop the old one issuing overlapping IDs. An expiry recorded by the service managing worker identities doesn't physically stop that process. The paperwork can expire while the old program keeps working. We still need proof those two can't issue overlapping IDs. But worker assignment isn't the only dependency in that historical code. If the clock goes behind the last reading the live process observed, generation refuses the next request. During an incident, that protection can show up as failed creates.
6:58 The process avoids walking back through its own combinations by temporarily withholding new IDs. And if its within-millisecond counter fills up, the code waits until the clock advances. More bits in the picture don't make time advance faster. Does remembering that clock reading also protect a brand-new process after a crash? Not by itself. While the program runs, it remembers that clock value; starting afresh doesn't recover it. Safe restart and identity reuse need more rules. That describes this archived code; other Snowflake designs can differ.
7:32 That clock dependence leads to another combination. UUID version 7 keeps the wider standard format but places a recorded clock value, in milliseconds, at the front. The standard gives that time field 48 bits. For our chosen design, the other 74 non-format bits carry random choices. That avoids assigning a separate worker identity. Does the version number tell us how to handle a clock that moves backward? No, that policy can vary. For our case, we'd use a tested library, reusable code that follows the UUID standard, with documented clock and randomness behavior, rather than build a generator from this diagram.
8:09 PostgreSQL 18 documents a version-7 generator, too. If the application doesn't need the label before insertion, that gives another place to generate it without building a separate service. Now consider the toy pair on screen. Both clocks show 1,000. What keeps the complete IDs different? The clock part matches, but the random values are one and 2 in this toy pair. So the complete labels differ. Comparing just their matching beginning would throw away the bits doing the separating. These tiny example values illustrate the layout; they aren't secure samples.
8:41 Independent creation still depends on healthy randomness. Distinct IDs don't establish action order. Consider the next pair: A happens first, its clock at 1,005; B happens later, its clock at 995. Sorting the time-shaped labels puts B ahead of A. The later action has received the smaller clock value. Can the rest of the identifier recover which event actually happened first? No. Random bits distinguish the labels; they don't measure the missing relationship between those machines' clocks or actions.
9:12 So sorting these labels is useful for storage, but treating that sort as the actual history would put our two actions in the wrong order. Even a generator that keeps its own values moving forward can't recover that missing relationship. But disagreement between clocks isn't the only concern. After a restart, fresh random choices must stay healthy even if the generator sees an old time value again. Look at copies A and B, restored from the same running program. If they inherit identical random state, the information used to make future random choices, they could repeat the same next choice while both clocks read 1,000.
9:51 Then the full labels could match, as the conditional example shows. That isn't a prediction about an ordinary restart. The standard for UUIDs specifically warns about refreshing random-generator state after process forks, when a process creates a copy of itself. So we must test the chosen library's handling of copied state, restarts and backward clocks. With those generator assumptions explicit, take a create request through the proposed system. First, the regional application checks that this caller may create a note in the requested account. Then it generates the record's identifier, attaches it to the note and inserts the full value into that region's database key, which rejects duplicates.
10:31 If that ID is already present in this store, our policy rejects the new insert and investigates. A matching label never authorizes replacing the other record. And the reply returns that same identifier. If the reply is lost and the caller sends the request again, does generating a new label prevent a second note? No. Distinct record labels don't make repeated requests count as one action. So recognizing a repeated request needs separate application logic, beyond the identifier. Next, follow the stored ID into the reply.
11:03 Ordinary JavaScript numbers can't represent every large whole number exactly, so a correct label can get damaged in transit. Consider the two neighboring values on screen. Both become the same Number value in the language's numeric type, so a caller receiving numeric data could lose the distinction. Discord documents returning its large Snowflake identifiers as strings, meaning text, for that reason. Keeping the value as text preserves those digits. We can send UUIDs as text too, and use the database's built-in UUID storage to keep their full value.
11:35 And don't confuse a hard-to-guess label with permission. Reading the requested note still requires a server permission check for this caller. Knowing where a record is doesn't grant access to it. That distinction explains the permission checks around our generator. Source links are in the description. Now compare those alternatives against our requirements. I think a separate ID service needs to earn its place; one database's own sequence may already satisfy its namespace. If an existing system accepts only a 64-bit whole number, a Snowflake-family design becomes more attractive, with its generator-assignment and clock responsibilities included.
12:12 Our fictional note service accepts wider keys and independent regional creation. A tested UUIDv7 library fits these requirements without asking a shared service for every label. We still accept the tiny risk of two labels matching, and we keep only the ordering guarantees we've actually established. Change either requirement, and we'd need to revisit the decision. With that choice made, trace the design again from either regional caller. Its application verifies the caller, obtains a local label and sends the note to its store.
12:44 The chosen code defines what happens when its clock reading goes backward and how it obtains random values. Each regional store preserves the UUID and refuses an insert that conflicts there. Neither regional path needs another region to hand it a new number every time a note is created. The generator makes the label, the store keeps it, and the caller gets that same value in the reply. Copying or editing the note still needs a separate design, as does proving global action order. Before picking a format, ask which records need distinct identifiers, what kind of order matters, and which width or coordination constraints the system has. Those answers make the choice much less mysterious.
13:24 A small counter can fit one job, a compact structured number another, and a wider locally generated label another. Thanks for listening to Learning Podcasts.