What an ID must be: unique, sortable, compact, opaque
Turn "we need an ID" into four requirements you can test (unique in which scope, sorted how strictly, how many bytes, what it reveals) and watch each one fail in a few lines of Python.
Contentsand lesson path
On this page
- Why it matters
- Unique: in which scope, and how
- Sortable: by time, roughly or strictly
- Compact: bytes, columns and clients
- Opaque: what an ID reveals
- Check your understanding
- Apply it
- Review prompt
Lessons of Unique ID Generation
- What an ID must be: unique, sortable, compact, opaque Concept · 15 min
- Sequences, ticket servers and UUID versions Concept · 20 min
- Building a Snowflake-style generator Lab · 30 min
- Short codes and the birthday bound Worked example · 20 min
- ID scheme check Knowledge check · 6 questions
What you will learn
- Compare database sequences, ticket servers, UUIDv4, UUIDv7 and Snowflake-style IDs by uniqueness guarantee, ordering, size and coordination cost.
01. Why it matters
In Choosing keys you gave each table a surrogate key and let one database count 1, 2, 3. That is a good default while one database creates every row. This skill is about what changes when that is no longer true: when orders are created on forty app servers, when a phone must name a record while it is offline, or when an ID appears in a public link.
IDs are one of the hardest things in a system to change. They end up in URLs, emails, logs, caches, search indexes, analytics tables and other companies' databases. You can add a column next week, but you cannot recall the IDs that strangers have already stored. So it pays to decide, before choosing a scheme, what the ID must do.
This lesson gives you four properties to test any scheme against: unique, sortable, compact and opaque. No scheme gives you all four for free. The next lesson compares the common schemes using exactly these four words.
02. Unique: in which scope, and how
Start with a question that sounds too simple: unique among what? One table, one customer's data, the whole company, or every system you will ever merge data with? And for how long: until the row is deleted, or forever? The wider the scope, the more a scheme has to work for it.
There are three basic strategies, and each fails in its own way. (IDs derived from something already unique, such as a hash of a natural key, inherit that input's uniqueness and its weaknesses, plus a chance of hash collisions that grows as the hash gets shorter.)
- Coordination. One place hands out the numbers, like a database sequence. Every ID is unique by construction, but creating an ID depends on that place being reachable and fast.
- Partitioning. The number space is split so that generators never overlap: one server takes odd numbers and another even ones, or each machine puts its own worker number inside every ID. Nobody talks at run time, but correctness now rests on the split being right. Give two generators the same part and they produce duplicates without any error.
- Randomness. Each generator picks from a space so large that a repeat is very unlikely. No coordination is needed at all, but uniqueness becomes a probability, and that probability is only as good as the random source.
The last point surprises people. A pseudo-random generator is a deterministic machine: the same internal state produces the same sequence. If that state is copied, for example when servers are cloned from one machine image, a container is restored from a snapshot, or a process forks after seeding its generator, the copies produce the same "random" IDs:
python3 - <<'EOF'
import copy
import random
template = random.Random(20261117) # seeded once, when the machine image was built
server_a = copy.deepcopy(template) # two servers cloned from that image
server_b = copy.deepcopy(template)
ids_a = [server_a.getrandbits(64) for _ in range(3)]
ids_b = [server_b.getrandbits(64) for _ in range(3)]
print(ids_a)
print("server B issues the same IDs:", ids_a == ids_b)
EOF[2686701686007980644, 17922656775488616830, 3731775833278846343]
server B issues the same IDs: TrueRFC 9562, the current UUID standard, therefore asks for a cryptographically secure random number generator (CSPRNG) and warns that its state must be reseeded after a process forks. Python's uuid.uuid4() and the secrets module read the operating system's secure source instead of a seed stored inside your process. The documentation of the random module warns that its generators should not be used for security purposes.
03. Sortable: by time, roughly or strictly
Why would anyone want IDs in creation order? Three reasons come up again and again.
- Index locality. A B-tree index keeps keys in order. If each new key sorts after the existing ones, inserts land at the right-hand edge of the index, on a few pages that stay in memory. Random keys land anywhere, so every insert may touch a different page. You will measure this in the next lesson.
- Paging and syncing. "Give me the items after ID x" only works if newer items have larger IDs.
- Debugging. When you read logs, you can tell which of two records came first without loading them.
Order comes in three strengths. No order is what random IDs give you. Rough order, also called k-sortable, means IDs sort by creation time to within some bound; when Twitter published its Snowflake design in 2010, its README promised IDs sorted to within one second and aimed for tens of milliseconds. Strict order needs one sequencer that sees every request, which brings back coordination.
Two warnings. First, a time-based ID is only as ordered as the clocks that made it. Clocks on different machines disagree by milliseconds or more, so an ID made later on a slow clock can sort before one made earlier on a fast clock. Rough order is fine for a feed; it is not a safe way to decide which of two writes happened last (see Distributed systems fundamentals). Second, even a single database sequence records when a number was taken, not when the row became visible to readers. The next lesson shows a reader that sees ID 5 before ID 4.
04. Compact: bytes, columns and clients
An ID is stored many times: in its own table, in every index that contains it, in every foreign key that points to it, and in caches and logs. A few extra bytes per ID become many gigabytes. The script below counts only the bytes of the key itself, for a billion rows and four copies of each key; real indexes add per-entry overhead on top.
python3 - <<'EOF'
import uuid
order_id = 1_874_221_015_329_034_241 # a 64-bit integer ID
public_id = uuid.UUID("019cece5-2687-73a1-8b5e-7c2d4f6a8190")
print("integer fits in 8 bytes:", order_id < 2**63)
print("UUID as raw bytes:", len(public_id.bytes), "bytes")
print("UUID as text:", len(str(public_id)), "characters")
rows, copies = 1_000_000_000, 4 # the key, plus 3 indexes or foreign keys holding it
for name, size in [("bigint", 8), ("uuid", 16), ("uuid as text", 36)]:
print(f"{name:<13} {size:>2} B x {copies} copies x 1e9 rows = "
f"{size * copies * rows / 1e9:>4,.0f} GB")
EOFinteger fits in 8 bytes: True
UUID as raw bytes: 16 bytes
UUID as text: 36 characters
bigint 8 B x 4 copies x 1e9 rows = 32 GB
uuid 16 B x 4 copies x 1e9 rows = 64 GB
uuid as text 36 B x 4 copies x 1e9 rows = 144 GBHow much this matters depends on the engine. In MySQL's InnoDB, every secondary index entry also stores the primary key, so the MySQL manual advises a short primary key. PostgreSQL indexes point at row locations instead, but foreign key columns and their indexes still hold the full value. Either way, store a UUID in a native 16-byte type, not as 36 characters of text; RFC 9562 says the same.
Compact also means "fits where it has to go". A 64-bit integer fits a BIGINT column and a CPU register. It does not fit a JavaScript number. JavaScript stores numbers as 64-bit floating-point values, which hold integers exactly only up to 2^53 − 1. Larger integers can be silently rounded when a browser parses JSON:
python3 - <<'EOF'
order_id = 1_874_221_015_329_034_241
as_js_number = int(float(order_id)) # a JS number is a 64-bit float, like Python's
print(as_js_number)
print("same ID:", as_js_number == order_id)
print(f"largest safe integer in JavaScript: {2**53 - 1:,}")
EOF1874221015329034240
same ID: False
largest safe integer in JavaScript: 9,007,199,254,740,991node -e 'console.log(JSON.parse("{\"id\": 1874221015329034241}").id)'1874221015329034200Node prints the shortest decimal that maps to the same floating-point value, so the two outputs look different, but both show the same rounded number, and a request for that ID finds nothing. The X (formerly Twitter) API documentation describes exactly this problem with its 64-bit IDs and tells clients to use the string field id_str. The usual fix is to send 64-bit IDs as JSON strings.
05. Opaque: what an ID reveals
An opaque ID is one that clients treat as a meaningless token. That has two sides. Your clients should not parse IDs or depend on their structure, so that you stay free to change the scheme; RFC 9562 gives the same advice for UUIDs. And the ID itself should not reveal anything you do not want to publish. Many schemes reveal more than their designers noticed:
python3 - <<'EOF'
import datetime as dt
import uuid
public_id = uuid.UUID("019cece5-2687-73a1-8b5e-7c2d4f6a8190") # a UUIDv7
created_ms = public_id.int >> 80 # its first 48 bits are Unix milliseconds
print("version", public_id.version, "created",
dt.datetime.fromtimestamp(created_ms / 1000, dt.timezone.utc))
monday, next_monday = 10_412, 11_630 # order numbers on two receipts a week apart
print(f"the shop takes about {next_monday - monday:,} orders a week")
EOFversion 7 created 2026-03-14 15:09:26.535000+00:00
the shop takes about 1,218 orders a weekA time-ordered UUID (version 7) carries its creation time to the millisecond, so a public account ID tells everyone when the account was opened. Sequential order numbers let a competitor subtract two receipts and estimate your sales. The older UUID version 1 can even contain the network card address of the machine that made it.
Opaque is not the same as secret. A hard-to-guess ID makes it harder to find records by scanning, but it is not access control: IDs leak through emails, logs and shared screenshots, so every request must still check that the caller may see that record (see Authentication and authorisation). The last lesson of this skill designs codes that are deliberately hard to guess.
06. Check your understanding
07. Apply it
Pick three IDs from a system you know, or use these: order numbers in a shop, links for sharing a private document, and event IDs in a logging pipeline. For each, write one line per property:
- Unique: in which scope, for how long, and which of coordination, partitioning or randomness you would rely on.
- Sortable: none, rough or strict, and which feature needs it.
- Compact: the size budget (a 64-bit column, a URL, a JavaScript client).
- Opaque: what the ID may reveal, and who sees it.
Keep the table. In lesson 3 you will build a generator for the case that this skill's practice task describes: IDs created on many machines at once, stored in 64 bits and sorted roughly by time.
08. Review prompt
Without looking back: name the three ways to make IDs unique and the typical failure of each. Explain the difference between rough and strict order, and why an ID taken first can become visible last. Why does a 64-bit ID need to travel as a string to a browser? And what can a UUIDv7 or a sequential number tell an outsider?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.