Sub topic 13
Choosing a scheme for your system
This chapter assumes you have read the earlier chapters on counters, UUIDs, time-ordered IDs, Snowflake-style IDs, and clock hazards. You should be comfortable with primary keys, B-tree indexes, and bit fields. The goal is to turn those pieces into a decision you can defend in a design review.
Start from requirements, not from a favorite scheme
No scheme wins on every property. A good choice starts with a short list of requirements, ordered by how much a violation would cost you.
- Uniqueness. Duplicates are never acceptable for primary keys. The question is whether uniqueness is guaranteed by construction (counters, Snowflake with unique workers) or only made very unlikely (random IDs).
- Coordination at write time. Can a node create an ID while partitioned from every other node? If yes, you need random or time-based IDs. If a database is always on the write path anyway, a sequence costs you nothing extra.
- Ordering. Do you need IDs to sort by creation time? Exact ordering across nodes needs a single writer. Approximate ordering (millisecond granularity) is enough for index locality and for most "newest first" pages.
- Size. A 64-bit integer fits in a
bigintcolumn, in JavaScript-unsafe-but-common 64-bit APIs, and in smaller secondary indexes. A 128-bit ID doubles the key size in every index that includes it. - Predictability. Can a client who sees one ID guess others, or learn when something was created?
- Operational burden. Who assigns worker IDs, and what happens when a clock misbehaves?
Comparing the schemes
| Scheme | Size | Ordering | Coordination | Main risk |
|---|---|---|---|---|
| Database auto-increment | 32 or 64 bits | Exact, in commit order of one database | Every insert hits the sequence owner | Bottleneck and single point of failure |
| Block allocation (ticket server) | 64 bits | Ordered within a block, roughly ordered overall | One call per block | Lost IDs on crash, ticket server availability |
| UUID v4 | 128 bits | None | None | Poor index locality, no creation time |
| UUID v7 / ULID | 128 bits | Millisecond-level | None | Same-millisecond IDs unordered, leaks creation time |
| Snowflake-style | 64 bits | Millisecond-level, strict per worker | Worker ID assignment, once | Duplicate worker IDs, backwards clocks |
Two points in this table are often misread.
- "None" under coordination means no coordination per ID. Snowflake needs coordination only when a worker starts. That is a very different cost from a network call per insert.
- Random IDs do not guarantee uniqueness. With 122 random bits, the birthday bound for a billion IDs is about 9.4e-20, which is negligible. The failure you should worry about is a broken random source, such as a cloned virtual machine image that reuses a seeded generator. It is not statistical bad luck.
A decision flow
The diagram below encodes the questions that most often decide the outcome. Real systems add exceptions, but this covers the common cases.
The same flow as code
Writing the decision as a function makes the assumptions explicit and testable. This is a teaching aid, not a library.
def choose_scheme(
single_writer,
public_ids,
need_64_bit,
can_assign_workers,
need_time_order,
):
"""Return a suggested ID scheme for a set of requirements."""
if single_writer:
if public_ids:
return "auto-increment internally plus a random public ID"
return "database auto-increment"
if need_64_bit:
if can_assign_workers:
return "Snowflake-style"
return "block allocation from a ticket server"
if need_time_order:
return "UUID v7 (or ULID)"
return "UUID v4"
print(choose_scheme(False, True, False, False, True)) # UUID v7 (or ULID)
print(choose_scheme(False, False, True, True, True)) # Snowflake-style
print(choose_scheme(True, False, False, False, False)) # database auto-incrementNotice what the function does not decide: it ignores throughput. Throughput matters, and the next section shows where.
Worked scenarios
Scenario 1: an internal orders service on one PostgreSQL primary
One writer, moderate load, IDs only used by your own services. A bigint identity column is the right answer. It is the smallest, sorts exactly, and needs no code. Reach for something more complex only when you outgrow a single primary. At that point, changing the key type is painful, so ask whether sharding is likely within the system's lifetime.
If order numbers appear in URLs, add a separate random public identifier. Keeping the internal key sequential preserves index locality, and the public one stops clients from enumerating records.
Scenario 2: a mobile app that creates records offline
Clients must create IDs with no network. Any scheme needing a server call fails. A Snowflake-style scheme would require handing out worker IDs to millions of phones, which is impractical. UUID v4 or v7 fits. Choose v7 if the server stores these IDs as primary keys in a B-tree, because inserts then land near the right edge of the index. Choose v4 if you are worried about clients revealing creation time, or if a client's clock may be wrong, since a skewed clock puts a v7 key far from the index's hot region.
Scenario 3: a high-volume event pipeline with 64-bit keys
You have a few hundred stateless workers, a column store sized for 64-bit keys, and a need for roughly time-sorted data. Snowflake-style fits. The cost is operational: you must give each worker a unique ID from a registry or lease system, and you must handle a clock that steps backwards.
With a 12-bit sequence, each worker can issue 4,096 IDs per millisecond. That is roughly four million per second per worker. If each worker needs more than that, the scheme is the wrong tool. In practice, throughput per worker is rarely the limit. The 10-bit worker field, which allows 1,024 workers, is the limit you reach first.
Failure modes to plan for
Whatever you choose, write down what breaks and how you will notice.
- Auto-increment: the primary fails or fails over with a gap. Sequences are not rolled back, so gaps are normal. Never treat a missing number as a missing row.
- Block allocation: a node crashes holding an unused block. Those IDs are lost. This is fine with 64-bit space, but not if you promised gap-free numbering.
- Random UUIDs: weak or duplicated random sources. Use the operating system's cryptographic generator, and confirm that cloned images and forked processes reseed.
- UUID v7 and ULID: IDs within the same millisecond are not ordered, unless your library adds a monotonic counter. Do not rely on strict order unless you have read your library's documentation.
- Snowflake-style: two workers share a worker ID, or the clock moves backwards. In the first case, duplicates are possible whenever both issue an ID in the same millisecond with the same sequence value. The generator from the earlier chapter refuses to issue IDs when it sees the clock go backwards, which turns silent duplicates into a visible error.
Migration and reversibility
Changing the ID scheme later is expensive because IDs are copied into foreign keys, caches, logs, URLs, and other teams' systems. Two habits lower that cost.
- Treat the ID as an opaque value in APIs. Serialize 64-bit integers as strings in JSON, because many clients parse numbers as 64-bit floats and lose precision above 2^53.
- Keep the generator behind one small interface in your codebase, so replacing it changes one module rather than every caller.
Existing rows keep their old IDs. Mixed schemes work when the column type fits both. A uuid column holds v4 and v7 values side by side, which makes a v4-to-v7 switch cheap. Going from 32-bit auto-increment to 64-bit Snowflake needs a column type change and a rewrite of every referencing table.
A short checklist
- Write the requirements: coordination-free creation, size limit, ordering need, exposure to clients.
- Eliminate schemes that violate a hard requirement, using the table above.
- Among the rest, pick the one with the simplest operations you can run reliably.
- Add a unique constraint and a monitor for duplicate-key errors.
- Write down the failure modes and test the clock and worker-assignment ones.
Exercise
A team runs 40 stateless API servers behind a load balancer, writing to a sharded database. They need 64-bit keys, rough time ordering for pagination, and no network call per insert. Servers are replaced often by an autoscaler. Which scheme from this chapter fits, and what is the first operational problem they must solve?
Show answer
A Snowflake-style scheme fits: it gives 64-bit IDs, millisecond-level ordering, and no per-ID coordination. The first problem is assigning a unique worker ID to every server instance, including replacements created by the autoscaler. They need a lease or registry so that a new instance never reuses the ID of a live one. They should also make the generator refuse to issue IDs when the clock moves backwards.
Exercise
A product stores 2 billion rows keyed by UUID v4 and sees slow inserts because of B-tree page splits. They want to fix this without changing the column type. What do you suggest, and what new concern does it add?
Show answer
Switch new rows to UUID v7. It uses the same 128-bit uuid column, so old and new values coexist. The timestamp prefix makes new keys land near the right edge of the index, which reduces page splits and improves cache use. The new concern is that v7 IDs reveal creation time to anyone who sees them. If IDs are public and creation time is sensitive, expose a separate random identifier instead.