Sequences, ticket servers and UUID versions
Run database sequences, a block allocator and UUIDs side by side in PostgreSQL 18 and Python: see where gaps and out-of-order IDs come from, build a UUIDv7 that matches the RFC 9562 test vector, and measure what random keys cost a B-tree index.
Contentsand lesson path
On this page
- Why it matters
- Sequences and ticket servers: unique, but not gapless or in commit order
- UUID versions in RFC 9562
- Measured: random versus time-ordered keys in a B-tree
- The schemes side by side
- 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
The previous lesson gave you four properties: unique, sortable, compact and opaque. Now you will test real schemes against them: some rely on coordination (a database sequence, a ticket server), some on randomness and the clock (UUIDs). Each has a cost that is easy to miss on paper and easy to see once you run it.
To follow along you need Docker for the PostgreSQL parts and Python 3.10 or newer for the UUID part. The examples were run with PostgreSQL 18.6, the first major version with a built-in uuidv7() function, and with Python 3.12.13 and 3.10.12. Start a throwaway database; --tmpfs keeps its data in memory, so nothing is left behind:
docker run --name ids-lab -e POSTGRES_PASSWORD=idslab \
--tmpfs /var/lib/postgresql -d postgres:18-alpine > /dev/null
until docker exec ids-lab pg_isready -h 127.0.0.1 -U postgres -q; do sleep 1; done
docker exec ids-lab psql -U postgres -At -c 'SHOW server_version'18.602. Sequences and ticket servers: unique, but not gapless or in commit order
A sequence is a counter object inside the database; an identity column such as bigint GENERATED ALWAYS AS IDENTITY uses one behind the scenes. nextval is cheap because it never waits for other transactions, and to stay cheap it never gives a number back. The PostgreSQL documentation is explicit: values are not reused when a transaction aborts, and with CACHE above 1 each session reserves a block of values, loses the unused ones when it disconnects, and may hand out values out of order compared with other sessions. Each docker exec … psql below is a new session:
docker exec ids-lab psql -U postgres -q -c 'CREATE SEQUENCE ticket_seq CACHE 10'
for session in A B C; do
docker exec ids-lab psql -U postgres -At \
-c "SELECT 'session $session', nextval('ticket_seq'), nextval('ticket_seq')"
done
docker exec ids-lab psql -U postgres -At -c 'SELECT last_value FROM ticket_seq'session A|1|2
session B|11|12
session C|21|22
30Session A reserved 1 to 10 and used two, B reserved 11 to 20, C reserved 21 to 30, and 3 to 10, 13 to 20 and 23 to 30 are gone for good. A rolled-back insert leaves a gap in the same way:
docker exec -i ids-lab psql -U postgres -q <<'SQL'
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
item text NOT NULL
);
INSERT INTO orders (item) VALUES ('kettle');
BEGIN;
INSERT INTO orders (item) VALUES ('toaster');
ROLLBACK;
INSERT INTO orders (item) VALUES ('teapot');
SELECT id, item FROM orders ORDER BY id;
SQL id | item
----+--------
1 | kettle
3 | teapot
(2 rows)Gaps are harmless for a key. They matter only if someone treats the numbers as a count, or a rule demands gapless numbering, as some invoice rules do; that needs a counter updated under a lock, which the PostgreSQL manual calls "much more expensive".
The next effect matters more. A number is taken when the row is inserted, but the row becomes visible only when its transaction commits. Here transaction A takes an ID and commits two seconds later, while B takes the next ID and commits at once:
docker exec -i ids-lab psql -U postgres -At -q <<'SQL' &
BEGIN;
INSERT INTO orders (item) VALUES ('slow') RETURNING 'A took id ' || id;
SELECT 'A commits now' FROM pg_sleep(2);
COMMIT;
SQL
sleep 1
docker exec ids-lab psql -U postgres -At -q \
-c "INSERT INTO orders (item) VALUES ('fast') RETURNING 'B took id ' || id"
docker exec ids-lab psql -U postgres -At \
-c "SELECT 'reader sees ' || string_agg(id::text, ', ' ORDER BY id) FROM orders"
wait
docker exec ids-lab psql -U postgres -At \
-c "SELECT 'reader sees ' || string_agg(id::text, ', ' ORDER BY id) FROM orders"A took id 4
B took id 5
reader sees 1, 3, 5
A commits now
reader sees 1, 3, 4, 5For one second, a reader saw 5 but not 4. A sync job that remembered "the highest ID I have seen is 5" would never fetch order 4. ID order is the order in which numbers were taken, not the order in which rows appeared.
Sequences are the right default when one database creates all the rows, because you are writing to that database anyway. The cost appears when several databases create rows of one kind: each shard or region has its own counter, and two of them both produce order 1001. You must then split the number space (each counter starts at a different value and steps by the number of counters: START WITH and INCREMENT BY in PostgreSQL, auto_increment_offset and auto_increment_increment in MySQL) or move the counter out of the shards.
Moving the counter out of the shards is what Flickr described in 2010. A ticket server is a dedicated database that only hands out numbers. Flickr kept a one-row MySQL table per sequence; each request ran REPLACE INTO Tickets64 (stub) VALUES ('a') and then SELECT LAST_INSERT_ID() to get a new 64-bit ID. To avoid a single point of failure they ran two servers, one issuing odd numbers and one even numbers, and spread requests across both. The post notes that the two sides drift apart, with hundreds of thousands more odd than even IDs.
The cost is a round trip to the allocator for every new object, and the allocator caps how fast the whole system can create things. The usual refinement is block allocation: an app server reserves a range of IDs in one round trip and hands them out from memory. In PostgreSQL that is one atomic UPDATE … RETURNING:
docker exec -i ids-lab psql -U postgres -q <<'SQL'
CREATE TABLE id_blocks (name text PRIMARY KEY, next_id bigint NOT NULL);
INSERT INTO id_blocks VALUES ('order', 1);
SQL
for server in app-1 app-2 app-1; do
docker exec ids-lab psql -U postgres -At -q -c "
UPDATE id_blocks SET next_id = next_id + 1000 WHERE name = 'order'
RETURNING '$server reserves ' || next_id - 1000 || '..' || next_id - 1"
doneapp-1 reserves 1..1000
app-2 reserves 1001..2000
app-1 reserves 2001..3000The row lock on id_blocks serialises the updates, so no two servers get the same range. The block size is a trade-off. Bigger blocks mean fewer round trips, but a server that crashes loses the rest of its block, and IDs stop following creation time: app-1 may still be issuing 900 when app-2 is already at 1500.
03. UUID versions in RFC 9562
A UUID is a 128-bit value that anyone can generate without asking anyone else. RFC 9562 (May 2024) replaced RFC 4122 as the standard. In every UUID version it defines (1 to 8), bits 48 to 51 hold the version and bits 64 and 65 hold the variant (binary 10). Three versions matter for new systems:
- Version 4 fills the other 122 bits with random data. It has no order and reveals nothing.
- Version 7 starts with a 48-bit Unix timestamp in milliseconds and fills the remaining 74 bits with random data, optionally with a counter or extra clock precision first. It sorts roughly by time. The RFC says to prefer it over the older time-based versions 1 and 6.
- Version 8 fixes only the version and variant bits and leaves 122 bits to your own layout. The RFC requires it for a custom timestamp epoch, recommends it for an embedded node ID, and warns that its uniqueness "MUST NOT be assumed": that is up to your design.
Python 3.12's uuid module has no uuid7(); it was added in Python 3.14. Writing one takes a few lines, and the RFC's own test vector (Appendix A.6) tells you whether you placed the bits correctly. Save this as uuid7.py:
"""UUIDv7 for Python 3.12, whose uuid module has no uuid7() (added in 3.14).
Field layout from RFC 9562, Section 5.7, most significant bits first:
unix_ts_ms (48) | ver = 7 (4) | rand_a (12) | var = 0b10 (2) | rand_b (62)
"""
import secrets
import time
import uuid
def build(unix_ts_ms: int, rand_a: int, rand_b: int) -> uuid.UUID:
for field, bits in ((unix_ts_ms, 48), (rand_a, 12), (rand_b, 62)):
if not 0 <= field < 1 << bits:
raise ValueError(f"{field} does not fit in {bits} bits")
value = (unix_ts_ms << 80) | (0x7 << 76) | (rand_a << 64) | (0b10 << 62) | rand_b
return uuid.UUID(int=value)
def uuid7() -> uuid.UUID:
"""Plain method: 74 fresh random bits, no counter (see Section 6.2)."""
unix_ts_ms = time.time_ns() // 1_000_000
return build(unix_ts_ms, secrets.randbits(12), secrets.randbits(62))
def timestamp_ms(u: uuid.UUID) -> int:
return u.int >> 80python3 - <<'EOF'
import datetime as dt
from uuid7 import build, timestamp_ms
u = build(0x017F22E279B0, 0xCC3, 0x18C4DC0C0C07398F) # RFC 9562, Appendix A.6
print(u)
print("matches the RFC:", str(u).upper() == "017F22E2-79B0-7CC3-98C4-DC0C0C07398F")
print("version:", u.version, "| variant:", u.variant)
print("created:", dt.datetime.fromtimestamp(timestamp_ms(u) / 1000, dt.timezone.utc))
EOF017f22e2-79b0-7cc3-98c4-dc0c0c07398f
matches the RFC: True
version: 7 | variant: specified in RFC 4122
created: 2022-02-22 19:22:22+00:00Python still names the variant after RFC 4122; the bits are the same in RFC 9562. Now look at order. Two UUIDs from the same millisecond share their first 48 bits, so the random bits decide which sorts first:
python3 - <<'EOF'
from uuid7 import build
ms = 1_794_906_000_000 # 2026-11-17T09:00:00Z
first = build(ms, 0xA51, 0x1234) # made first ...
second = build(ms, 0x09C, 0x5678) # ... then second, in the same millisecond
third = build(ms + 1, 0x000, 0x0000) # one millisecond later
names = {first: "first", second: "second", third: "third"}
for u in sorted([first, second, third]):
print(u, names[u])
EOF01a1e8bc-0a80-709c-8000-000000005678 second
01a1e8bc-0a80-7a51-8000-000000001234 first
01a1e8bc-0a81-7000-8000-000000000000 thirdFor increasing values within a millisecond, RFC 9562 Section 6.2 offers three methods: a counter after the timestamp, an incremented random value, or extra clock precision in the first 12 random bits. Python 3.14's uuid7() uses a 42-bit counter, and PostgreSQL 18 documents a sub-millisecond timestamp in uuidv7(). Either way, this covers one generator; values from different machines are only as ordered as their clocks.
04. Measured: random versus time-ordered keys in a B-tree
RFC 9562 explains version 7 partly by index locality. You can measure it. The script loads one million rows into a table keyed by uuidv4() and another keyed by uuidv7(), runs a checkpoint, inserts 100,000 more rows into each, and then reports the index size, how full its leaf pages are (from the pgstattuple extension), and how much write-ahead log (WAL) the extra inserts produced.
docker exec -i ids-lab psql -U postgres -q <<'SQL'
CREATE EXTENSION pgstattuple;
CREATE TABLE ids_v4 (id uuid PRIMARY KEY DEFAULT uuidv4());
CREATE TABLE ids_v7 (id uuid PRIMARY KEY DEFAULT uuidv7());
INSERT INTO ids_v4 SELECT FROM generate_series(1, 1000000);
INSERT INTO ids_v7 SELECT FROM generate_series(1, 1000000);
CHECKPOINT;
SELECT pg_current_wal_insert_lsn() AS t0 \gset
INSERT INTO ids_v4 SELECT FROM generate_series(1, 100000);
SELECT pg_current_wal_insert_lsn() AS t1 \gset
INSERT INTO ids_v7 SELECT FROM generate_series(1, 100000);
SELECT pg_current_wal_insert_lsn() AS t2 \gset
SELECT 'v4' AS key, pg_size_pretty(pg_relation_size('ids_v4_pkey')) AS index_size,
round(avg_leaf_density) AS leaf_fill_pct,
pg_size_pretty(pg_wal_lsn_diff(:'t1', :'t0')) AS wal_100k_more
FROM pgstatindex('ids_v4_pkey')
UNION ALL
SELECT 'v7', pg_size_pretty(pg_relation_size('ids_v7_pkey')),
round(avg_leaf_density), pg_size_pretty(pg_wal_lsn_diff(:'t2', :'t1'))
FROM pgstatindex('ids_v7_pkey');
SQL key | index_size | leaf_fill_pct | wal_100k_more
-----+------------+---------------+---------------
v4 | 40 MB | 74 | 42 MB
v7 | 33 MB | 90 | 14 MB
(2 rows)Here is what this run measured. With random keys, pages split in the middle and the leaves ended up only 71 to 74% full, so the same 1.1 million keys needed a fifth to a quarter more index space. The extra 100,000 random inserts also wrote about three times as much WAL. The documented reason: after each checkpoint, PostgreSQL writes a full copy of a page to the WAL the first time that page changes, and random keys touch thousands of different leaf pages, while time-ordered keys keep touching the same few at the right-hand edge. More WAL means more disk writes, more data shipped to replicas and larger backups.
What this small test does not show is the effect that hurts most in production: when the index no longer fits in memory, a random insert may have to read a page from disk first. RFC 9562 says the difference between local and random inserts "can be one order of magnitude or more"; that is the RFC's claim, not a number measured here, so measure with your own data and hardware. Time-ordered keys have their own cost, too: in a cluster partitioned by key range, every new row lands in the newest partition (see shard keys and hot spots).
docker rm -f -v ids-lab05. The schemes side by side
scheme unique because order size cost per ID
DB sequence one counter order numbers taken 64 bits call to the DB
ticket server one central counter order numbers taken 64 bits call to allocator
block allocator reserved ranges within each block 64 bits 1 call per block
UUIDv4 122 random bits none 128 bits none
UUIDv7 ms time + 74 bits rough, by clock 128 bits none
Snowflake-style time+worker+sequence rough, by clock 64 bits unique worker IDsRead the last column as "what must be true for every new ID". Coordinated schemes need a reachable counter, UUIDs need a good random source, and Snowflake-style IDs need a different number for every worker, the subject of the next lesson's lab. On opacity, UUIDv4 reveals nothing, sequences reveal volume, and UUIDv7 and Snowflake IDs reveal creation time.
06. Check your understanding
07. Apply it
Go back to the table of three IDs you wrote in the previous lesson.
- Choose a scheme for each from the summary above, and write one sentence on what you gain and one on what you give up.
- Restart the database, add a third table keyed by
bigint GENERATED ALWAYS AS IDENTITYto the measurement script, and compare its index size and WAL with the two UUID tables. Explain the difference in one sentence. - Write down which of your three IDs would need the Snowflake-style generator from the next lesson, and which worker numbers you would give your machines.
08. Review prompt
Without looking back: why does a PostgreSQL sequence leave gaps, and why can a reader see ID 5 before ID 4? What does a bigger block trade away in block allocation? Which bits of a UUIDv7 hold the time, the version and the variant, and when must you use version 8 instead? Which two costs of random keys did you measure, and which one did you not?
References
- RFC 9562: Universally Unique IDentifiers (UUIDs)
- PostgreSQL 18 documentation: CREATE SEQUENCE
- PostgreSQL 18 documentation: Sequence Manipulation Functions
- PostgreSQL 18 documentation: UUID Functions
- PostgreSQL 18 documentation: pgstattuple
- PostgreSQL 18 documentation: Write Ahead Log settings (full_page_writes)
- Flickr Code (2010): Ticket Servers, Distributed Unique Primary Keys on the Cheap
- MySQL 8.4 Reference Manual: auto_increment_increment and auto_increment_offset
- Python documentation: uuid
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.