Sub topic 8
Time-ordered IDs: UUID v7 and ULID
This chapter assumes you know what a B-tree index is, can read bit-shift expressions in Python, and have seen the collision estimate for random UUID v4 values. The previous chapters showed that random IDs need no coordination but scatter inserts across an index. Time-ordered IDs keep the no-coordination property and fix most of the scattering.
The core idea
A time-ordered ID puts a timestamp in its most significant bits and fills the rest with random bits. Databases and sorting functions compare IDs from the most significant bit down. Two IDs created in different milliseconds therefore sort by creation time, and the random tail only matters when the timestamps match.
You get three properties at once:
- No central coordinator. Each node reads its own clock and its own random source.
- Rough chronological order. Sorting by ID is close to sorting by creation time.
- Good index locality. New rows land near the right edge of a B-tree, as they do with an auto-increment key.
The ordering is only rough. Different nodes have different clocks, and IDs created within the same millisecond have no defined order unless the generator adds one.
UUID version 7
UUID v7 is defined in RFC 9562 (2024). It keeps the standard 128-bit UUID size and its 36-character text form, so existing UUID columns, drivers, and libraries accept it.
| Field | Bits | Content |
|---|---|---|
| unix_ts_ms | 48 | Milliseconds since the Unix epoch |
| ver | 4 | Always 7 |
| rand_a | 12 | Random bits (or a counter) |
| var | 2 | Always binary 10 |
| rand_b | 62 | Random bits |
That leaves 74 random bits (12 + 62). A 48-bit millisecond timestamp covers about 8,900 years from 1970, so overflow is not a concern.
A hand-built generator
This code builds the layout directly. It also shows how to read the timestamp back out of an ID.
import os
import time
import uuid
def uuid7():
# 48-bit Unix timestamp in milliseconds, then 80 random bits.
ts_ms = time.time_ns() // 1_000_000
value = (ts_ms << 80) | int.from_bytes(os.urandom(10), "big")
# Set the 4-bit version field (bits 79-76) to 7.
value &= ~(0xF << 76)
value |= 7 << 76
# Set the 2-bit variant field (bits 63-62) to 0b10.
value &= ~(0x3 << 62)
value |= 0b10 << 62
return uuid.UUID(int=value)
def timestamp_ms(u):
# The top 48 bits of the 128-bit integer are the timestamp.
return u.int >> 80
first = uuid7()
time.sleep(0.002)
second = uuid7()
print(first)
print(second)
print(first < second) # True: created in different milliseconds
print(timestamp_ms(second) - timestamp_ms(first)) # about 2uuid.UUID objects compare by their integer value, so first < second follows the byte order a database would use. Python 3.14 added uuid.uuid7() to the standard library. Use it when you can, and use the hand-built version to understand what it does.
Ordering inside one millisecond
The generator above gives no order between two IDs created in the same millisecond. Their random tails decide, so the order is arbitrary. RFC 9562 describes optional methods to fix this. One method uses rand_a as a counter that increases within a millisecond. Another adds one to the whole random portion. Many libraries implement one of these. If your code depends on strict per-process ordering, check which method your library uses and test it. Do not assume it.
ULID
ULID (Universally Unique Lexicographically Sortable Identifier) predates UUID v7 and uses almost the same idea. It has a 48-bit millisecond timestamp followed by 80 random bits, for 128 bits in total. The differences are in the encoding and in the monotonicity rule.
- Text form: 26 characters in Crockford Base32, for example
01HZX3K9V4Q8M2T6R5B7N0WJCD. This is shorter than the 36-character UUID text. - Alphabet:
0123456789ABCDEFGHJKMNPQRSTVWXYZ. It omits I, L, O, and U to avoid look-alike characters. The characters are in ASCII order, so sorting the strings sorts the IDs. - No version or variant bits. All 80 low bits are random, which is slightly more entropy than UUID v7's 74.
- The ULID specification defines monotonic generation. If the timestamp has not advanced, the generator adds one to the previous random part.
The 128 bits do not divide evenly into 5-bit characters. 26 characters hold 130 bits, so the first character carries only 3 bits and never exceeds 7. A string starting with 8 or higher is not a valid ULID.
A monotonic ULID generator
import os
import threading
import time
ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"
def encode_base32(value, length=26):
chars = []
for _ in range(length):
chars.append(ALPHABET[value & 31])
value >>= 5
return "".join(reversed(chars))
class MonotonicUlid:
def __init__(self):
self.last_ms = -1
self.last_random = 0
self.lock = threading.Lock()
def new(self):
with self.lock:
now = time.time_ns() // 1_000_000
if now > self.last_ms:
self.last_ms = now
self.last_random = int.from_bytes(os.urandom(10), "big")
else:
# Same millisecond, or the clock stepped back: keep the old
# timestamp and increment the random part so order is preserved.
self.last_random += 1
if self.last_random >= 1 << 80:
raise OverflowError("random part exhausted for this millisecond")
return encode_base32((self.last_ms << 80) | self.last_random)
gen = MonotonicUlid()
ids = [gen.new() for _ in range(5)]
for item in ids:
print(item)
print(ids == sorted(ids)) # TrueThe else branch handles two cases with one rule. If many IDs arrive in the same millisecond, the counter increments. If the clock moves backwards, the generator keeps using the last timestamp it issued. This preserves order within one process, at the cost of timestamps that drift from the real time during the backward step.
The random part starts at a random value, not zero. If it started at zero, IDs created early in a millisecond would be easy to guess from the previous one. A random start keeps IDs unguessable across milliseconds, though not within a run of same-millisecond IDs.
Collision risk
Collisions are only possible between IDs with the same timestamp, so the random bits only have to separate IDs created in the same millisecond. Apply the birthday bound from the earlier chapter with 74 random bits for UUID v7. Suppose 1,000 IDs are created in the same millisecond:
p ≈ n² / (2 · 2⁷⁴) = 10⁶ / (3.78 × 10²²) ≈ 2.6 × 10⁻¹⁷
That is far smaller than the chance of a hardware fault. At realistic rates the collision risk is negligible, and a primary key constraint will catch the rare duplicate. Counter-based monotonic modes remove random collisions inside one process entirely. They do nothing across processes, which still rely on randomness.
Comparing the schemes
| Property | UUID v4 | UUID v7 | ULID |
|---|---|---|---|
| Size | 128 bits | 128 bits | 128 bits |
| Text form | 36 characters | 36 characters | 26 characters |
| Random bits | 122 | 74 | 80 |
| Sortable by time | No | Yes, by millisecond | Yes, by millisecond |
| Index locality | Poor | Good | Good |
| Native database type | Yes (`uuid`) | Yes (`uuid`) | No, store as `uuid` or `char(26)` |
| Standardized | RFC 9562 | RFC 9562 | Community spec |
If you want ULID's text form but a native uuid column, a ULID's 128 bits can be stored as a UUID value. The bytes sort the same way. Convert at the API boundary.
Gotchas
- Clocks are not synchronized. Two nodes whose clocks differ by 50 ms will produce IDs that interleave incorrectly across that window. The ID order matches real order only to within clock skew. Do not use these IDs as proof that one event happened before another. Later chapters cover clock hazards in detail.
- Timestamps leak. Anyone who sees an ID can read when the record was created. This matters for user-visible IDs, such as account numbers or order links, where creation time may be private. The security chapter covers this.
- Text sorting depends on case and encoding. Crockford Base32 sorts correctly in uppercase ASCII order. If a library emits lowercase, or a database collation ignores case or reorders characters, string sorting can break. Compare binary values, or force a binary collation.
- Sorting is not ranking. Within a millisecond, order is arbitrary unless the generator guarantees monotonicity. Never rely on ID order to break ties for queries like "the latest row", and add an explicit timestamp column when order matters.
- Keys are sequential. Sequential inserts can concentrate writes on one index page or one shard. In a sharded system keyed by ID range, all new writes hit the newest shard. Hash the key for sharding, and keep the time-ordered ID for the index.
- Old data is not retrofitted. Existing UUID v4 rows stay random. A mixed table only benefits for new inserts.
When to pick which
Choose UUID v7 when you already use UUID columns and want better insert performance without changing types. Choose ULID when short, URL-friendly text is valuable and you can handle the missing native type. Choose UUID v4 when creation time must stay hidden and your table is small enough that locality does not matter. Choose neither when you need a 64-bit key or strict ordering guarantees. The next chapter covers Snowflake-style IDs, which address the size question.
Exercise
A service creates UUID v7 values on three servers. Server A and server B each create an ID within the same millisecond. A developer sorts the table by ID and treats the first row as "created first". What is wrong with that assumption, and what would you change?
Show answer
Within one millisecond the ordering is decided by random bits (or by a per-process counter that other servers cannot see), so the sort order of the two IDs is arbitrary. Clock skew between servers A and B also means a later event can carry an earlier timestamp. The sort order is only approximate. To get a reliable order, store an explicit created_at column, or a sequence assigned by a single authority if strict ordering is required. Use the ID order only for index locality and rough chronology.
Exercise
A ULID string begins with the character 9. Is it valid? Explain using the encoding.
Show answer
No. A ULID is 128 bits, but 26 Base32 characters hold 130 bits, so the first character carries only 3 bits and its value can be at most 7. The character 9 has value 9, which needs 4 bits. A valid ULID's first character is therefore in the range 0 to 7.