Unique ID Generation
- List the requirements that drive an ID scheme (uniqueness scope, ordering, size, coordination, leakage, readability) and pick a scheme from them
- Explain UUIDv4, UUIDv7, ULID and Snowflake layouts and their behaviour under clock skew and high concurrency
- Predict the effect of random vs time-ordered keys on B-tree indexes and on range-sharded distributed databases
- Design customer-facing order and transaction references with check characters, separate from internal keys
TL;DR
- Decide from requirements: unique where? (table, service, globally), sortable by time?, 64 or 128 bits?, coordination allowed?, may it leak volume or time?, must humans read it?
- DB sequences are simple and compact but tie ID generation to one database; segment allocation (fetch a block of 1,000 ids at a time) removes the per-insert round trip.
- UUIDv4 is random and coordination-free but scatters B-tree inserts. UUIDv7 (RFC 9562) puts a millisecond timestamp first, so inserts are append-mostly while staying a standard 128-bit UUID. ULID is a similar idea with a 26-character Base32 text form.
- Snowflake: 64 bits = 41-bit ms timestamp + 10-bit worker id + 12-bit sequence ≈ 4 M ids/s per worker, k-sortable, fits a
BIGINT. It needs unique worker ids and careful clock-skew handling. - Time-ordered keys are great for single-node B-trees but can hotspot the last range in range-sharded distributed SQL databases.
- Customer-facing references (
ORD-3KX9-QM2T-7) should be short, unambiguous, carry a check character, and be separate from the internal primary key.
Why it matters
- Sharded and multi-region systems cannot rely on one auto-increment column. Orders created in two shards must not collide, and you want ids before the row is inserted (to publish events, to embed in idempotency records, to route by id).
- Banking: every transfer has an internal id, an idempotency key, references from the channel and from the scheme (an ISO 8583 STAN and RRN for card traffic, an ISO 20022
EndToEndIdand often a UUID-based UETR for SWIFT gpi payments), and a reference printed on the customer's receipt. Reconciliation depends on all of them being stored and searchable (see Reconciliation & Settlement). - E-commerce: order numbers are read over the phone to support agents and typed into return forms. Typos must be detected, and sequential numbers must not reveal to competitors that you processed 12,000 orders yesterday.
- Performance: a random 128-bit primary key on a write-heavy table can noticeably increase index size and I/O compared with a time-ordered one.
Core concepts
Requirements checklist
| Question | Why it matters |
|---|---|
| Uniqueness scope | Per table, per service, or global across regions and systems |
| Generation rate and availability | Can generation depend on a central DB, or must every node generate independently? |
| Ordering | Do you need ids roughly sortable by creation time (k-sortable)? Exact global order is rarely achievable |
| Size and type | 64-bit fits BIGINT and is cheap to index; 128-bit fits UUID |
| Leakage | Sequential ids reveal volume and enable enumeration; time-based ids reveal creation time |
| Readability | Will humans read, type or speak it? |
| Interoperability | Does a partner or standard require a format (length, character set)? |
Database sequences and ticket servers
- Auto-increment / sequences: compact, ordered, trivially unique within one database. PostgreSQL sequences are fast and non-transactional (rolled-back inserts leave gaps — gaps are normal, never rely on gap-free ids for accounting numbering).
- Multi-primary offsets: two databases with step 2 and offsets 1 and 2 generate odd and even ids. Works, but adding a third node means re-planning.
- Ticket servers (popularised by Flickr): a dedicated database whose only job is handing out ids from an auto-increment table, run as two servers with odd/even offsets for availability. Simple and strongly ordered per server, but a central dependency on every insert.
Segment allocation
Instead of one round trip per id, each application instance reserves a block of ids and hands them out from memory. Meituan's Leaf ("segment mode") is a well-known example of the pattern.
- One DB write per 1,000 ids; a short DB outage is absorbed by the buffered block (double buffering).
- IDs are unique and increasing per instance; globally they interleave (k-sortable within block granularity).
- Restarting an instance discards the rest of its block — gaps, which are fine.
- Still leaks volume if exposed directly.
UUIDv4
122 random bits (plus version and variant bits), generated anywhere with no coordination. Collision probability is negligible for practical volumes (you would need on the order of 2⁶¹ ids for a 50% chance). Downsides: 16 bytes, no time ordering, and random insert positions in B-tree indexes.
UUIDv7
Standardised in RFC 9562 (2024), which replaced RFC 4122:
| Bits | Field |
|---|---|
| 48 | Unix timestamp in milliseconds |
| 4 | Version (7) |
| 12 | Random, or a sub-millisecond counter for monotonicity |
| 2 | Variant |
| 62 | Random |
Same storage type as any UUID, sortable by creation time, ≈ 74 bits of randomness for uniqueness within a millisecond. It reveals creation time to anyone who sees it. Library support is now broad (for example github.com/google/uuid has NewV7; PostgreSQL 18 added a built-in uuidv7() function — check your versions).
ULID
48-bit millisecond timestamp + 80 random bits, encoded as 26 Crockford Base32 characters (01J9Z3K7Q4M8T2W6X0B5N9R1CD) that sort lexicographically by time. A "monotonic" mode increments the random part for ids generated in the same millisecond on one node. Not an IETF standard, but widely implemented; UUIDv7 now covers most of the same use cases with standard tooling.
Snowflake
Twitter's Snowflake (2010) packs a sortable id into a signed 64-bit integer:
| Bits | Field | Notes |
|---|---|---|
| 1 | Sign | Always 0 so the id stays positive |
| 41 | Milliseconds since a custom epoch | ≈ 69 years of range |
| 10 | Worker id | 1,024 generators (often split 5 datacenter + 5 worker) |
| 12 | Sequence within the millisecond | 4,096 ids/ms per worker ≈ 4 M/s |
Operational concerns:
- Unique worker ids. Two processes with the same worker id generate duplicates. Assign ids from a coordination service with leases (etcd, ZooKeeper, a DB table), or derive from a Kubernetes StatefulSet ordinal; never from random numbers or IP addresses alone.
- Clock going backwards. NTP corrections, VM migrations or leap-second handling can move the clock back. Options: refuse to generate until the clock catches up (safe, briefly unavailable), keep using the last timestamp for small skews, or borrow from reserved bits. Configure NTP to slew rather than step.
- Sequence exhaustion. More than 4,096 ids in one millisecond on one worker means waiting for the next millisecond.
- Ordering is approximate. Ids from different workers are ordered only as well as their clocks agree (see Time, Clocks & Ordering). Never use id order as the authoritative order of financial events.
- Variants: Instagram generated similar ids inside PostgreSQL with a shard id instead of a worker id (so the id also routes to its shard); Sonyflake uses 10 ms time units and a 16-bit machine id; many companies tune the bit split for their scale.
Ordering and index locality
- Single-node B-tree (PostgreSQL, MySQL/InnoDB): time-ordered keys keep the working set of the index small and pages dense. In InnoDB the primary key is the clustered row order, so a random PK scatters entire rows, not just index entries. See Indexing and Storage Engines: B-Tree vs LSM.
- Range-sharded distributed SQL (Spanner, CockroachDB, TiDB): monotonically increasing keys make the newest range a write hotspot. Their documentation generally recommends random UUIDs, hash-prefixed keys or features like TiDB's
AUTO_RANDOMinstead. - Hash-sharded stores (Cassandra, DynamoDB): the partition key is hashed, so ordering of the id barely matters for distribution; it matters for clustering/sort keys within a partition.
- Size: 8-byte
BIGINTvs 16-byteUUID— every secondary index repeats the primary key (InnoDB) or a pointer, so size compounds. Never store UUIDs asVARCHAR(36).
Human-friendly IDs for orders and transactions
Internal keys and customer-facing references have different jobs. Keep a compact internal primary key (Snowflake, UUIDv7) and a separate, unique, indexed public reference:
- Alphabet: Crockford Base32 (
0-9andA-ZwithoutI,L,O,U) avoids confusing0/Oand1/I/L; decode leniently (mapO→0,I/L→1, ignore hyphens and case). - Length: 8–10 characters plus a check character is readable over the phone. 8 Base32 characters = 40 bits ≈ 1.1 × 10¹² values.
- Check character: catch typos before a database lookup — Luhn for digits (card numbers), Luhn mod N for alphanumerics, ISO 7064 MOD 97-10 (the IBAN scheme). Reject invalid references at the edge, which also blunts enumeration and cache-penetration attacks (see Caching).
- Grouping and prefix:
ORD-3KX9-QM2T-7,TRF-…; the prefix tells support what kind of object it is. - Source of the value: either random (with a unique constraint and retry — collisions become likely around √N codes by the birthday bound, so expect and handle them) or an encoding of the internal id (unique by construction, but leaks volume or time and is longer).
- Do not embed personal data, account numbers or anything secret. Do not rely on unguessability for authorization — always check ownership.
- Banking specifics: store the scheme references (STAN, RRN,
EndToEndId, UETR) alongside your own id; they are unique only within their context (terminal, day, scheme) and are what counterparties will quote in disputes.
Trade-offs
| Scheme | Strengths | Weaknesses | Choose when |
|---|---|---|---|
| DB sequence / auto-increment | Compact, ordered, simple | Single-DB dependency, leaks volume, breaks with sharding | Single database, internal ids |
| Ticket server | Global, ordered, simple | Central dependency per insert | Moderate rates, few writers |
| Segment allocation | Fast, compact, survives short DB outages | Gaps, interleaved order, central allocator | High-rate 64-bit ids with a DB already in place |
| UUIDv4 | No coordination, unguessable-ish | 16 bytes, random index inserts, unsortable | Distributed SQL, ids exposed publicly, low write rates |
| UUIDv7 | No coordination, time-ordered, standard UUID | Leaks creation time, 16 bytes | Default modern choice for new services |
| ULID | Sortable, readable 26-char text | Not an IETF standard | Text-centric systems, logs, legacy ULID users |
| Snowflake | 64-bit, sortable, very fast | Worker-id management, clock skew | High-volume systems wanting BIGINT keys |
| Random public reference + check char | Short, readable, typo-resistant | Needs uniqueness check and retries | Order numbers, receipts, support references |
In practice
- JSON and 64-bit ids: JavaScript numbers lose precision above 2⁵³. Serialise 64-bit ids as strings in JSON APIs (Twitter's API famously added
id_strfor this reason). - Generate ids in the application, before insert, so the same id can go into the outbox event, the idempotency record and logs in one transaction.
- PostgreSQL:
gen_random_uuid()(v4) is built in since version 13; use theuuidtype. MySQL: store UUIDs asBINARY(16). - A Snowflake generator in Go (single process, mutex-protected):
package snowflake
import (
"errors"
"sync"
"time"
)
const (
workerBits = 10
sequenceBits = 12
maxWorker = 1<<workerBits - 1
maxSequence = 1<<sequenceBits - 1
workerShift = sequenceBits
timeShift = workerBits + sequenceBits
maxBackwards = 5 // ms of clock regression we tolerate by reusing lastMs
)
// epoch is a custom epoch (2024-01-01 UTC) to make the 41-bit range last.
var epoch = time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC).UnixMilli()
var ErrClockBackwards = errors.New("snowflake: clock moved backwards")
type Generator struct {
mu sync.Mutex
worker int64
lastMs int64
sequence int64
now func() int64 // Unix ms; injectable for tests
}
// New creates a generator; worker must be unique across the fleet (lease it).
func New(worker int64) (*Generator, error) {
if worker < 0 || worker > maxWorker {
return nil, errors.New("snowflake: worker id out of range")
}
return &Generator{worker: worker, now: func() int64 { return time.Now().UnixMilli() }}, nil
}
func (g *Generator) Next() (int64, error) {
g.mu.Lock()
defer g.mu.Unlock()
ms := g.now()
if ms < g.lastMs {
if g.lastMs-ms > maxBackwards {
return 0, ErrClockBackwards // refuse rather than risk duplicates
}
ms = g.lastMs // small regression: stay on the last timestamp
}
if ms == g.lastMs {
g.sequence = (g.sequence + 1) & maxSequence
if g.sequence == 0 { // 4,096 ids used in this ms: spin to the next ms
for ms <= g.lastMs {
ms = g.now()
}
}
} else {
g.sequence = 0
}
g.lastMs = ms
return (ms-epoch)<<timeShift | g.worker<<workerShift | g.sequence, nil
}
- A readable reference with a Luhn mod 32 check character:
package refcode
import "strings"
// Crockford Base32: no I, L, O, U.
const alphabet = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"
var lenient = strings.NewReplacer("-", "", "I", "1", "L", "1", "O", "0")
// Encode renders n as width Base32 chars plus a check char, grouped by 4,
// e.g. Encode("ORD", n, 8) -> "ORD-3KX9-QM2T-7".
func Encode(prefix string, n uint64, width int) string {
body := make([]byte, width)
for i := width - 1; i >= 0; i-- {
body[i] = alphabet[n%32]
n /= 32
}
s := append(body, alphabet[check(body)])
var b strings.Builder
b.WriteString(prefix)
for i, c := range s {
if i%4 == 0 {
b.WriteByte('-')
}
b.WriteByte(c)
}
return b.String()
}
// Valid reports whether code has a correct check character.
func Valid(prefix, code string) bool {
s := lenient.Replace(strings.TrimPrefix(strings.ToUpper(code), strings.ToUpper(prefix)))
if len(s) < 2 {
return false
}
body := []byte(s[:len(s)-1])
for _, c := range body {
if strings.IndexByte(alphabet, c) < 0 {
return false
}
}
return alphabet[check(body)] == s[len(s)-1]
}
// check computes a Luhn mod N (N = 32) check value over body.
func check(body []byte) int {
factor, sum := 2, 0
for i := len(body) - 1; i >= 0; i-- {
addend := factor * strings.IndexByte(alphabet, body[i])
factor = 3 - factor
sum += addend/32 + addend%32
}
return (32 - sum%32) % 32
}
Pair Encode with 40 random bits from crypto/rand, a UNIQUE constraint on the reference column, and a retry on conflict.
Common pitfalls
- 64-bit ids as JSON numbers. Symptom: the web app shows or requests an order id that differs in the last digits; "order not found" for valid orders.
- Duplicate Snowflake worker ids after copying a config or scaling a Deployment. Symptom: rare primary-key violations or, worse, silently merged records in systems without unique constraints.
- Ignoring clock regression. Symptom: duplicate ids after an NTP step or VM live migration.
- Random UUID primary keys on a hot InnoDB table. Symptom: index size and write I/O grow faster than row count; buffer-pool hit ratio drops.
- Sequential keys on Spanner/CockroachDB/TiDB. Symptom: one node at 100% CPU handling all inserts.
- Exposing sequential ids publicly. Symptom: competitors infer order volume; attackers enumerate
/orders/10001,/orders/10002and find authorization gaps (IDOR). - Gap-free numbering assumed from sequences. Symptom: auditors ask about "missing" invoice numbers. If regulations require gap-free invoice numbers, generate them in a dedicated, transactional counter.
- Using the order id as the idempotency key. The client must generate the idempotency key before the first attempt; a server-generated id cannot deduplicate retries of the creating request.
Interview angle
- Where it appears: "Design a unique ID generator in distributed systems" (SDI Vol. 1, Ch. 7), and inside URL shortener, chat (message ids), payment and order designs.
- Strong answer covers: requirements first; a comparison of at least sequences/segments, UUIDs and Snowflake; bit-layout maths (ids per ms, years of range); worker-id assignment; clock-skew handling; index locality; JSON precision; and public vs internal ids.
- Follow-ups: "How many ids per second can one worker produce?", "What happens when the clock moves back?", "How do you assign worker ids in Kubernetes?", "UUIDv4 or v7 for the payments table?", "How would you design a customer-facing order number?"
- Red flags: relying on timestamps alone, random worker ids, no clock-skew answer, assuming global ordering of ids equals event order, exposing auto-increment ids without considering enumeration.
Self-check
1. Compute the capacity of the standard Snowflake layout per worker and in total, and its lifetime.
12 sequence bits = 4,096 ids per millisecond per worker ≈ 4.1 M ids/s per worker. 10 worker bits = 1,024 workers ≈ 4.2 × 10⁹ ids/s in total. 41 bits of milliseconds ≈ 2.2 × 10¹² ms ≈ 69.7 years from the custom epoch.
2. Why does UUIDv7 usually index better than UUIDv4 in PostgreSQL, and when might v4 be preferable?
UUIDv7 starts with a millisecond timestamp, so new keys land at the right edge of the B-tree, keeping pages dense and the hot part of the index small and cached; v4 inserts at random leaves, causing page splits and a large working set. v4 can be preferable when the key must not reveal creation time, or in range-sharded distributed databases where sequential keys would hotspot the newest range.
3. Describe segment allocation and its failure behaviour.
Each instance reserves a block of ids (for example 1,000) with one atomic UPDATE … RETURNING on an allocator row, serves them from memory, and prefetches the next block when the current one runs low. A brief allocator outage is absorbed by the buffer. A crash wastes the rest of the block (gaps). IDs are unique and increasing per instance but interleave across instances.
4. How should a Snowflake generator handle the clock moving backwards by 2 ms? By 2 seconds?
For a small regression, keep using the last timestamp and continue the sequence (or wait 2 ms) — no duplicates and negligible delay. For a large regression, refuse to issue ids (return an error, mark the instance unready) until the clock passes the last timestamp, and alert; issuing ids would risk duplicates. Configure NTP to slew instead of step to make large jumps rare.
5. Scenario: design the order number for a marketplace doing 2 M orders per day.
Keep a Snowflake or UUIDv7 primary key internally. Generate a public reference from 50 random bits (10 Crockford Base32 characters) plus a Luhn mod 32 check character, shown in groups of four such as ORD-7QK2-M9XT-4RA, with a unique index and retry on conflict. Decode leniently, validate the check character before any lookup, rate-limit lookups, and always check ownership. Serialise ids as strings in JSON.
6. Why are sequential public ids a security and business risk?
They are enumerable: an attacker can iterate ids and exploit any missing authorization check (IDOR) to read others' orders or statements. They also leak business metrics: the difference between two order numbers a week apart reveals order volume. Time-based ids leak creation times. Use non-sequential public references and enforce authorization on every access.
Exercise
- Implement the Snowflake generator and write tests with an injected clock: normal operation, 5,000 ids in one millisecond (must spill into the next), a 2 ms regression (no duplicates), a 2 s regression (error).
- Generate 10 M ids concurrently from 8 goroutines and verify there are no duplicates.
- In PostgreSQL, create two tables with 20 M rows each: one keyed by UUIDv4, one by UUIDv7. Compare
pg_relation_sizeof the primary-key indexes and insert throughput withpgbenchor a Go loader. - Implement
refcode, then write a test that every single-character substitution of a valid code is rejected.
Done looks like: passing tests, a two-row table of index size and insert rate (v4 vs v7), and a short note on which you would use for a payments table.
Further reading
- RFC 9562, "Universally Unique IDentifiers (UUIDs)" (2024), rfc-editor.org.
- Twitter Engineering, "Announcing Snowflake" (2010).
- Instagram Engineering, "Sharding & IDs at Instagram" (2012).
- Flickr engineering blog, "Ticket Servers: Distributed Unique Primary Keys on the Cheap" (2010).
- Meituan tech blog, "Leaf — Meituan's distributed ID generation system" (segment and Snowflake modes).
- The ULID specification (github.com/ulid/spec) and Douglas Crockford's Base32 encoding description.
- System Design Interview, Vol. 1 (Alex Xu), Ch. 7 "Design a Unique ID Generator in Distributed Systems".
Related
- Database Replication & Sharding — shard-aware ids and routing.
- Indexing — why key order affects B-tree performance.
- Time, Clocks & Ordering — why id order is not event order.
- Idempotency & Exactly-Once — client-generated idempotency keys.
- URL Shortener — id generation and Base62 encoding in a classic design.
- Order Management & State Machines — where order references live.
- Payments & Card Flows — STAN, RRN and scheme references.
Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).