Skip to content

In development. Expect rough edges and changes. The source code is not public yet.

PgDog 5 min read Deep dive mediumAdept

Primary keys in sharded databases

PgDog generates globally unique primary keys across Postgres shards without extensions or external ID services. It reuses Postgres's hash-partition algorithm, so each shard can call satisfies_hash_partition and loop nextval until a value belongs to that shard. Setting pgdog.next_id_seq as the column DEFAULT is enough, and pgdog.next_uuid_auto does the same for UUIDs. Sequence caching (ALTER SEQUENCE ... CACHE 1000) makes the brute-force loop cheap and cuts WAL writes, at the cost of gaps after a crash but never duplicates.

Related posts

  • Choosing a Postgres Primary Key

    Supabase mediumAdept

    Postgres primary key options progress from integer and serial sequences to standards-compliant IDENTITY columns, then to random IDs and UUIDs, each fixing a weakness of the last. Sequences can leave gaps and expose guessable, enumerable IDs. Python's random module is unsafe for IDs, so the secrets module is needed. UUIDv1 and v4 are hard to guess but are twice the size of bigint, and they sort and index poorly. Newer k-sortable formats (UUIDv6/v7/v8, ULID, KSUID, Snowflake and others) fix ordering, and the uuid-ossp and Rust-based pg_idkit extensions are benchmarked on generation speed and table/index size.

  • Sequences and other volatiles in Neki

    PlanetScale hardMaster

    Neki, PlanetScale's sharded Postgres, implements Postgres sequences by classifying sequence operations like nextval() as router-only, with an authoritative shard hosting all sequences so values are never duplicated across shards. The planner relies on Postgres's immutable/stable/volatile expression classification: immutable expressions can be pushed to shards, stable ones like now() or to_char() need consistent clocks or GUCs such as lc_time, and volatile ones must run exactly once per row of the table expression. Determining that cardinality correctly under cross-shard joins, filter reordering and shard-local join pushdown is the hard part, because optimizations that deduplicate join-multiplied rows are invalid for volatile expressions.

  • You should shard your database

    PgDog mediumAdept

    Sharding Postgres early avoids the operational pain of large single instances, illustrated by an outage where stale planner statistics caused a 300 GB table to be sequentially scanned. Attempts to fix it by raising default_statistics_target added planning time (0.2ms to ~1ms per query, significant at 100k QPS), while making autovacuum analyze more often increased IOPS. Splitting the table into 12 shards cuts writes, autovacuum work and scanned rows by 12x, making migrations like ALTER COLUMN TYPE BIGINT finish in seconds and lowering the cost of mistakes.

  • One, Two, Skip a Few...

    incident.io mediumAdept

    Postgres sequences pre-log 32 values to the WAL (SEQ_LOG_VALS), so replicas see sequence state as it would be after a primary crash. When incident.io promoted a follower during a database upgrade, every per-organisation incident ID sequence jumped forward by up to 32, producing gaps like #INC-7 to #INC-39. Sequences guarantee monotonic values but not gap-free ones, and rollbacks can also skip numbers. The fix replaced them with a BEFORE INSERT trigger computing MAX(external_id)+1 per organisation, backed by an index, and the post recommends keeping external IDs separate from internal primary keys.

  • Shard design doesn't start from your tables

    PlanetScale mediumAdept

    Neki's shard groups co-locate related Postgres tables by hashing a shared shard key (e.g. customer_id via xxhash) into a 64-bit keyspace split across shards, so joins and transactions for one customer stay on a single shard with full Postgres semantics. Cross-shard transactions get no atomic commit or shared snapshot. The design toolkit includes reference tables replicated to every shard for lookup data, separate shard groups for differently keyed data like a SKU catalog, SQL expressions in shard indexes such as lower(sku), range and modulo index types for legacy schemes, and global secondary indexes that turn non-shard-key lookups into two single-shard reads. The core advice is to design shard groups from your most important queries and transactions rather than from your tables, and to change them later with the Reshard workflow as needed.

The quest for software engineering knowledge.

Look:
Layout: