Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 5 · Concept · 20 min · revision 1

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

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:

Terminal · start PostgreSQL 18
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'
Expected output (a newer 18.x is fine)
18.6

02. 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:

Terminal · three sessions share a sequence with CACHE 10
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'
Expected output
session A|1|2
session B|11|12
session C|21|22
30

Session 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:

Terminal · an identity column and a rollback
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
Expected output
 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:

Terminal · two writers and a reader
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"
Expected output
A took id 4
B took id 5
reader sees 1, 3, 5
A commits now
reader sees 1, 3, 4, 5

For 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:

Terminal · reserve blocks of 1,000 IDs
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"
done
Expected output
app-1 reserves 1..1000
app-2 reserves 1001..2000
app-1 reserves 2001..3000

The 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:

Python 3.12 · 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 >> 80
Terminal · check against RFC 9562, Appendix A.6
python3 - <<'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))
EOF
Expected output
017f22e2-79b0-7cc3-98c4-dc0c0c07398f
matches the RFC: True
version: 7 | variant: specified in RFC 4122
created: 2022-02-22 19:22:22+00:00

Python 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:

Terminal · three UUIDv7 values, sorted
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])
EOF
Expected output
01a1e8bc-0a80-709c-8000-000000005678 second
01a1e8bc-0a80-7a51-8000-000000001234 first
01a1e8bc-0a81-7000-8000-000000000000 third

For 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.

Terminal · one million UUIDv4 and UUIDv7 keys
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
Illustrative output (PostgreSQL 18.6; over four runs the v4 row ranged 40-42 MB and 71-74%)
 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).

Terminal · remove the database when you are done
docker rm -f -v ids-lab

05. The schemes side by side

Summary · the four properties per scheme
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 IDs

Read 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

Practice check · 3 questions

Sequences, allocators and UUIDs

Predict what each scheme does in three new situations.

Q1. A new PostgreSQL sequence has CACHE 50. Three short-lived worker connections each insert one invoice and disconnect. Then a fourth connection inserts one invoice. Which IDs do the four invoices get?
Q2. Orders live on 8 shards, and each shard's table has its own identity column starting at 1. A report that merges the shards finds many orders sharing an ID. Which change stops the clashes and still creates IDs locally on each shard?
Q3. A service builds UUIDv7 values with all 74 non-time bits random and no counter. It creates two IDs for one user within the same millisecond. When sorted, which comes first?
Practice only: not graded, not saved, not evidence.

07. Apply it

Go back to the table of three IDs you wrote in the previous lesson.

  1. Choose a scheme for each from the summary above, and write one sentence on what you gain and one on what you give up.
  2. Restart the database, add a third table keyed by bigint GENERATED ALWAYS AS IDENTITY to the measurement script, and compare its index size and WAL with the two UUID tables. Explain the difference in one sentence.
  3. 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

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check