Skip to content

ID Generation at Scale ​

"UUID versions that are not time ordered, such as UUIDv4 (described in Section 5.4), have poor database-index locality. This means that new values created in succession are not close to each other in the index; thus, they require inserts to be performed at random locations." — RFC 9562, Universally Unique IDentifiers (UUIDs), May 2024

Summary: An ID generator is a choice between four things that pull against each other: uniqueness without coordination, size, order, and what the value reveals when it leaves your system. Focus: Sequences and identity columns, UUID v1/v4/v7, ULID, KSUID, Snowflake and its relatives, hi/lo and ticket servers, B-tree locality, collision maths, storage types, exposure, and idempotency keys. Learning goal: Pick a primary-key strategy for a single database, a sharded fleet and a public API, predict its failure mode (gaps, clock skew, page splits, enumeration), and implement it in SQL, Go and Laravel.

This page is the complete reference for generating identifiers. Schema design owns the question "bigint or UUID for this table"; this page owns how every generator works underneath and what it costs at scale. The index structure behind the locality argument is taught in indexing and B-tree vs B+Tree; shard routing is in partitioning and sharding and consistent hashing; concurrency of sequence access touches locks and concurrency.

Page map ​

If you are looking forGo to
Every generator in one tableEverything in one minute
Why a plain counter stops working, and the trade-offWhy ID generation is hard
Where Snowflake, Instagram, UUID v7 and ULID came fromWhere it comes from
One generator, with timeline, scenarios, per-engine table, fixThe generators, one by one
Sequences, CACHE, gaps, int4 exhaustion, AUTO_INCREMENT lock modesSequences and identity, auto_increment
Offset/step, Instagram's PL/pgSQL, Flickr tickets, hi/loAcross shards
UUID v1/v4/v6/v7/v8, ULID, KSUID, ObjectId, timeuuidIdentifier formats
Snowflake bits, clock skew, machine IDs, Sonyflake, DiscordSnowflake family
Page splits, index size, uuid vs text, UUID_TO_BINIndex locality and storage
Collision probability, birthday mathsCollision maths
Enumeration, Hashids/sqids, public vs internal IDsExposing IDs
Idempotency keys, ordering across nodes, leap secondsOrdering, clocks and idempotency
Exact functions and errors per engineMechanics, Per-engine behaviour
Working SQL, Go, LaravelSolving the classic problems, Go, Laravel
Which generator for which workloadChoosing a generator
Monolith to many shardsIn architecture
Reproduce v4 vs v7 index bloatLab
Wrong beliefs, cheat sheet, termsMisconceptions, Cheat sheet, Glossary

Everything in one minute ​

The generators. Every row is unpacked below.

GeneratorSizeOrdered by time?Needs coordination?Biggest catch
Sequence / identity (PostgreSQL), AUTO_INCREMENT (MySQL)4 or 8 bytesBy insert order, per databaseYes: one allocator per sequenceGaps; one writer; int4 exhaustion; reveals volume
Offset/step sequences8 bytesRoughlyAt setup: fixed number of nodesChanging the node count is painful
Ticket server (Flickr)8 bytesRoughlyYes: an extra serviceExtra moving part, single point of failure unless doubled
Hi/lo8 bytesRoughlyOne round trip per blockGaps after a crash; block-order not global order
UUIDv416 bytesNoNoneRandom inserts, wide keys
UUIDv116 bytesNot in byte orderMAC/node and clock sequenceTimestamp is in the wrong byte order; leaks node
UUIDv716 bytesYes (ms)NoneOrder inside a millisecond only if the generator adds a counter
ULID16 bytes (26 chars)Yes (ms)NoneSame; string form is case-insensitive base32
KSUID20 bytes (27 chars)Yes (seconds)NoneSecond resolution, bigger
Snowflake8 bytesYes (ms)A unique node ID per processClock going backwards; node ID assignment
Sonyflake8 bytesYes (10 ms)A unique machine IDOnly 256 IDs per 10 ms per instance
MongoDB ObjectId12 bytesYes (seconds)NoneOnly second resolution; counter per process
Cassandra timeuuid16 bytesWithin a column, by timeNoneIt is a v1 UUID; leaks MAC-like node
DynamoDBnone built inn/aYou chooseNo auto-generated keys at all

The four properties.

PropertyQuestion to askCheap wayExpensive way
UniquenessCan two writers ever produce the same value?One allocatorRandom bits plus enough of them
SizeHow many bytes per key, per index entry, per foreign key?bigint (8)UUID (16), string (26 to 36+)
OrderDo new rows land at the end of the index?Time prefixRandom value
ExposureWhat does the value tell a stranger?Opaque random public IDRaw sequence or Snowflake in the URL

Three things to do.

SituationDo this
One database, internal IDsbigint GENERATED ALWAYS AS IDENTITY (PostgreSQL) or BIGINT AUTO_INCREMENT (MySQL)
Many writers, microservices, offline clients, shardedUUIDv7 in a native uuid / BINARY(16) column; generate in the application
ID visible to users or partnersKeep the internal key, add a separate random public ID, and authorise every read

Why ID generation is hard ​

An ID must be unique forever, cheap to produce, small enough to index, and (ideally) helpful to the B-tree. One database can satisfy all of that by keeping one counter. The moment two machines may create rows without talking to each other, "next number" has no single meaning. Everything in this page is a different way to avoid the conversation, or to make it cheap.

Simple (central counter)Rich (decentralised generator)
8-byte keys, perfectly dense8 to 16 bytes, sparse
One allocator: simple, and the bottleneckAny node can generate: scales, can run offline
Order is exact insert orderOrder is approximate (clock-based) or absent
Reveals volume and growthReveals creation time (v7, Snowflake) or nothing (v4)
Gaps, but monotonicDuplicates are impossible only if the assumptions hold (clock, node ID)
Failure: the database is down, nobody can insertFailure: clock skew, duplicate node IDs, silent collisions in a bad RNG

The analogy we reuse on this page: paper ticket books at a city office. One counter issues numbers from one book: unique, in order. A second counter with its own book starts at 001, so the stubs collide when they reach head office. Counters that use "odd numbers only" and "even numbers only" never collide (offset/step). A counter that takes a whole book of 100 stubs at a time (hi/lo) visits the supply room rarely. A clerk who files letters in random drawers (UUIDv4) never collides but must keep the whole cabinet on the desk; filing by date (UUIDv7) keeps work at the front.

Three common misunderstandings, up front ​

  1. "IDs are just a column default." The default is only where the code runs. Whether it is safe on a replica set, a shard, a restored backup or an offline client is the real design question.
  2. "A UUID can never collide, and an unguessable ID is secure." Collisions are astronomically unlikely only with a good random source; and RFC 9562 says UUIDs "MUST NOT be used as security capabilities". Authorise every read.
  3. "Time-ordered means strictly ordered." It is ordered by the generator's clock at millisecond (or second) resolution. Across nodes there is no order at all, and inside one millisecond there is none unless a counter is added.

Where it comes from ​

For most of database history the primary key came from the database itself. A sequence or an AUTO_INCREMENT column hands out the next integer, and that is enough while one server owns the table. The problem appears when the data is split across machines, and Twitter hit it in 2010. Its engineering blog post introducing Snowflake says:

"Unlike MySQL, Cassandra has no built-in way of generating unique ids – nor should it, since at the scale where Cassandra becomes interesting, it would be difficult to provide a one-size-fits-all solution for ids. Same goes for sharded MySQL."

Twitter's requirements were that IDs be generated without coordination, be roughly sortable by time, and fit in 64 bits. It rejected ticket servers, UUIDs and ZooKeeper sequential nodes. The blog says "all the schemes we could find required 128 bits" for UUIDs, and that ZooKeeper sequential nodes did not give "the performance characteristics we needed" and "would lower our availability for no real payoff". The archived 2010 README describes the split as 41 bits of time, 10 bits of machine ID and 12 bits of sequence, and promises IDs that are k-sorted "within a reasonable bound (we're promising 1s, but shooting for 10's of ms)". The blog adds that sequence numbers are per-thread and "worker numbers are chosen at startup via zookeeper (though that's overridable via a config file)", and calls the code "alpha-quality".

Instagram's 2012 post describes the same wall from a PostgreSQL shop:

"The typical solution that works for a single database — just using a database's natural auto-incrementing primary key feature — no longer works when data is being inserted into many databases at the same time."

It lists the options it weighed: application-side UUIDs, Twitter's Snowflake (rejected for "additional complexity" and the extra "moving parts (ZooKeeper, Snowflake servers)"), and Flickr's ticket servers ("two ticket DBs (one on odd numbers, the other on even)"). Instagram's own scheme brought a Snowflake-like layout inside PostgreSQL.

UUID version 4 came from RFC 4122 and was revised by RFC 9562 (May 2024), which added UUIDv6, v7 and v8 and states "Implementations SHOULD utilize UUIDv7 instead of UUIDv1 and UUIDv6 if possible." The ULID specification (ulid/spec) was partly inspired by Instagram's post and describes a 128-bit, time-prefixed value in 26 Crockford base32 characters. PostgreSQL 18 shipped a built-in uuidv7() (the PostgreSQL 19 manual lists gen_random_uuid()/uuidv4() and uuidv7()), and Laravel's HasUuids trait generates UUIDv7 by default.

Claims in this page that did not come from a document we fetched and read (Discord's snowflake layout, Flickr's exact SQL, KSUID details beyond its README, Cassandra's timeuuid) are marked as such where they appear.

The generators, one by one ​

Each block follows the same order: plain words, the usual wrong belief, definition, a timeline, real scenarios, engine differences, and the fix.

Sequences and identity columns Must-know ​

In plain words: a sequence is a counter that lives in the database and gives out the next number each time you ask. It is outside your transaction: once a number is handed out, it is gone.

Common misunderstanding: "My keys are gapless because I use a sequence." Never. A rolled-back insert, a crash, a failed INSERT ... ON CONFLICT, or a cached block that a session abandons all leave holes. PostgreSQL's manual: "Because nextval and setval calls are never rolled back, sequence objects cannot be used if 'gapless' assignment of sequence numbers is needed."

Definition: PostgreSQL CREATE SEQUENCE name [ AS data_type ] [ INCREMENT BY n ] [ MINVALUE ] [ MAXVALUE ] [ START WITH n ] [ CACHE n ] [ [ NO ] CYCLE ] [ OWNED BY column ]. The data type is smallint, integer or bigint (default bigint). nextval('s') advances and returns; currval('s') returns the value last obtained by nextval in this session; lastval() returns the last nextval of any sequence in this session; setval('s', n) resets. An identity column (GENERATED { ALWAYS | BY DEFAULT } AS IDENTITY) is the SQL-standard way to attach an implicit sequence to a column; the legacy serial/bigserial pseudo-types do the same with a default expression.

text
     Session A                          Session B                       sequence last_value
1    BEGIN;                             BEGIN;                          100
2    INSERT ... (id = nextval -> 101)                                   101
3                                       INSERT ... (id = nextval -> 102) 102
4    ROLLBACK;                          COMMIT;                         102   -- 101 is a permanent gap
5    -- crash of the server here: PostgreSQL logs a sequence only every 32 values,
6    -- so after recovery the counter may jump ahead by up to 32 (never back)

Real scenarios: an invoice table that must have consecutive numbers fails an audit because bigserial skipped numbers; an int4 primary key on a busy event table reaches 2,147,483,647 on a Friday night and every insert fails; a developer calls setval after a bulk COPY with explicit IDs, forgets, and the next normal insert fails with a duplicate key; a replica promoted after failover has a sequence behind the data because the primary's cache and the last logged value differ.

CACHE, gaps and ordering ​

CACHE n makes each session pre-allocate n values and serve them from memory. The manual: "any numbers allocated but not used within a session will be lost when that session ends, resulting in 'holes' in the sequence." And "with a cache setting of 10, session A might reserve values 1..10 and return nextval =1, then session B might reserve values 11..20 and return nextval =11 before session A has generated nextval =2." So with CACHE > 1 assume values are distinct but not generated in order, and that setval in one session is not noticed by others until they spend their cache.

SettingEffectUse when
CACHE 1 (default)Each nextval touches the sequence; values are issued in orderNormal tables
CACHE 50..1000Fewer sequence touches under heavy concurrency; larger holes; out-of-order across sessionsBulk loads, very hot insert paths
CYCLEWraps at MAXVALUE: only safe if old rows are goneRarely; rotating slots
NO CYCLE (default)Errors at the limitEverything else

Exhaustion: int4 to int8 ​

integer tops out at 2,147,483,647 (about 2.1 billion); bigint at 9,223,372,036,854,775,807. PostgreSQL's numeric-type page lists serial as 4 bytes, bigserial 8 bytes. When an integer identity runs out, PostgreSQL raises ERROR: nextval: reached maximum value of sequence "t_id_seq" (2147483647) (SQLSTATE 2200H, sequence_generator_limit_exceeded). Rows hitting 2.1 billion are common: 1,000 inserts per second exhaust it in about 25 days. Changing a column to bigint rewrites the table and every index; every foreign key column that references it must change too.

sql
-- Early warning: how close is every sequence to its limit?
SELECT schemaname, sequencename, data_type, last_value, max_value,
       round(100.0 * last_value / max_value, 2) AS pct_used
FROM   pg_sequences
WHERE  last_value IS NOT NULL
ORDER  BY pct_used DESC;
FixHowCost
Start with bigintid bigint GENERATED ALWAYS AS IDENTITY4 more bytes per row and per index entry; cheap insurance
Convert in placeALTER TABLE t ALTER COLUMN id TYPE bigint; and ALTER SEQUENCE t_id_seq AS bigint;Full table rewrite with ACCESS EXCLUSIVE lock; see zero-downtime migrations
Convert onlineNew bigint column, trigger/backfill in batches, swapWeeks of care; see billion-row tables
Buy timeALTER SEQUENCE ... MINVALUE -2147483648 RESTART WITH -2147483648 and count upward through the negative rangeDoubles the lifetime; confusing; temporary

Engine differences:

EngineCounterExhaustionRollback
PostgreSQLSequence object (nextval), identity or serialError 2200H at MAXVALUENever rolled back
MySQL / InnoDBAUTO_INCREMENT per table (counter is persisted in 8.0+)Next insert fails with error 1062 duplicate entry on the max valueLost, not reused
SQL ServerIDENTITY(seed, step) or SEQUENCE with NEXT VALUE FORArithmetic overflow error 8115Lost; the identity cache can also skip values (1,000 for int) after an unexpected restart
OracleSEQUENCE (NEXTVAL, CACHE 20 default) or GENERATED AS IDENTITYORA-08004 sequence exceeds MAXVALUELost; cache lost on restart or flush
SQLiteINTEGER PRIMARY KEY (rowid); AUTOINCREMENT keyword avoids reusePicks a random unused rowid once max is reached (without AUTOINCREMENT), or SQLITE_FULL with itRolled back with the transaction (no gap) because it is just max(rowid)+1
MongoDBNone for _id; ObjectId generated by the drivern/an/a
CockroachDBSERIAL maps to unique_rowid() (time plus node) by default, or SEQUENCEunique_rowid does not exhaustNot applicable
RedisINCR keyAt 2^63 − 1 returns an errorNot transactional

Fix:

sql
-- PostgreSQL: the recommended shape
CREATE TABLE orders (
  id         bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  created_at timestamptz NOT NULL DEFAULT now()
);

-- After bulk-loading explicit ids, realign the sequence
SELECT setval(pg_get_serial_sequence('orders', 'id'),
              (SELECT COALESCE(max(id), 1) FROM orders));
go
// Go: take the generated key with RETURNING (LastInsertId is not supported by PostgreSQL drivers)
var id int64
err := db.QueryRowContext(ctx,
    `INSERT INTO orders (created_at) VALUES (now()) RETURNING id`).Scan(&id)
php
// Laravel: migration with a bigint identity-like key (id() = unsignedBigInteger auto-increment)
Schema::create('orders', function (Blueprint $table) {
    $table->id();            // BIGINT UNSIGNED AUTO_INCREMENT (MySQL) / bigserial-style identity (PostgreSQL)
    $table->timestamps();
});

MySQL AUTO_INCREMENT and lock modes Must-know ​

In plain words: InnoDB keeps one counter per table. Taking the next value needs a short lock, and how long it is held depends on innodb_autoinc_lock_mode.

Common misunderstanding: "A multi-row INSERT always gets consecutive IDs." Only in modes 0 and 1. In the default mode 2, concurrent statements interleave and bulk inserts may leave gaps.

Definition (MySQL 8.4 manual): mode 0 (traditional): "all 'INSERT-like' statements obtain a special table-level AUTO-INC lock", held to the end of the statement. Mode 1 (consecutive): "bulk inserts" (INSERT ... SELECT, REPLACE ... SELECT, LOAD DATA) use that table lock, and "simple inserts" "avoid table-level AUTO-INC locks by obtaining the required number of auto-increment values under the control of a mutex". Mode 2 (interleaved): "no 'INSERT-like' statements use the table-level AUTO-INC lock, and multiple statements can execute at the same time". "Interleaved lock mode (innodb_autoinc_lock_mode=2) is the default" in 8.4, and it is unsafe for statement-based replication. In every mode "if a transaction that generated auto-increment values rolls back, those auto-increment values are 'lost'... Such lost values are not reused."

text
     Session A                                   Session B                          mode 0/1        mode 2
1    INSERT INTO t SELECT ... (1000 rows)        
2                                                INSERT INTO t VALUES (...)         waits           runs now
3    -- A's rows: ids 1..1000                    -- B's row                          1001            may take id 5 (interleaved)
4    -- table-level AUTO-INC lock held to end of statement under modes 0 and 1
ModeNameBulk insertsConsecutive within a statementStatement-based replication safe
0traditionaltable AUTO-INC lockYesYes
1consecutivetable AUTO-INC lock (simple inserts use a mutex)YesYes
2interleavedno table lockNo: gaps possible under concurrencyNo

Real scenarios: a hot INSERT ... SELECT import blocks all other writers on the table in mode 1 (they wait on AUTO-INC); switching to mode 2 lifts the wait at the cost of non-contiguous IDs; a replica using statement-based replication drifts from the primary because mode 2 assigned different IDs.

Fix: keep mode 2 (default) with row-based replication, never assume contiguity, and use a BIGINT UNSIGNED column (maximum 18,446,744,073,709,551,615). If you need contiguity within a batch, insert the batch with explicit IDs from your own allocator.

sql
-- MySQL: inspect and size
SHOW VARIABLES LIKE 'innodb_autoinc_lock_mode';
SELECT TABLE_NAME, AUTO_INCREMENT FROM information_schema.TABLES
WHERE TABLE_SCHEMA = DATABASE() ORDER BY AUTO_INCREMENT DESC;
-- INT UNSIGNED max 4294967295; INT max 2147483647; error 1062 when the counter cannot advance
go
// Go (database/sql, MySQL driver): Result.LastInsertId works here
res, err := db.ExecContext(ctx, `INSERT INTO orders (note) VALUES (?)`, note)
if err != nil { return err }
id, _ := res.LastInsertId() // first id of a multi-row insert; do not assume the rest are +1
php
// Laravel: DB::table('orders')->insertGetId(['note' => $note]) returns the generated id
$id = DB::table('orders')->insertGetId(['note' => $note]);

Sequences across shards: offset/step, ticket servers, hi/lo, Instagram Must-know ​

In plain words: when several databases each own part of a table, each one's counter starts at 1 and the keys overlap. You either partition the number space ahead of time, ask one place for numbers, ask in blocks, or build the key from more than a counter.

Common misunderstanding: "Each shard has its own table, so duplicate IDs are fine." They are fine until one query, one cache key, one message, one foreign key in another service, or one data merge uses the ID without the shard. Then id = 1 means two rows.

Definition: four classic answers.

SchemeHow it worksAdvantageCost / limitation
Offset/stepNode k of N issues k, k+N, k+2N... (auto_increment_increment = N, auto_increment_offset = k in MySQL; INCREMENT BY N START WITH k in PostgreSQL)No runtime coordination; plain integersN is frozen at design time; adding nodes needs a new scheme; ordering across nodes only approximate
Ticket server (Flickr)A tiny dedicated database whose only job is an auto-increment counter; clients ask it for IDs. Run two with odd/even steps for availability8-byte numbers; well understoodExtra service on every insert path; two servers no longer sort in global order
Hi/loAsk the database for a block (the "hi" value) and hand out the "lo" part from memoryOne round trip per block; very fast insertsA crash wastes the rest of the block; IDs from different app nodes interleave; block size is a tuning knob
Composite integer (Instagram)Pack time, logical shard and a per-table sequence into one bigint inside the databaseNo extra service; shard recoverable from the IDSequence modulo wraps; custom epoch; clock must not go backwards
text
     app node 1 (block size 100)          app node 2                      id_blocks.next_id
1    UPDATE id_blocks SET next_id=next_id+100 RETURNING next_id-100      -> 1      (node 1 owns 1..100)
2                                         UPDATE ... RETURNING          -> 101    (node 2 owns 101..200)
3    serves 1,2,3 ... from memory         serves 101,102,103 ... from memory
4    crash after using 1..40                                            -> 41..100 are never used (a gap, not a duplicate)
5    restarts, reserves a new block                                     -> 201..300

Real scenarios: Flickr's ticket servers use a table with one row and REPLACE INTO plus LAST_INSERT_ID() to take the next ID (Flickr's post was not read in full here; Instagram's post summarises it as "two ticket DBs (one on odd numbers, the other on even)"); Hibernate's hilo and pooled optimizers do the same thing from an ORM; Instagram generates the ID inside the insert default; a two-site MySQL pair uses auto_increment_increment = 2 with offsets 1 and 2 for active-active writes.

sql
-- MySQL: active-active pair, node 1 (odd) and node 2 (even)
-- node 1: SET GLOBAL auto_increment_increment = 2; SET GLOBAL auto_increment_offset = 1;
-- node 2: SET GLOBAL auto_increment_increment = 2; SET GLOBAL auto_increment_offset = 2;

-- PostgreSQL: the same with sequences
CREATE SEQUENCE orders_seq_node1 INCREMENT BY 4 START WITH 1;  -- node 1 of 4
CREATE SEQUENCE orders_seq_node2 INCREMENT BY 4 START WITH 2;  -- node 2 of 4

Instagram's scheme in PL/pgSQL ​

Instagram's post: "41 bits for time in milliseconds (gives us 41 years of IDs with a custom epoch)", "13 bits that represent the logical shard ID", "10 bits that represent an auto-incrementing sequence, modulus 1024". It used one PostgreSQL schema per logical shard (several thousand logical shards over far fewer physical servers) and this function as the column default:

sql
CREATE OR REPLACE FUNCTION insta5.next_id(OUT result bigint) AS $$
DECLARE
    our_epoch bigint := 1314220021721;
    seq_id bigint;
    now_millis bigint;
    shard_id int := 5;
BEGIN
    SELECT nextval('insta5.table_id_seq') % 1024 INTO seq_id;
    SELECT FLOOR(EXTRACT(EPOCH FROM clock_timestamp()) * 1000) INTO now_millis;
    result := (now_millis - our_epoch) << 23;
    result := result | (shard_id << 10);
    result := result | (seq_id);
END;
$$ LANGUAGE PLPGSQL;
-- CREATE TABLE insta5.our_table ("id" bigint NOT NULL DEFAULT insta5.next_id(), ...);

Two things a careful reader notices. The post says "41 years", but 2^41 ms is about 69.7 years. And the function shifts the time left by 23, so the 41 time bits end at bit 63, the sign bit of a bigint; signed IDs would go negative after 2^40 ms (about 34.8 years) from the epoch. Choose the epoch and layout so that the top bit stays zero (Twitter's layout reserves it).

What provides it: PostgreSQL (the function above), MySQL (a stored function or app side), SQL Server (SEQUENCE plus an expression), Oracle (sequence plus function). Because the shard ID is inside the key, a read can be routed from the ID alone.

Fix / use: offset/step for two or three fixed nodes; hi/lo for fast inserts from many app nodes against one database (Go snippet below); Instagram's pattern when you shard PostgreSQL and want 8-byte keys without a service; UUIDv7 or Snowflake when the application tier generates IDs.

go
// Package hilo hands out IDs from blocks reserved in the database. One round
// trip reserves a block of Size values ("hi"); the process then serves the "lo"
// part from memory until the block runs out. A crash loses the unused rest of
// the block, which is a gap, never a duplicate.
package hilo

import (
	"context"
	"database/sql"
	"sync"
)

// Allocator needs a table id_blocks(name text primary key, next_id bigint).
type Allocator struct {
	db   *sql.DB
	name string
	size int64

	mu   sync.Mutex
	next int64
	end  int64 // exclusive
}

func New(db *sql.DB, name string, size int64) *Allocator {
	return &Allocator{db: db, name: name, size: size}
}

// Next returns a unique ID, reserving a new block when the current one is spent.
func (a *Allocator) Next(ctx context.Context) (int64, error) {
	a.mu.Lock()
	defer a.mu.Unlock()
	if a.next >= a.end {
		var start int64
		// One atomic statement: the row lock serialises concurrent allocators.
		err := a.db.QueryRowContext(ctx,
			`UPDATE id_blocks SET next_id = next_id + $2
			   WHERE name = $1 RETURNING next_id - $2`, a.name, a.size,
		).Scan(&start)
		if err != nil {
			return 0, err
		}
		a.next, a.end = start, start+a.size
	}
	id := a.next
	a.next++
	return id, nil
}
php
// Laravel: take a block inside a transaction (id_blocks table), then serve it from memory
$start = DB::transaction(function () {
    $row = DB::table('id_blocks')->where('name', 'orders')->lockForUpdate()->first();
    DB::table('id_blocks')->where('name', 'orders')->update(['next_id' => $row->next_id + 100]);
    return $row->next_id;   // serve $start .. $start + 99
});

Identifier formats: UUID versions, ULID, KSUID, ObjectId, timeuuid Must-know ​

In plain words: a UUID is a 128-bit label written as 32 hex digits. The version nibble says how it was made: from a clock and a MAC address (v1), from random bits (v4), from a Unix millisecond clock plus random bits (v7).

Common misunderstanding: "UUID means random." Only version 4 (and the random parts of v7) are. Versions 1 and 6 are timestamp-based, 3 and 5 are hashes of a name, 7 is time-ordered, and 8 is vendor-defined.

Definition (RFC 9562): the 128-bit value has a 4-bit version (bits 48 to 51) and a 2-bit variant (10 for RFC 9562). The Nil UUID is all zeros; the Max UUID is all ones. v1 has a 60-bit Gregorian timestamp (100 ns ticks since 1582-10-15), a 14-bit clock sequence and a 48-bit node (usually a MAC); its time fields are stored low part first, so the bytes do not sort by time. v6 is v1 reordered so the timestamp is most significant first ("reordered for improved DB locality"). v7 is "a Unix timestamp in milliseconds in the most significant 48 bits" with the rest random apart from version and variant. v8 is for experimental or vendor-specific use. RFC 9562 also names two optional tricks for v7: a sub-millisecond fraction in rand_a, or a counter.

unix_ts_ms48 bitsver0111rand_a12 bitsvar10rand_b62 bits randomUUIDv7 (RFC 9562 section 5.7): 128 bits, sorts by time firstULID: 128 bits, written as 26 Crockford base32 characterstimestamp48 bits (10 chars)randomness80 bits (16 chars)Inside one millisecond neither format orders values unless the generator adds a counter
text
UUIDv7   019535d9-3df7-79fb-b466-fa907fa17f9e
         |----------|  ||  |       |
         48-bit ms     7   rand_a   rand_b (variant 10 in the top bits of this group)
UUIDv4   5b30857f-0bfa-48b5-ac0b-5c64e28078d1     (version 4, 122 random bits)
UUIDv1   c232ab00-9414-11ec-b3c8-9f6bdeced846     (time_low first; does not sort by time)
FormatLayoutSizeOrderReadable form
UUIDv160-bit time, 14-bit clock seq, 48-bit node16 BTime, but byte order wrong36 chars
UUIDv4122 random bits16 BNone36 chars
UUIDv6v1 reordered16 BTime36 chars
UUIDv748-bit ms, 74 random bits16 BTime (ms)36 chars
UUIDv8vendor-defined16 BDefined by you36 chars
ULID48-bit ms, 80 random bits16 BTime (ms)26 chars Crockford base32
KSUID (Segment)32-bit seconds since 2014-03-05, 128-bit random payload20 BTime (s)27 chars base62
MongoDB ObjectId4-byte seconds, 5-byte per-process random, 3-byte counter12 BTime (s), then counter24 hex chars
Cassandra timeuuidv1 UUID; CQL compares by timestamp first16 BTime36 chars
Snowflake1 + 41 + 10 + 12 bits8 BTime (ms)decimal integer

ULID, from the spec: 48-bit Unix milliseconds, "Won't run out of space 'til the year 10889 AD", 80 bits of randomness, Crockford alphabet 0123456789ABCDEFGHJKMNPQRSTVWXYZ, "Within the same millisecond, sort order is not guaranteed", and an optional monotonic mode where "the random component is incremented by 1 bit in the least significant bit position (with carrying)" and generation fails on overflow. The largest valid ULID is 7ZZZZZZZZZZZZZZZZZZZZZZZZZ because 26 characters carry 130 bits. KSUID's README (Segment): a 32-bit timestamp and a 16-byte payload, in base62 "that will lexicographically sort by timestamp". MongoDB documents ObjectId as a 4-byte timestamp (seconds), a 5-byte random value generated once per client-side process, and a 3-byte incrementing counter per process initialised to a random value.

Real scenarios: MySQL's UUID() returns version 1 values; PostgreSQL's uuid-ossp extension adds v1 generators; a mobile app that creates drafts offline generates UUIDv7 and syncs later; a log pipeline writes ULIDs so ORDER BY id approximates time order; a Cassandra time-series table uses timeuuid as a clustering column (Cassandra details from its CQL types documentation).

Per-engine support:

EngineNative typeBuilt-in generators
PostgreSQLuuid (16 bytes)gen_random_uuid() / uuidv4() (v4); uuidv7([shift interval]) in PostgreSQL 18+; uuid_extract_timestamp() (v1/v7), uuid_extract_version(); uuid-ossp for v1/v3/v5
MySQL / InnoDBBINARY(16) (no native type)UUID() (v1); UUID_TO_BIN(u, swap_flag), BIN_TO_UUID, IS_UUID; UUID_SHORT() is a 64-bit server-scoped number
SQL Serveruniqueidentifier (16 bytes)NEWID() (random), NEWSEQUENTIALID() (ordered, usable only as a column default)
OracleRAW(16)SYS_GUID()
SQLiteBLOB or TEXTNone (the app generates; randomblob(16))
MongoDBObjectId, or UUID as BSON binary subtype 4Driver generates ObjectId
CockroachDBUUIDgen_random_uuid(), uuid_generate_v4()
Cassandrauuid, timeuuiduuid(), now() (timeuuid), toTimestamp(), minTimeuuid()/maxTimeuuid() for range queries
DynamoDBno auto-generated keysnone: the client chooses the partition key (a random UUID or ULID is typical); a conditional write (attribute_not_exists(pk)) guards against reuse
RedisstringsINCR for counters; XADD auto IDs are <ms>-<seq>

Fix / how to use it:

sql
-- PostgreSQL 18+
CREATE TABLE events (
  id uuid PRIMARY KEY DEFAULT uuidv7(),
  payload jsonb NOT NULL
);
SELECT uuid_extract_timestamp(id), uuid_extract_version(id) FROM events LIMIT 3;

-- Before 18: gen_random_uuid() is v4; for v7 generate in the app, or use an extension/function

-- MySQL 8: the swap flag only helps v1 values, not v4 or v7
CREATE TABLE events (id BINARY(16) PRIMARY KEY DEFAULT (UUID_TO_BIN(UUID(), 1)), payload JSON);
SELECT BIN_TO_UUID(id, 1) FROM events;
go
// Go: github.com/google/uuid exposes NewV7() (UUID, error), time-ordered
id, err := uuid.NewV7()
if err != nil {
    return err
}
fmt.Println(id.String())
// Standard library only: crypto/rand.Read 16 bytes, set version and variant bits
// by hand (see the uuidv7 snippet below). Go 1.24's stdlib has no UUID type.
go
// Package uuidv7 builds UUIDv7 values by hand from the RFC 9562 layout
// (section 5.7): 48 bits of Unix time in milliseconds, the 4-bit version 0b0111,
// 12 random bits, the 2-bit variant 0b10 and 62 random bits.
package uuidv7

import (
	"crypto/rand"
	"fmt"
	"time"
)

// New returns a UUIDv7 for the current time in canonical 8-4-4-4-12 form.
// Values created within the same millisecond are not ordered among themselves.
func New() (string, error) {
	return at(time.Now())
}

func at(t time.Time) (string, error) {
	ms := uint64(t.UnixMilli())
	if ms >= 1<<48 {
		return "", fmt.Errorf("uuidv7: timestamp %d does not fit in 48 bits", ms)
	}

	var b [16]byte
	for i := 0; i < 6; i++ {
		b[i] = byte(ms >> (40 - 8*i)) // unix_ts_ms, big-endian, octets 0-5
	}
	if _, err := rand.Read(b[6:]); err != nil {
		return "", err
	}
	b[6] = 0x70 | (b[6] & 0x0f) // ver = 0b0111
	b[8] = 0x80 | (b[8] & 0x3f) // var = 0b10

	return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:16]), nil
}
php
// Laravel 13
use Illuminate\Support\Str;
Str::uuid();               // version 4
Str::uuid7();              // time-ordered; Str::uuid7(time: now()) accepts a timestamp
Str::ulid();               // 26-character ULID
// Models: HasUuids (UUIDv7 by default) or HasUlids
// Migrations: $table->uuid('id')->primary() or $table->ulid('id')->primary()

The MySQL swap flag deserves a sentence: UUID_TO_BIN(u, 1) swaps "the time-low and time-high parts (the first and third groups of hexadecimal digits)", which "moves the more rapidly varying part to the right" and "can improve indexing efficiency", but "time-part swapping assumes the use of UUID version 1 values" and for other UUIDs "provides no benefit". Do not use the flag with UUIDv7: v7 already starts with the time.

The Snowflake family Must-know ​

In plain words: a Snowflake ID is a 64-bit integer built from three counters glued together: the current time, the number of the machine, and a count within that millisecond. Because time is on top, numbers grow with time; because the machine number is in the middle, two machines never produce the same value.

Common misunderstanding: "Snowflake needs a central service." Twitter's original did run as a network service, but the algorithm needs only a unique machine ID per process. After start-up everything is local.

Definition: 1 unused bit, 41 bits of milliseconds since a custom epoch, 10 bits of node ID (Twitter's 2010 code: 5 datacenter bits and 5 worker bits), 12 bits of sequence. Capacity per node: 4,096 IDs per millisecond (about 4.1 million per second); 1,024 nodes; 2^41 ms is about 69.7 years from the epoch.

0timestamp41 bits, ms since custom epochnode10 bitssequence12 bits, 0..4095 per msbit 63bit 02^41 ms = 69.7 years | 1024 nodes | 4096 IDs per ms per node = 4.1 M/s/node2010 Twitter code splits node as 5 datacenter + 5 worker bits; Instagram uses 41 / 13 shard / 10 sequenceid = (now_ms - epoch) << 22 | node << 12 | sequence (sorts by time, then node, then sequence)
text
     time (ms since epoch)   node   seq     what happens
1    1000                    7      0       first ID in this millisecond
2    1000                    7      1       same millisecond: sequence increments
3    1000                    7      4095    sequence exhausted
4    1000 -> 1001                   0       wait for the next millisecond, reset sequence
5    clock steps back to 998        --      refuse (error) or wait until the clock passes 1001

Real scenarios: Discord's snowflake (Discord API reference, not fetched here): 42 bits of milliseconds since 2015-01-01, 5 bits worker, 5 bits process, 12 bits increment, so a client can compute the creation time of any message from its ID; Sonyflake (Sony) uses 39 bits in units of 10 ms (about 174 years), an 8-bit sequence ("2^8 IDs per 10 msec at most in a single instance", fewer than Snowflake) and 16 bits of machine ID taken from the private IP address; JavaScript numbers hold only 53 bits of integer precision, so a 64-bit Snowflake must travel as a string in JSON (Twitter's API carries both id and id_str); Instagram's variant puts the logical shard in the middle.

Clock skew and the backwards step ​

The wall clock can move backwards: an NTP step, a VM migration or restore, a manual change, a leap second applied as a step. A generator that trusts the clock may issue a value it already issued. Twitter's README: "Snowflake protects from non-monotonic clocks, i.e. clocks that run backwards" by refusing to issue IDs until the clock catches up.

StrategyWhat it doesCost
Refuse (the snippet)Returns an error while now < lastShort unavailability; the caller retries
WaitSleep until the clock passes lastLatency equal to the step; bad for large steps
Logical clocklast = max(last, now) and keep issuing from lastIDs keep flowing; time bits drift from reality during the skew
Monotonic offsetsAnchor wall time once, advance with Go's monotonic time.SinceSurvives NTP steps; slowly drifts from true time
Slew, do not stepConfigure chrony/NTP to slew; use leap-second smearingOperational discipline
Persist lastStore the last timestamp durably and compare at startSurvives a restore from an old snapshot

Machine IDs: ZooKeeper, etcd, configuration ​

The 10-bit node number must be unique among live generators.

SourceHowCatch
Static configOne number per host, or a StatefulSet ordinal (pod-3 is node 3)Manual; cloned VMs duplicate it
ZooKeeper sequential nodeTwitter's choice: each worker creates a sequential node at start-upNeeds ZooKeeper at start-up only, not per ID
etcd leaseTake a key under a lease (/nodes/<n>), keep it alive, release on exitA paused process can keep generating after its lease expired
Database rowINSERT ... ON CONFLICT into a nodes table with a lease timestampAnother dependency; fine at start-up
IP address bitsSonyflake: 16 bits of the private IPUnique only inside one /16
Random plus registrationPick at random and registerBirthday collisions among 1,024 values: use more bits

A paused node whose lease has expired can keep generating with an ID another node now owns. The defence is a fencing check at start-up and a short validity window.

go
// Package snowflake generates 64-bit, roughly time-ordered IDs without asking
// another node for anything at generation time. Layout, most significant bit
// first: 1 unused bit, 41 bits of milliseconds since Epoch, 10 bits of node ID,
// 12 bits of per-millisecond sequence.
package snowflake

import (
	"errors"
	"fmt"
	"sync"
	"time"
)

const (
	nodeBits     = 10
	sequenceBits = 12

	maxNode      = -1 ^ (-1 << nodeBits)     // 1023
	sequenceMask = -1 ^ (-1 << sequenceBits) // 4095

	nodeShift = sequenceBits
	timeShift = sequenceBits + nodeBits
)

// Epoch is a custom epoch. A recent epoch keeps the 41-bit millisecond field
// usable for about 69 years.
var Epoch = time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC)

// ErrClockMovedBack is returned instead of issuing an ID that could repeat an
// earlier one.
var ErrClockMovedBack = errors.New("snowflake: clock moved backwards")

type Generator struct {
	mu       sync.Mutex
	node     int64
	lastMS   int64
	sequence int64
}

func New(node int64) (*Generator, error) {
	if node < 0 || node > maxNode {
		return nil, fmt.Errorf("snowflake: node %d outside 0..%d", node, maxNode)
	}
	return &Generator{node: node, lastMS: -1}, nil
}

// Next returns the next ID. It is safe for concurrent use.
func (g *Generator) Next() (int64, error) {
	g.mu.Lock()
	defer g.mu.Unlock()

	now := time.Now().UnixMilli() // wall clock: NTP can step it backwards
	if now < g.lastMS {
		return 0, fmt.Errorf("%w: %d ms behind", ErrClockMovedBack, g.lastMS-now)
	}
	if now == g.lastMS {
		g.sequence = (g.sequence + 1) & sequenceMask
		if g.sequence == 0 {
			// All 4096 sequence values for this millisecond are used up.
			now = waitNextMillis(g.lastMS)
		}
	} else {
		g.sequence = 0
	}
	g.lastMS = now

	return (now-Epoch.UnixMilli())<<timeShift | g.node<<nodeShift | g.sequence, nil
}

// Time recovers the creation time encoded in an ID, at millisecond precision.
func Time(id int64) time.Time {
	return Epoch.Add(time.Duration(id>>timeShift) * time.Millisecond)
}

func waitNextMillis(last int64) int64 {
	for {
		now := time.Now().UnixMilli()
		if now > last {
			return now
		}
		time.Sleep(50 * time.Microsecond)
	}
}

Fix / how to use it (SQL and Laravel):

sql
-- PostgreSQL: Snowflake-like default; node supplied by the caller, sequence from a real sequence
CREATE SEQUENCE ids_seq;
CREATE FUNCTION snowflake_id(node int) RETURNS bigint LANGUAGE sql AS $$
  SELECT ((floor(extract(epoch FROM clock_timestamp()) * 1000)::bigint - 1577836800000) << 22)
         | (node::bigint << 12)
         | (nextval('ids_seq') % 4096);
$$;
php
// Laravel: no built-in Snowflake. Disable auto-increment and assign the ID in the creating event.
class Message extends Model
{
    public $incrementing = false;

    protected static function booted(): void
    {
        static::creating(function (Message $m) {
            $m->id ??= app(\App\Support\Snowflake::class)->next();
        });
    }
}

Index locality, page splits and storage type Must-know ​

In plain words: an index keeps its keys in sorted order inside 8 KB pages. A key that is bigger than every existing key goes to the last page. A random key goes into some page in the middle, so the database must find that page, load it, and sometimes split it in two.

Common misunderstanding: "UUIDs are slow because they are long." Length matters (below), but the bigger cost of UUIDv4 is where it lands: every insert dirties a different leaf page, so the whole index must stay in memory, and each page splits when it fills.

Definition: in a B-tree, inserting into a full leaf triggers a page split: allocate a new page, move about half the entries, and add a pointer in the parent. A key beyond the current maximum fills the rightmost leaf and starts a new one (PostgreSQL splits the rightmost page at the index fillfactor, 90 by default, instead of 50/50). Random insertion into a B-tree settles at an average leaf fill of about ln 2, roughly 69%, so a random-key index is about a third larger than a sequential one holding the same rows. After a checkpoint, the first change to each page is also written to the WAL as a full-page image, so random inserts produce far more WAL.

Random (UUIDv4)Time-ordered (UUIDv7, ULID, Snowflake)every leaf is a write target; pages split at ~50% fullinsertsold leaves stay full and cold; one hot right edgeinsertsWorking set of dirty index pages: whole index (left) vs one page (right)
text
     insert key           random UUIDv4                          time-ordered (v7, Snowflake, bigint)
1    k1                   leaf 17 (read from disk if cold)       rightmost leaf (cached)
2    k2                   leaf 402                               rightmost leaf
3    k3                   leaf 9, split (50/50)                  rightmost leaf, now full -> new leaf (90/10)
4    dirty pages so far   3                                      1..2
5    steady state         every leaf is a candidate              one hot leaf; old leaves stay cold and ~90% full

Real scenarios: a 500-million-row events table with a UUIDv4 primary key stops fitting in shared_buffers, and insert latency becomes bound by random reads; a nightly import into a UUIDv4 table writes five times the WAL of the same import into a bigint table; a replica's replay lag grows during bulk inserts because it must apply the full-page images; an InnoDB table (clustered on the primary key) with a random key has its table data fragmented, not just an index, and every secondary index also carries the wide primary key.

Costbigint identityUUIDv7UUIDv4
Key bytes81616
Index entries per 8 KB page (PostgreSQL, ballpark)about 360about 260about 200 (69% fill)
Dirty leaf pages per insert burst11many
Working set for insertsrightmost pagerightmost pagewhole index
Full-page WAL images after a checkpointfewfewmany
InnoDB secondary indexessmallestlarger (each carries the 16-byte PK)larger

Storing 128 bits: uuid vs text. PostgreSQL's uuid type is 16 bytes: "a 128-bit quantity". Stored as text or varchar(36) it is 36 characters plus a header, more than double, and comparisons are slower and collation-dependent. In MySQL there is no native type: use BINARY(16) with UUID_TO_BIN and BIN_TO_UUID; CHAR(36) stores 36 bytes for ASCII digits, which more than doubles the key and every secondary index (InnoDB appends the primary key to each secondary index entry). ULIDs have a 16-byte binary form: store that in uuid (PostgreSQL) or BINARY(16), and convert to the 26-character string at the edge. Laravel's ulid() and uuid() column methods create CHAR/UUID-equivalent columns; on PostgreSQL uuid() creates a native uuid.

Storage choicePostgreSQLMySQL / InnoDBSQL ServerSQLite
16-byte binaryuuidBINARY(16)uniqueidentifierBLOB
36-char texttext/varchar(36): avoidCHAR(36): avoidchar(36): avoidTEXT: allowed, larger
Clustered by PK?No (heap), key only affects the indexYes: PK order is the physical orderOptional (clustered index)Rowid table by default; WITHOUT ROWID clusters on the PK

How to measure it: the Lab below uses pgstatindex (from the pgstattuple extension). PostgreSQL documents its columns: leaf_pages, avg_leaf_density ("the fraction of the index size that is taken up by user data") and leaf_fragmentation. Neither PostgreSQL nor InnoDB exposes a per-index split counter; use leaf page count, density and WAL bytes as proxies.

Fix: use a time-ordered key (bigint identity, UUIDv7, Snowflake, ULID); store 128-bit IDs in a 16-byte type; if you must keep v4, lower fillfactor on the index (for example 70) to delay splits, and keep the index in memory; on MySQL with v1 UUIDs, swap with UUID_TO_BIN(u, 1).

sql
-- PostgreSQL
CREATE EXTENSION IF NOT EXISTS pgstattuple;
SELECT * FROM pgstatindex('events_pkey');  -- leaf_pages, avg_leaf_density, leaf_fragmentation
ALTER INDEX events_pkey SET (fillfactor = 70);  -- for random keys; REINDEX to apply to existing pages
go
// Go: scan a uuid column into a [16]byte-friendly type; pgx maps uuid to [16]byte or pgtype.UUID
var id [16]byte
err := pool.QueryRow(ctx, `SELECT id FROM events WHERE payload = $1`, p).Scan(&id)
php
// Laravel: native column types
$table->uuid('id')->primary();         // PostgreSQL uuid; MySQL CHAR(36)
$table->ulid('id')->primary();         // CHAR(26)
// For a 16-byte MySQL key use $table->binary('id', 16)->primary() and convert in a cast

Collision probability, the birthday bound Important ​

In plain words: with enough random 122-bit values, two can match, but "enough" is so large that it does not happen in practice. The danger is not the maths; it is a bad random-number generator, a copied seed, or an ID scheme with fewer random bits than you think.

Common misunderstanding: "A collision is impossible, so I do not need a unique constraint." The primary key constraint is what turns a one-in-a-trillion event into a clean error instead of silent corruption. Keep it.

Definition: for n values drawn uniformly from N possibilities, the probability of at least one collision is about n²/(2N) when it is small. For UUIDv4, N = 2^122 ≈ 5.3 × 10^36.

ScenarionProbability of any collision
UUIDv4, one billion rows10^9about 9 × 10^-20
UUIDv4, one trillion rows10^12about 9 × 10^-14
UUIDv4, 1-in-a-billion riskabout 1 × 10^1410^-9
UUIDv4, 50%about 2.7 × 10^180.5
UUIDv7, 1,000 IDs in the same millisecond (74 random bits)10^3about 3 × 10^-17
UUIDv7, a million IDs in one millisecond10^6about 3 × 10^-11
ULID, 80 random bits per millisecond, a million in one ms10^6about 4 × 10^-13
Snowflake, unique node IDsany0 (guaranteed) if node IDs and the clock hold
Snowflake, two processes share a node IDanycertain, as soon as both issue in the same ms with the same sequence

So random UUIDs are safe; broken assumptions are not. Real failure modes: VM images cloned with the RNG state or a fixed seed (identical "random" IDs), math/rand instead of crypto/rand in Go, rand() instead of random_bytes in PHP, copied Snowflake configuration, containers that all start with node ID 0, and client libraries that generate UUIDs from Math.random() in JavaScript.

Fix: use the platform CSPRNG (crypto/rand, PHP random_bytes, gen_random_uuid()), keep the unique constraint, and treat a duplicate-key error on an ID as a retry-with-new-ID event, not a crash.

sql
-- the constraint is the real guarantee; the generator only makes violations rare
ALTER TABLE events ADD CONSTRAINT events_pk PRIMARY KEY (id);
go
// Go: retry on a unique violation (SQLSTATE 23505) with a fresh ID
for attempt := 0; attempt < 3; attempt++ {
    id, _ := uuid.NewV7()
    _, err := db.ExecContext(ctx, `INSERT INTO events (id, payload) VALUES ($1, $2)`, id, p)
    var pgErr *pgconn.PgError
    if err == nil || !errors.As(err, &pgErr) || pgErr.Code != "23505" {
        return err
    }
}
php
// Laravel: UniqueConstraintViolationException (a QueryException subclass) means "pick a new id"
try {
    Event::create(['payload' => $p]);
} catch (\Illuminate\Database\UniqueConstraintViolationException $e) {
    Event::create(['payload' => $p]); // new id generated by HasUuids
}

Exposing IDs: enumeration, Hashids, sqids, public vs internal Important ​

In plain words: an ID in a URL is a piece of information. A sequential ID tells a stranger how many orders you have, and lets them try the next one. Hiding the ID is not the fix; checking permission is.

Common misunderstanding: "My IDs are random UUIDs, so nobody can guess them." Maybe so, but UUIDs leak through logs, referrer headers, shared links and email, and RFC 9562 says they "MUST NOT be used as security capabilities (identifiers whose mere possession grants access)". It also says that where a UUID is used in any security context, UUIDv4 "SHOULD be utilized", because the timestamp in a v7 value carries information.

Definition: enumeration (an IDOR, insecure direct object reference) is walking /orders/1001, /orders/1002... and reading other users' data because the server only checked "is it a valid order?". Information leak is learning volume (sequential), creation time (v1, v6, v7, ULID, Snowflake, ObjectId), and node (Snowflake, v1 MAC).

text
     attacker                                server (no ownership check)
1    GET /orders/1001  (own order)           200
2    GET /orders/1002                        200  <- somebody else's order (IDOR)
3    loop 1..N                               scrape everything
4    (fix) GET /orders/1002                  403/404: WHERE id = ? AND user_id = ?
TechniqueWhat it doesSecurity value
Authorise every read (WHERE id = ? AND tenant_id = ?, policies, row-level security)Stops enumeration at the rootThe real fix
Opaque public ID (random 128-bit token, separate column, unique index)Hides count and time; internal key stays smallGood; still authorise
Hashids / sqidsEncode a number as a short string like Uk3zP using a secret-seeded alphabetObfuscation only: it is reversible and not encryption; do not rely on it
Encrypt the ID (format-preserving, AES-based)Reversible with a keyReal secrecy, key management cost
UUIDv4 as the public keyUnguessableFine as an identifier; not a capability
Signed, expiring URLCapability with a MAC and TTLCorrect for "anyone with the link" sharing

Public vs internal IDs: keep a compact internal key (bigint, UUIDv7) for joins, foreign keys and clustering, and add a separate public_id (random v4 UUID or a 128-bit token) for URLs and API payloads. The cost is a second unique index and a lookup; the benefit is that the key you show can be rotated or changed without touching every foreign key, and that creation time is not leaked.

go
// Package publicid shows the internal/public split: the database keeps a
// compact internal bigint key, and the outside world sees an opaque random
// token that is looked up through a unique index. The token is only an
// identifier; every read must still be authorised.
package publicid

import (
	"crypto/rand"
	"encoding/base32"
	"strings"
)

var enc = base32.StdEncoding.WithPadding(base32.NoPadding)

// New returns a 26-character random token (130 bits, rounded up from 16 bytes).
func New() (string, error) {
	var b [16]byte
	if _, err := rand.Read(b[:]); err != nil {
		return "", err
	}
	return strings.ToLower(enc.EncodeToString(b[:])), nil
}

Real scenarios: an invoice endpoint returns another customer's PDF by incrementing the number (the classic IDOR); a competitor estimates daily orders from two order numbers a day apart (the "German tank problem"); a Discord-style snowflake exposes a message's creation time by design; a v7 primary key in a URL reveals when a user account was created.

sql
-- PostgreSQL: internal bigint + public uuid, ownership enforced in the query
CREATE TABLE orders (
  id        bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  public_id uuid NOT NULL DEFAULT gen_random_uuid() UNIQUE,
  user_id   bigint NOT NULL,
  total     numeric(12,2) NOT NULL
);
SELECT id, total FROM orders WHERE public_id = $1 AND user_id = $2;
go
// Go: look up by public id AND owner; "not found" and "not yours" look the same
err := db.QueryRowContext(ctx,
    `SELECT id, total FROM orders WHERE public_id = $1 AND user_id = $2`,
    publicID, userID).Scan(&id, &total)
if errors.Is(err, sql.ErrNoRows) {
    return ErrNotFound
}
php
// Laravel: route-model binding on the public column, scoped to the owner
class Order extends Model {
    public function getRouteKeyName(): string { return 'public_id'; }
}
Route::get('/orders/{order}', fn (Order $order) => $order);
// And always: $request->user()->orders()->where('public_id', $id)->firstOrFail();

Ordering across nodes, clocks, leap seconds and idempotency keys Important ​

In plain words: IDs sort by the clock of whoever made them. Two machines' clocks disagree by milliseconds or more, so an ID made later on node B can sort before an ID made earlier on node A. There is no global order unless one place numbers everything.

Common misunderstanding: "I can use the ID as the event order for replay." Within one node and one millisecond you may get ties; across nodes you get skew. Use a per-entity version number or a log offset for order, and the ID only for uniqueness and rough locality. Twitter's own words: IDs are "k-sorted" within "a reasonable bound", not totally ordered.

Definition: k-sorted means each item is at most k positions from its sorted place. Hybrid logical clocks (HLC) combine physical time with a counter so timestamps never go backwards and respect causality (used by CockroachDB). Spanner bounds clock error with TrueTime and waits it out. Without such machinery, wall clocks across nodes may be skewed by tens of milliseconds, so two IDs created 5 ms apart can sort the wrong way.

text
     node A (clock +0 ms)             node B (clock -12 ms)             sorted by ID
1    t=1000 create order #A           
2                                     t=1005 (real) -> stamps 993       #B (993)
3                                                                       #A (1000)  <- B's later write sorts first

Leap seconds. RFC 9562 defines UUIDv7's timestamp as "since midnight 1 Jan 1970 UTC, leap seconds excluded". UTC inserts an occasional extra second (23:59:60). Unix time has no such second, so the clock repeats a value or steps back by one second, unless the operating system or cloud provider smears it over many hours (Google, AWS). To a Snowflake generator that step is a backwards clock: it refuses or waits for up to a second. Smearing, or using a monotonic clock for deltas, avoids it. (The international standards body has voted to stop adding leap seconds by 2035; until then, plan for them.)

Idempotency keys. An idempotency key is an ID created by the caller for one logical operation (a payment, an order), sent with every retry, so the server can do the work once. It is an ID-generation problem with the opposite rule from a primary key: it must be the same across retries and unique across operations.

text
     client                               server                            db
1    POST /payments  Idempotency-Key: K1  begin
2                                         INSERT idempotency (K1) ON CONFLICT DO NOTHING   -> inserted
3                                         charge card, store response under K1
4    (timeout, client retries)
5    POST /payments  Idempotency-Key: K1  INSERT ... ON CONFLICT                           -> exists
6                                         return the stored response for K1 (no second charge)
RuleWhy
Client generates the key (UUIDv4 or v7) before the first attemptA key made by the server per attempt cannot dedupe retries
Server stores key + request fingerprint + responseA reused key with a different body must be rejected (HTTP 422 or 409)
Unique constraint on the key, scoped by tenantThe database is the arbiter under concurrency
Expire keys after a window (hours to days)Bounded storage; document the window
Same pattern in consumers: dedupe by message IDSee idempotent consumer / inbox and delivery guarantees
sql
CREATE TABLE idempotency_keys (
  tenant_id  bigint NOT NULL,
  key        text   NOT NULL,
  request_hash bytea NOT NULL,
  response   jsonb,
  created_at timestamptz NOT NULL DEFAULT now(),
  PRIMARY KEY (tenant_id, key)
);
INSERT INTO idempotency_keys (tenant_id, key, request_hash) VALUES ($1, $2, $3)
ON CONFLICT (tenant_id, key) DO NOTHING RETURNING key;   -- no row returned => replay
go
// Go: claim the key; if the row already exists, return the stored response
res, err := tx.ExecContext(ctx,
    `INSERT INTO idempotency_keys (tenant_id, key, request_hash) VALUES ($1,$2,$3)
     ON CONFLICT (tenant_id, key) DO NOTHING`, tenant, key, hash)
if err != nil {
    return err
}
if n, _ := res.RowsAffected(); n == 0 {
    return replayStoredResponse(ctx, tx, tenant, key)
}
php
// Laravel: insertOrIgnore returns the number of rows inserted
$claimed = DB::table('idempotency_keys')->insertOrIgnore([
    'tenant_id' => $tenant, 'key' => $key, 'request_hash' => $hash, 'created_at' => now(),
]);
if ($claimed === 0) {
    return response()->json(DB::table('idempotency_keys')->where(['tenant_id' => $tenant, 'key' => $key])->value('response'));
}

Mechanics ​

How the pieces work underneath, with the exact knobs and error codes.

TopicMechanismKnob / functionError or symptom
PostgreSQL sequenceA one-row relation; nextval is non-transactional and WAL-logged every 32 valuesCACHE, INCREMENT BY, MAXVALUE, CYCLE, OWNED BY2200H reached maximum value; duplicate key 23505 after setval mistakes
Identity columnImplicit sequence; ALWAYS rejects explicit values unless OVERRIDING SYSTEM VALUEGENERATED ALWAYS / BY DEFAULT AS IDENTITY428C9 cannot insert into a GENERATED ALWAYS column
Sequence statepg_sequences.last_value; currval is per sessionpg_get_serial_sequence, lastval()55000 currval not yet defined in this session
InnoDB auto-incrementIn-memory counter, persisted in 8.0+innodb_autoinc_lock_mode (0/1/2), auto_increment_increment, auto_increment_offset1062 duplicate entry at the type maximum
UUID v4122 random bits from the OS CSPRNGgen_random_uuid(), crypto/rand, Str::uuid()Duplicate key if the RNG is broken
UUID v748-bit ms + 74 random bits (or sub-ms + counter)uuidv7(), Str::uuid7(), uuid.NewV7()Ties within a millisecond if no counter
SnowflakeMutex around (time, sequence); node fixed at startEpoch, node bits, sequence bitsClock moved backwards; sequence overflow waits a millisecond
Hi/loBlock reserved with an atomic UPDATE ... RETURNINGBlock sizeGaps after restart
B-tree insertDescend, insert, split on overflowfillfactor, pgstatindexIndex bloat, WAL volume, shared-buffer misses
Postgres UUID type16 bytes, binary comparisonuuid_extract_timestamp, uuid_extract_version22P02 invalid input syntax for type uuid

Error codes verbatim:

EngineCode and messageMeaning
PostgreSQL2200H nextval: reached maximum value of sequence "x" (n)Sequence exhausted
PostgreSQL22P02 invalid input syntax for type uuidBad string, or a ULID/text passed to a uuid column
PostgreSQL23505 duplicate key value violates unique constraintID collision or replay
PostgreSQL428C9 cannot insert a non-DEFAULT value into column "id"Explicit ID into GENERATED ALWAYS
MySQL1062 Duplicate entry '2147483647' for key 'PRIMARY'Counter at the type maximum, or collision
MySQL1264 Out of range value for column 'id'Explicit value too big for INT
SQL Server8115 Arithmetic overflow error converting IDENTITY to data type intIdentity exhausted
OracleORA-08004 sequence exceeds MAXVALUESequence exhausted
SQLiteSQLITE_FULLAUTOINCREMENT table reached the maximum rowid
DynamoDBConditionalCheckFailedExceptionattribute_not_exists(pk) found an existing item

Per-engine behaviour ​

What each product really does.

ProductDefault key idiomTime-ordered built-in?Clustered on PK?Notable
PostgreSQLbigint GENERATED ... AS IDENTITYuuidv7() (18+)No (heap)Sequence not transactional; uuid type; logical replication has historically not carried sequence state (check your version's release notes): re-sync sequences after a failover or major-version upgrade
MySQL / InnoDBBIGINT AUTO_INCREMENTNo (UUID() is v1)Yesinnodb_autoinc_lock_mode=2 default (8.4); UUID_TO_BIN(u,1) for v1
SQL Serverbigint IDENTITY or SEQUENCENEWSEQUENTIALID()Clustered index by default on the PKNEWID() as a clustered key fragments badly
OracleGENERATED AS IDENTITY / SEQUENCENoHeap (index-organised optional)SYS_GUID() RAW(16); RAC sequences need CACHE and NOORDER for speed
SQLiteINTEGER PRIMARY KEY (rowid alias)NoRowid B-treeAUTOINCREMENT prevents reuse; UUIDs are your job
MongoDBObjectId in _idYes (seconds)_id index; WiredTiger clusters data by an internal RecordIdTime-ordered by default; _id can be any unique value
CockroachDBUUID DEFAULT gen_random_uuid(); SERIAL is unique_rowid()unique_rowid() is time+nodePrimary index range-partitionedSequential keys create a hot range; hash-sharded indexes avoid it
SpannerUUID or bit-reversed sequenceNoRows sorted by PKMonotonic keys hotspot a split; use a bit-reversed sequence or hashed prefix
CassandraUUID / timeuuidtimeuuidPartition key hashed; clustering key sortedNo auto-increment, by design
DynamoDBClient-generatedNonePartition key hashedNo auto IDs; high-cardinality keys spread load
RedisINCRXADD *n/aCounter is atomic; not durable by default

Distributed stores flip the rule. On a range-partitioned store (Spanner, CockroachDB, HBase, Bigtable), a monotonically increasing key sends all inserts to the last range: the hotspot that B-tree locality makes good inside one node makes bad across nodes. The fix is the reverse of the single-node advice: hash or bit-reverse a prefix, or spread writes across shards with a shard number first. On a hash-partitioned store (Cassandra, DynamoDB), the partition key is hashed anyway, so time-ordering helps only within a partition, in the clustering key.

Solving the classic problems ​

ProblemSolutionHowAdvantageCost / limitation
Sharded tables overlapApp-side UUIDv7 or SnowflakeGenerate before insertNo coordinationWider key (v7) or node IDs (Snowflake)
Sharded, want bigint and no serviceInstagram-style functionPL/pgSQL default with shard IDShard in the keyEpoch/sign-bit care; Postgres only
Primary-key index too large or slowSwitch v4 to v7New table + backfill, or new rows onlyLocality, smaller WALExisting v4 rows stay scattered
int4 exhaustingbigintIn-place rewrite or online migrationWide headroomLock or long backfill
Gapless invoice numbersCounter row with FOR UPDATELocks the counter inside the transactionGaplessSerialises all invoices; see locks
Public URL leaks volumeSeparate public IDRandom token column, unique indexHides count and timeSecond index and lookup
Duplicate submissionsIdempotency keyUnique constraint, store responseSafe retriesStorage, TTL
Cross-node order neededPer-entity version or log offsetNot the IDTrue orderNeeds a single sequencer per entity
Clock goes backwardsRefuse, wait or logical clockSee the strategy tableNever duplicatesBrief unavailability or drift
Duplicate node IDsLease from etcd/ZooKeeperFencing at startNo collisionsAnother dependency at start-up

Gapless numbers, the right way. If a law or an auditor requires consecutive numbers (invoices), do not use a sequence. Keep a counter row and increment it inside the same transaction that writes the invoice; if the transaction rolls back, so does the counter. The cost is that invoices for one counter are serialised.

sql
UPDATE invoice_counters SET last_no = last_no + 1 WHERE series = 'EU-2026' RETURNING last_no;
-- same transaction: INSERT INTO invoices (number, ...) VALUES (that value, ...)
go
tx, _ := db.BeginTx(ctx, nil)
var no int64
err := tx.QueryRowContext(ctx,
    `UPDATE invoice_counters SET last_no = last_no + 1 WHERE series = $1 RETURNING last_no`, series).Scan(&no)
// insert the invoice with `no`, then tx.Commit(); a rollback undoes the number too
php
$no = DB::transaction(function () use ($series) {
    $row = DB::table('invoice_counters')->where('series', $series)->lockForUpdate()->first();
    DB::table('invoice_counters')->where('series', $series)->update(['last_no' => $row->last_no + 1]);
    return $row->last_no + 1;
});

Retry and failure handling ​

FailureMeaningRetry?Action
23505 on a generated IDCollision, or a replay of the same insertYes, with a new ID, up to 3 times; but if the ID is an idempotency key, do not retry: return the stored resultAlert if it happens at all
2200H / 8115 / ORA-08004Sequence exhaustedNoEmergency migration to bigint
Snowflake ErrClockMovedBackWall clock behind the last timestampYes, after a short waitAlert if skew exceeds a threshold
Hi/lo block fetch failsDatabase unreachableYes, with backoffBlock already held keeps serving
Lease lost (etcd/ZooKeeper)Another node may now own your node IDNo: stop generatingRe-acquire, then resume
Duplicate key after restore from backupSequence behind the dataAfter setvalRe-sync every sequence

Sequences after restore, failover or a logical-replication cutover. A restored dump, a logical replica or a pg_upgrade does not always bring sequence positions. After any such move, run setval(pg_get_serial_sequence(...), max(id)) for every table before accepting writes. The failure mode is a flood of 23505 on the first inserts.

Choosing a generator ​

Who creates the ID?One databaseidentity / bigserialMany app nodes, offlineUUIDv7 (uuid column)Need 64-bit + time orderSnowflake / SonyflakeExposed to users? Add a separate public IDauthorise every read; never rely on unguessable keys
WorkloadRecommendedExtra techniqueReason
Single PostgreSQL/MySQL, internal admin appbigint identityPublic ID if exposedSmallest, simplest, best locality
Public SaaS API, one databasebigint internal + random public_idRow-level authorisationCompact joins, no leak of volume
Microservices creating rows independentlyUUIDv7Unique constraint; native uuid columnNo coordination, good locality
Offline-first mobile / syncUUIDv7 or ULID from the clientServer validates and dedupesIDs exist before the server knows
Sharded MySQL/PostgreSQL, 8-byte keysSnowflake or Instagram-styleNode ID lease; clock monitoringTime order, shard in the key
Event/log table, append-only, hugeUUIDv7 or SnowflakePartition by time range on the keyRecent writes in one partition
Invoices, legal numberingCounter row with lockSeries per fiscal yearGapless
Payments, retried APIsIdempotency key (client UUID)Unique constraint + stored responseExactly-once effect
Cassandra/DynamoDBUUIDv7/ULID or timeuuid as clustering keyHash a prefix if hotSpread writes, ordered reads in a partition
Range-partitioned distributed SQL (Spanner, CockroachDB)Random or hash-prefixed UUID, or hash-sharded indexAvoid monotonic PKsAvoid a hotspot range
Security tokens, reset links128+ random bits from CSPRNGNot an ID: a secret, hashed in the DBA capability needs unguessability, not an ID

Go ​

Before ​

The store relies on a single bigserial sequence, which breaks across shards, and it writes random v4 UUIDs into a hot table whose primary key is the UUID. Both are the choices this page argues against.

go
// Package before shows the two habits this topic argues against: one database
// sequence as the only source of IDs, and random v4 UUIDs as the primary key of
// a hot, insert-heavy table.
package before

import (
	"context"
	"crypto/rand"
	"database/sql"
	"fmt"
)

type EventStore struct {
	db *sql.DB
}

func NewEventStore(db *sql.DB) *EventStore {
	return &EventStore{db: db}
}

// InsertSerial relies on the table's sequence. On a single primary that is
// correct. Run the same table on two shards and both sequences start at 1, so
// the keys collide as soon as the data is merged or read across shards.
func (s *EventStore) InsertSerial(ctx context.Context, payload string) (int64, error) {
	var id int64
	err := s.db.QueryRowContext(ctx,
		`INSERT INTO events (payload) VALUES ($1) RETURNING id`, payload,
	).Scan(&id)
	return id, err
}

// InsertRandom uses a random v4 UUID as the primary key. The values are
// uniformly distributed, so each insert lands at a random place in the
// primary-key B-tree and the write touches pages all over the index.
func (s *EventStore) InsertRandom(ctx context.Context, payload string) (string, error) {
	id, err := randomV4()
	if err != nil {
		return "", err
	}
	_, err = s.db.ExecContext(ctx,
		`INSERT INTO events_uuid (id, payload) VALUES ($1, $2)`, id, payload)
	return id, err
}

// randomV4 builds a version 4 UUID from 122 random bits (RFC 9562, section 5.4).
func randomV4() (string, error) {
	var b [16]byte
	if _, err := rand.Read(b[:]); err != nil {
		return "", err
	}
	b[6] = (b[6] & 0x0f) | 0x40 // version 4
	b[8] = (b[8] & 0x3f) | 0x80 // RFC 9562 variant
	return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:16]), nil
}

After ​

A Snowflake-style generator built only on sync and time (shown above), a UUIDv7 generator written from the RFC 9562 layout with crypto/rand (shown above), and a demo that prints both so the version nibble and the ordering can be checked by eye.

go
// Command demo prints a few IDs from each generator so their shape and order
// can be checked by eye.
package main

import (
	"fmt"
	"log"
	"time"

	"academy/id-generation/after/snowflake"
	"academy/id-generation/after/uuidv7"
)

func main() {
	gen, err := snowflake.New(7)
	if err != nil {
		log.Fatal(err)
	}
	for i := 0; i < 3; i++ {
		id, err := gen.Next()
		if err != nil {
			log.Fatal(err)
		}
		fmt.Printf("snowflake %d  time=%s\n", id, snowflake.Time(id).Format(time.RFC3339Nano))
	}

	for i := 0; i < 3; i++ {
		u, err := uuidv7.New()
		if err != nil {
			log.Fatal(err)
		}
		fmt.Println("uuidv7   ", u)
		time.Sleep(2 * time.Millisecond)
	}
}

The Go angle ​

Go's standard library has no UUID or ULID type, so most projects import github.com/google/uuid (which has NewV7) or github.com/oklog/ulid. The snippets here avoid dependencies and write the layout directly, which makes each bit visible.

database/sql exposes generated keys through Result.LastInsertId, and its documentation warns that "Not all databases support this feature, and the syntax of such statements varies." PostgreSQL has no such result, so the pattern is INSERT ... RETURNING id. crypto/rand.Read fills its slice with cryptographically secure random bytes and, in current Go, does not return an error in practice, so generators can take randomness from the OS with no state of their own.

The Snowflake generator keeps its state behind a sync.Mutex. time.Now().UnixMilli() reads the wall clock, which can step backwards under NTP, so the generator checks against its last timestamp. Go's time.Time also carries a monotonic reading; subtracting two time.Now() values uses it, which is the basis of the "monotonic offsets" strategy. Never use math/rand for IDs.

Laravel ​

Before ​

Order keeps the default auto-incrementing integer key, so every shard starts at 1. Event uses a random v4 UUID through Str::uuid(), which is documented as version 4.

php
<?php

// Before: two habits that break once data lives on more than one shard.
//
// 1. Order keeps Eloquent's default $incrementing = true. Each shard's `orders`
//    table has its own sequence starting at 1, so shard A and shard B both
//    issue id 1. Merging the shards, or reading both through one API, yields
//    duplicate primary keys.
//
// 2. Event uses a random v4 UUID as its primary key. Inserts land at random
//    positions in the primary-key B-tree, so writes are spread across the index.

namespace App\Models;

use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class Order extends Model
{
    // No override: the per-shard database sequence supplies the key.
}

class Event extends Model
{
    use HasUuids;

    public function newUniqueId(): string
    {
        return (string) Str::uuid(); // version 4, random
    }
}

After ​

Event uses HasUuids and overrides newUniqueId() to call Str::uuid7(). The same trait generates UUIDv7 by default, and the override makes the choice visible and fixed. Ticket uses HasUlids for a ULID key.

php
<?php

// After: application-generated, time-ordered keys. The value is unique across
// shards without asking a database sequence, and new rows sort after old ones.
//
// HasUuids already generates UUIDv7 by default in Laravel 13. The override
// below pins the format explicitly, so a future change to the default cannot
// silently alter the keys this table stores.

namespace App\Models;

use Illuminate\Database\Eloquent\Concerns\HasUlids;
use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class Event extends Model
{
    use HasUuids;

    public function newUniqueId(): string
    {
        return (string) Str::uuid7();
    }
}

// HasUlids is the same shape. The ULID is a 26-character string stored in the
// primary key column `id` (declared as $table->ulid('id') in the migration), and
// it sorts lexicographically by time.
class Ticket extends Model
{
    use HasUlids;
}

The migration uses the uuid column method, and primary() adds the index. The comment at the bottom shows the equivalent ulid column.

php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('events', function (Blueprint $table) {
            // uuid() creates a UUID-equivalent column. primary() adds the unique
            // B-tree index on it. UUIDv7 values increase with time, so new rows
            // append near the right edge of that index instead of splitting
            // random pages.
            $table->uuid('id')->primary();
            $table->string('payload');
            $table->timestamps();
        });

        // For ULID keys, use the ulid() column method instead:
        // $table->ulid('id')->primary();
    }

    public function down(): void
    {
        Schema::dropIfExists('events');
    }
};

The Laravel angle ​

The Eloquent documentation says: "By default, the HasUuids trait will generate UUIDv7 identifiers for your models. These UUIDs are more efficient for indexed database storage because they can be sorted lexicographically." HasUlids works the same way with ULIDs.

If the model uses a non-incrementing key, the primary key column must be a UUID or ULID equivalent. For a value outside a model, the Strings page lists Str::uuid() (version 4), Str::uuid7(time: now()) (time-ordered, with an optional timestamp) and Str::ulid(). Carbon::createFromId() decodes the creation time from a ULID. To keep an integer key and also a generated public ID, define uniqueIds() on the model to name the columns that should receive the UUID (the Eloquent docs describe this), and keep $incrementing true for the primary key.

In production systems ​

  • PostgreSQL sequences do not roll back. The docs state that nextval is never rolled back, so a failed insert leaves a gap. Any bigserial key is fine for identity but not for invoice numbers.
  • PostgreSQL has UUID generators built in. The UUID functions page lists gen_random_uuid() (version 4) and uuidv7(), which uses a Unix millisecond timestamp, a sub-millisecond timestamp and random bits, and uuid_extract_timestamp().
  • Instagram stores time, shard and sequence in one bigint. Its post describes a 41/13/10 split generated by a PL/pgSQL default, so the shard is recoverable from the key.
  • Twitter kept IDs at 64 bits deliberately. The Snowflake blog says IDs must "fit into 64 bits"; the 2010 IdWorker code uses 5 datacenter bits and 5 worker bits within its 10-bit node field.
  • MySQL documents innodb_autoinc_lock_mode=2 as the default in 8.4 and UUID() as version 1, with UUID_TO_BIN(…, 1) to reorder the time parts.
  • MongoDB's ObjectId is a 4-byte timestamp, a 5-byte per-process random value and a 3-byte counter. It is time-ordered to the second by construction.

In architecture: from a single process to a distributed system ​

Choosing an ID strategy is choosing where ordering, uniqueness and the trust boundary live.

Monolith (one process, one database) ​

One PostgreSQL, one orders table. Use bigint GENERATED ALWAYS AS IDENTITY. It is dense, small, locality-perfect, and the database guarantees uniqueness. If the ID reaches the browser, add a public_id. Monitor pg_sequences so an int4 never surprises you. A job queue that uses the table ID as the cursor for keyset pagination benefits from monotonic IDs.

Modular monolith / multiple databases ​

Modules own their tables and may use separate databases. IDs are still local, but foreign keys across modules (stored as plain columns) now travel in events and joins in the application. A module that exports an ID should export a type-prefixed one (ord_…, inv_…) so a mix-up is visible; internally the key can stay bigint. Avoid reusing the same integer space in two modules in one search index or cache namespace.

Microservices ​

Each service creates rows independently, so a central counter is a coupling and a latency tax. Use UUIDv7 generated in the service (or a Snowflake with a node lease). A multi-service flow carries the IDs end to end:

text
     client                    orders service                 payments service               broker
1    POST /orders (Idem-Key K) INSERT order id=O1 (uuidv7)
2                              outbox row: OrderPlaced{O1, K}
3                                                             <- OrderPlaced (message id M1)
4                                                             dedupe on M1 / K, charge, payment id=P1 (uuidv7)
5                                                             PaymentCaptured{P1, O1}
6                              <- PaymentCaptured             correlate by O1; order -> paid

Order across services is by causality (O1 before P1 in the flow), not by comparing their IDs. Correlation IDs, trace IDs and message IDs are all IDs: generate them once, pass them on, and never regenerate. See saga and outbox for the delivery side.

Distributed data (replicas, caches, sharded databases, multi-region) ​

  • Replicas: sequences exist only on the primary. After a failover the new primary's sequence may be behind; re-sync before accepting writes (see replication and failover).
  • Caches: a cache key order:1002 is safe only if IDs are globally unique. With per-shard IDs you must include the shard in the key.
  • Sharded databases: an ID that encodes the shard (Instagram) lets any node route a read without a lookup table; changing the shard of a row then changes its ID. Hash or consistent-hash routing on a random ID (consistent hashing) lets you reshard without changing IDs.
  • Multi-region: each region generating Snowflake or UUIDv7 IDs works with no cross-region round trip; clocks differ between regions, so cross-region order is approximate. Spanner's TrueTime and CockroachDB's HLC are the exceptions that bound it. A range-partitioned store needs the hotspot-avoiding advice from above.
  • Sequences, again: a single global sequence across regions is a consensus operation per ID. Use hi/lo blocks per region if you need integers.

Scaling path ​

ScaleDesignExample
1x: one databasebigint identityA small SaaS: orders.id identity, public_id uuid
10x: read replicas, many app nodesSame identity; hi/lo blocks if inserts are hot; UUIDv7 for new tablesA busy API adds events with UUIDv7
100x: sharded, multiple servicesUUIDv7 or Snowflake; shard in the key if you need routingInstagram-style IDs in PostgreSQL; Discord-style snowflakes across services
GlobalRegion in the node bits; hybrid clocks for orderSnowflake with datacenter bits; HLC where order matters

Lab ​

Goal: insert one million rows with a v4 and a v7 key and compare index size, leaf density and WAL volume. This needs PostgreSQL 18 (for uuidv7()). Docker was not running when this page was written, so the output below describes the expected shape, not measured numbers; record your own.

sql
-- Terminal 1 (psql)
CREATE EXTENSION IF NOT EXISTS pgstattuple;
CREATE TABLE t_v4  (id uuid PRIMARY KEY DEFAULT gen_random_uuid(), payload text DEFAULT 'x');
CREATE TABLE t_v7  (id uuid PRIMARY KEY DEFAULT uuidv7(),           payload text DEFAULT 'x');
CREATE TABLE t_big (id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, payload text DEFAULT 'x');
sql
-- Experiment 1: WAL volume for 1M inserts into each (CHECKPOINT between runs so full-page images are comparable)
CHECKPOINT;
SELECT pg_current_wal_lsn() AS lsn0 \gset
INSERT INTO t_v4 (payload) SELECT 'x' FROM generate_series(1, 1000000);
SELECT pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), :'lsn0')) AS wal_v4;
-- repeat with t_v7 and t_big
-- expected: wal_v4 clearly the largest (many full-page images); wal_v7 close to wal_big
sql
-- Experiment 2: index size and shape
SELECT 't_v4' AS t, pg_size_pretty(pg_relation_size('t_v4_pkey')) AS idx, (pgstatindex('t_v4_pkey')).*;
SELECT 't_v7' AS t, pg_size_pretty(pg_relation_size('t_v7_pkey')) AS idx, (pgstatindex('t_v7_pkey')).*;
-- expected: v4 index about 30-60% larger, avg_leaf_density near 70, leaf_fragmentation high;
--           v7 avg_leaf_density near the 90 fillfactor, leaf_fragmentation near 0
sql
-- Experiment 3: a rough split count = leaf pages beyond the ideal packing
SELECT leaf_pages,
       ceil(1000000 / ((8192 - 24) * 0.90 / 28))::int AS ideal_leaf_pages_at_fillfactor_90,
       leaf_pages - ceil(1000000 / ((8192 - 24) * 0.90 / 28))::int AS extra_pages_from_splits
FROM pgstatindex('t_v4_pkey');
-- 28 = 24-byte uuid index tuple + 4-byte line pointer (an estimate; compare v4 with v7)
sql
-- Experiment 4: cold-cache insert cost after the table is bigger than memory (optional)
-- Run EXPLAIN (ANALYZE, BUFFERS) on a batch insert and compare "shared read" between v4 and v7.
go
// Experiment 5: generate in Go instead of the database (same layout, compare)
id, _ := uuid.NewV7()
_, _ = db.ExecContext(ctx, `INSERT INTO t_v7 (id) VALUES ($1)`, id)
php
// Experiment 6: Eloquent with HasUuids (v7 by default) vs Str::uuid() (v4)
foreach (range(1, 1000000) as $i) { /* chunk with Event::insert($rows) */ }

Common misconceptions ​

BeliefReality
"A sequence gives gapless numbers."Gaps from rollbacks, crashes, CACHE and failed statements. Use a locked counter row for legally gapless numbers
"UUIDs are slow."Random v4 keys cause scattered inserts and bigger indexes; v7 keys are nearly as friendly as bigint, at twice the bytes
"UUIDv7 is strictly ordered."Millisecond order from one clock; ties within a ms and skew across nodes
"Snowflake needs ZooKeeper."Only for assigning a node ID at start-up (Twitter's choice); config or leases work too
"41 bits is 41 years."2^41 ms is about 69.7 years (Instagram's post said 41; Twitter's README says 69)
"An unguessable ID is authorisation."RFC 9562: UUIDs must not be used as capabilities; check access on every read
"Hashids/sqids encrypt IDs."They are reversible encodings; they hide nothing from someone who knows the alphabet
"MySQL UUID_TO_BIN(u, 1) fixes any UUID."It reorders v1 time parts only; it does nothing for v4 and is not needed for v7
"int is big enough."2.1 billion rows arrive faster than you think; choose bigint at the start
"Collisions are impossible with UUIDv4."Negligible with a good CSPRNG; certain with a broken one. Keep the constraint
"ID order is event order."Not across nodes; use versions or a log offset
"Sequences travel with logical replication or dumps."Not always; re-sync after failover or restore
"ULID and UUIDv7 differ in bytes."Both are 48-bit ms plus random; they differ in text encoding and the optional monotonic rule

Cheat sheet ​

TopicWhat to remember
Default single-database keybigint GENERATED ALWAYS AS IDENTITY / BIGINT AUTO_INCREMENT
Sequence gapsnextval never rolls back; CACHE adds holes and out-of-order values
int4 limit2,147,483,647; error 2200H (PostgreSQL), 1062 (MySQL), 8115 (SQL Server)
innodb_autoinc_lock_mode0 traditional, 1 consecutive, 2 interleaved (default in 8.4)
Offset/stepNode k of N: INCREMENT BY N START WITH k
Hi/loReserve a block with one UPDATE ... RETURNING; serve locally; crash = gap
UUIDv4122 random bits; no order; scattered inserts
UUIDv748-bit ms + 74 random bits; native uuidv7() in PostgreSQL 18; Str::uuid7(); uuid.NewV7()
ULID48-bit ms + 80 bits; 26 chars Crockford base32; same-ms order not guaranteed
Snowflake1 + 41 + 10 + 12; 4,096 IDs/ms/node; ~69.7 years
Clock skewRefuse, wait, or logical clock; never trust the wall clock
Storageuuid / BINARY(16), never CHAR(36)
ExposureAuthorise every read; add public_id; sqids is not security
Idempotency keyClient-made, unique constraint, stored response
Collisionsn²/2N; 1-in-a-billion at ~10^14 v4 UUIDs

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — Why can a rolled-back transaction leave a gap in a PostgreSQL sequence? Must-know ​

Answer

Answer: nextval is not transactional: once a value is handed out it is never taken back, so a rollback (or crash, or discarded cache) leaves a hole.

2 — What does CACHE 20 change for two concurrent sessions? Important ​

Answer

Answer: Each session reserves 20 values; values are distinct but can be issued out of global order, and unused cached values are lost when the session ends.

3 — Which innodb_autoinc_lock_mode keeps IDs consecutive within one bulk insert? Good to know ​

Answer

Answer: Modes 0 and 1 (table-level AUTO-INC lock for bulk inserts). Mode 2 (default in 8.4) may interleave and leave gaps under concurrency.

4 — Name the four fields of a Snowflake ID and their sizes. Good to know ​

Answer

Answer: 1 unused bit, 41 bits time, 10 bits node, 12 bits sequence.

5 — What should a Snowflake generator do when the clock moves backwards? Important ​

Answer

Answer: Refuse to issue (or wait, or use a logical clock) so it never repeats a timestamp-sequence pair.

6 — Why are UUIDv4 primary keys harder on a B-tree than UUIDv7? Must-know ​

Answer

Answer: Random keys land on random leaf pages: the whole index is the working set, pages split at about 50%, leaf density settles near 69% and WAL grows from full-page images. v7 keys append to the rightmost leaf.

7 — When does UUID_TO_BIN(u, 1) help in MySQL? Important ​

Answer

Answer: Only for version 1 UUIDs, whose time-low part varies fastest; it swaps time parts so the index sorts by time. It gives no benefit for v4 and is unnecessary for v7.

8 — Why must a public ID be authorised even if it is a random UUID? Must-know ​

Answer

Answer: UUIDs leak through logs, links and referrers; RFC 9562 says they must not act as capabilities. Ownership must be checked on every read.

9 — What is an idempotency key and who generates it? Must-know ​

Answer

Answer: A caller-generated ID for one logical operation, sent on every retry so the server dedupes using a unique constraint and returns the stored response.

10 — Why can two IDs from different nodes sort in the wrong order? Important ​

Answer

Answer: Each embeds its node's clock; clocks differ by milliseconds or more, so there is no global order without a sequencer or bounded clocks.

Glossary ​

TermMeaning
SequenceA database counter object (nextval), not rolled back
Identity columnGENERATED ... AS IDENTITY; SQL-standard auto-number with an implicit sequence
serial / bigserialLegacy PostgreSQL pseudo-types: integer column with a sequence default
CACHENumber of sequence values a session pre-allocates
GapA missing number in a sequence, normal and permanent
ExhaustionReaching the maximum of the type (int4 2,147,483,647)
AUTO_INCREMENTMySQL's per-table counter
innodb_autoinc_lock_modeInnoDB setting for how the counter lock is held (0, 1, 2)
Offset/stepGiving node k of N the numbers k, k+N, ...
Ticket serverA dedicated database that only issues IDs (Flickr)
Hi/loReserve a block ("hi"), serve the "lo" part locally
UUID128-bit identifier with version and variant bits (RFC 9562)
UUIDv1 / v4 / v6 / v7 / v8Time+MAC / random / reordered v1 / Unix-ms time-ordered / vendor-defined
ULID48-bit ms + 80 random bits, Crockford base32
KSUID4-byte seconds + 16-byte payload, base62
Snowflake64-bit time + node + sequence ID
SonyflakeSnowflake variant with 10 ms time units and 16-bit machine ID
Node ID / machine IDThe part of an ID that makes generators distinct
Clock skewDifference between two machines' clocks, or a clock stepping backwards
Leap secondAn inserted 23:59:60; Unix time repeats or smears it
k-sortedEach item is within k positions of its sorted place
HLCHybrid logical clock: physical time plus counter
Page splitA full B-tree page divided in two on insert
fillfactorTarget fill of index/table pages (90 for B-tree leaves by default)
pgstatindexpgstattuple function reporting leaf pages, density and fragmentation
Birthday boundAbout n²/2N probability of a collision among n random values
Enumeration / IDORWalking guessable IDs to read data you should not
Hashids / sqidsReversible short-string encodings of integers; obfuscation only
Public IDA separate random identifier shown to clients
Idempotency keyCaller-generated ID that makes retries safe
ObjectIdMongoDB's 12-byte ID: seconds, per-process random, counter
timeuuidCassandra's v1-style UUID type ordered by time
UUID_TO_BINMySQL function converting a UUID to BINARY(16), with optional time-swap
gen_random_uuid()PostgreSQL v4 generator
uuidv7()PostgreSQL 18 time-ordered generator

References ​

Built by Morteza Negahi