System DesignVol. 12 · Part XII
0 / 0

Shelves / System Design

SD·127

Database Architecture

Structuring the data tier for scale and evolution: choosing data models, read replicas and replication lag handling, table partitioning (range, list, hash) and partition pruning, sharding architectures (application-level, proxy-based such as Vitess and Citus, distributed SQL), secondary indexes in single-node and sharded systems (local versus global), denormalisation and materialized views (database and streaming), change data capture with Debezium and logical replication, CQRS with separate read models, polyglot persistence, connection management, zero-downtime schema migrations, and backups and point-in-time recovery.

26 topics · ~21 min read · 31-question quiz
Updated Suggest a correction

Start here: one database, then copies, then pieces

The data tier usually grows in three steps. First, one database, tuned and indexed; it goes further than most people expect (chapter 122's estimate fitted five years of orders on one server). Second, read replicas: copies that serve reads, so the primary only handles writes. Third, partitioning: splitting a table into pieces, inside one database or across many (sharding). Each step solves a problem and creates a new one.

Replicas are behind, always a little

An order was written to the primary and then immediately read back from the replica, 500 times:

Text
idle primary, read replica right after write:      467 of 500 reads missed the new order
primary under heavy write load (replica 71 ms,
  ~10 MB behind):                                   298 of 300 missed
under load, wait for the replica to reach my write: 0 of 300 missed (waited p50 17 ms, max 97 ms)

Even with nothing else happening, the replica hadn't applied the write in the fraction of a millisecond before the read. A customer who places an order and is immediately shown "your orders" from a replica sees an empty list. That's a read-your-writes violation, and it's the classic replica bug. Fixes: read your own recent data from the primary; or remember the position of your write in the log (the LSN) and wait until the replica has replayed it, which cost 17 ms at the median under load here.

Partitioning a table by time

1.5 million orders, stored once as one big table and once split into 12 monthly partitions. A query for one week in March:

Text
Aggregate
  -> Bitmap Heap Scan on orders_p2          ← only March's partition is touched
       -> Bitmap Index Scan on orders_p2_created_at_idx

The planner skipped the other 11 partitions entirely (partition pruning). A full month's total:

Text
one big table:     52.8 ms
partitioned:       11.8 ms   (scans one month's partition instead of filtering the whole table)

And removing January's data:

Text
DELETE from the big table:   141.9 ms, and leaves 127,000 dead rows for VACUUM to clean up
DROP the January partition:   37.2 ms, and the space is freed at once

Partitioning by time makes recent-data queries cheaper and old-data removal almost free, which is why time-series and order tables are its most common use. Splitting across machines (sharding) uses the same idea with a key such as customer or tenant, and adds the costs of cross-shard queries and transactions.

How deep to go in database architecture

Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.

Level What you can do
L1 Explain replicas, replication lag, partitioning and sharding
L2 Add read replicas with correct routing and partition a large table by time
L3 Explain sync vs async replication, read-your-writes, pruning, shard keys and resharding
L4 Diagnose lag-related bugs, hot shards and missing pruning from measurements and plans
L5 Design a data tier's evolution: when to replicate, partition, shard, or change engine
L6 Operate fleets of databases with standards for replication, backups and migrations

Designing the data tier

The database is usually the hardest part of a system to scale and change: it holds state, and state is expensive to move, copy and keep consistent. Database architecture decisions are about:

  • Data model fit for the access patterns (relational, document, key-value, wide-column, graph, search, analytical; chapter 123).
  • Read scaling (replicas, caches, derived read models).
  • Write and size scaling (partitioning, sharding, distributed databases).
  • Query flexibility (secondary indexes, materialized views, search, analytics stores).
  • Keeping copies in sync (replication, CDC, events) with known consistency.
  • Evolution (schema migrations, backfills) and recovery (backups, PITR).

Start from access patterns: list the queries (by frequency, latency requirement, and consistency need) before choosing schemas and partition keys. "Get order by ID" (point lookup), "list a customer's orders newest first" (range on a key), "search orders by product name" (full-text), "revenue per day per region" (analytical aggregation) each favour different structures.

appcommands primary DBsource of truthpartitioned writes read replicasasync, lag reads CDCWAL / binlog event log search index cache invalidation CQRS read models warehouse / lake
A typical evolved data architecture. The primary OLTP database is the source of truth for writes; read replicas serve read-heavy queries; change data capture streams every committed change into an event log, from which consumers maintain derived stores: a search index, a cache, materialized read models for CQRS queries, and an analytics warehouse or lakehouse.

Read replicas

How they work

The primary streams its changes (PostgreSQL WAL, MySQL binlog) to replicas, which apply them and serve read-only queries. Managed services make adding replicas a click (RDS/Aurora replicas, Cloud SQL read replicas, Azure read replicas); Aurora and AlloyDB share storage between primary and replicas, reducing lag to milliseconds typically.

Use them for: read-heavy endpoints, reporting queries that would disturb OLTP workloads, regional read locality, and as failover candidates.

Replication lag and its anomalies

Asynchronous replicas are behind the primary by some lag (milliseconds normally; seconds or minutes under heavy write load, long-running queries on the replica, or network issues). Anomalies (Vol. 5 ch. 71):

Anomaly Example Mitigation
Read-your-writes violation User updates their profile, refresh shows the old one Route the user's reads to the primary for N seconds after a write; or wait until the replica has replayed past the write's LSN/GTID
Monotonic reads violation Two refreshes hit different replicas: a comment appears, then disappears Pin a session to one replica (hash user ID)
Consistent prefix violation Seeing an answer before the question Causally related writes in the same partition; causal tokens
Stale reads in business logic Checking "is username taken?" on a replica, then inserting Do uniqueness/invariant checks on the primary (or rely on constraints)
Go
// Read-your-writes with PostgreSQL LSN tokens: after a write, remember the primary's WAL position;
// on later reads, use a replica only if it has replayed past that position.
func (s *Store) AfterWrite(ctx context.Context) (lsn string, err error) {
    err = s.primary.QueryRowContext(ctx, "SELECT pg_current_wal_lsn()::text").Scan(&lsn)
    return // store in the user's session or a cookie
}

func (s *Store) readerFor(ctx context.Context, minLSN string) *sql.DB {
    if minLSN == "" { return s.replica }
    var caughtUp bool
    err := s.replica.QueryRowContext(ctx,
        "SELECT pg_last_wal_replay_lsn() >= $1::pg_lsn", minLSN).Scan(&caughtUp)
    if err == nil && caughtUp { return s.replica }
    return s.primary            // replica behind: read from primary
}

Also monitor lag (pg_stat_replication, replica_lag metrics) and take lagging replicas out of rotation automatically.

Read/write splitting

Route at the application layer (separate data sources; Spring AbstractRoutingDataSource with @Transactional(readOnly = true)), in a driver (MySQL Connector/J replication URLs, target_session_attrs in libpq), or in a proxy (ProxySQL, PgCat, pgpool, RDS Proxy reader endpoints). Keep transactions that read-then-write on the primary.

Partitioning within a database

Table partitioning splits one logical table into physical partitions inside the same database server. It helps with:

  • Data lifecycle: drop or detach old partitions instantly (DROP TABLE events_2025_09) instead of slow, bloating DELETEs; archive to cheap storage.
  • Query performance via partition pruning: queries filtering on the partition key scan only relevant partitions.
  • Maintenance: vacuum, reindex and backups per partition; smaller indexes per partition.

It doesn't add write capacity beyond one server (that's sharding).

Method Use
Range Time-series and event data by month/day; IDs by range
List By discrete values: region, tenant tier, status
Hash Even spread when no natural range (e.g. by user_id), mainly for parallelism and maintenance
Composite Range by month, sub-partitioned by hash of tenant
SQL
-- PostgreSQL declarative partitioning: clicks partitioned by month
CREATE TABLE clicks (
    link_id    bigint      NOT NULL,
    clicked_at timestamptz NOT NULL,
    country    char(2),
    user_agent text
) PARTITION BY RANGE (clicked_at);

CREATE TABLE clicks_2026_10 PARTITION OF clicks
    FOR VALUES FROM ('2026-10-01') TO ('2026-11-01');
CREATE TABLE clicks_2026_11 PARTITION OF clicks
    FOR VALUES FROM ('2026-11-01') TO ('2026-12-01');

CREATE INDEX ON clicks (link_id, clicked_at);   -- created on each partition

-- Pruning: only clicks_2026_10 is scanned
EXPLAIN SELECT count(*) FROM clicks
WHERE clicked_at >= '2026-10-01' AND clicked_at < '2026-10-08' AND link_id = 42;

-- Retention: detach and drop a whole month in milliseconds
ALTER TABLE clicks DETACH PARTITION clicks_2025_10 CONCURRENTLY;
DROP TABLE clicks_2025_10;

Automate partition creation (pg_partman, scheduled jobs) so inserts never fail for a missing future partition. Caveats: unique constraints and primary keys must include the partition key; queries without the partition key scan all partitions; too many partitions (thousands) slow planning.

Sharding architectures

When one primary can't handle the write volume or data size (even after vertical scaling), data must be split across multiple database servers (chapter 124 for strategies and keys).

Approach How Examples Trade-offs
Functional partitioning (vertical split) Different tables/domains in different databases (users DB, orders DB, catalogue DB), usually aligned with services Most microservice architectures Simple; cross-domain joins/transactions become distributed
Application-level sharding The application computes the shard from the key and connects to the right database Many large web companies historically (Instagram's Postgres sharding with logical shards) Full control; all cross-shard logic, resharding and tooling are yours
Sharding proxy / middleware A layer routes queries to shards transparently, can scatter-gather and reshard Vitess (MySQL; YouTube, Slack, GitHub-scale), Citus (PostgreSQL extension; distributed tables, reference tables, colocated joins), ProxySQL, ShardingSphere Less application work; proxy is critical infrastructure
Distributed SQL The database shards, replicates (Raft/Paxos) and rebalances automatically, with distributed transactions Spanner, CockroachDB, YugabyteDB, TiDB, Aurora DSQL Least application work; higher latency for multi-range transactions; cost; operational novelty
Natively partitioned NoSQL Partition key is part of the data model DynamoDB, Cassandra/ScyllaDB, Bigtable, MongoDB sharded clusters Massive scale; queries constrained by key design

Citus example: distribute by tenant so each tenant's rows colocate, enabling single-shard joins and transactions:

SQL
-- Citus: distributed tables colocated by tenant_id; reference tables replicated everywhere
SELECT create_distributed_table('accounts', 'tenant_id');
SELECT create_distributed_table('invoices', 'tenant_id', colocate_with => 'accounts');
SELECT create_reference_table('currencies');

-- Routed to a single shard (tenant_id filter): fast, transactional
SELECT a.name, sum(i.amount)
FROM accounts a JOIN invoices i ON i.tenant_id = a.tenant_id AND i.account_id = a.id
WHERE a.tenant_id = 42
GROUP BY a.name;

DynamoDB example of designing keys around access patterns (single-table design):

Text
PK               SK                        attributes
CUSTOMER#42      PROFILE                   name, email
CUSTOMER#42      ORDER#2026-10-24#9817     status, total        ← "list customer's orders newest first"
ORDER#9817       ITEM#1                    sku, qty, price      ← "get order with items"
GSI1PK=STATUS#PENDING  GSI1SK=2026-10-24T10:15Z#9817             ← "pending orders by time" via a GSI

Secondary indexes

Single-node indexes

Indexes make queries on non-key columns fast at the cost of write amplification and storage (Vol. 4 covers B-trees, LSM trees, index types). Design checklist:

  • Index for your query patterns: composite indexes in the order of equality columns, then range/sort columns ((customer_id, created_at DESC) for "a customer's orders, newest first").
  • Covering indexes (INCLUDE columns) enable index-only scans.
  • Partial indexes (WHERE status = 'PENDING') keep indexes small for selective queries.
  • Specialised indexes: GIN (jsonb, arrays, full-text), GiST/SP-GiST (geospatial, ranges), BRIN (huge append-only time-ordered tables), HNSW/IVFFlat (pgvector).
  • Every index slows writes and consumes memory: remove unused ones (pg_stat_user_indexes).

Indexes in partitioned and sharded systems

When data is partitioned by key A, a query by attribute B needs a secondary index, which can be organised two ways:

Local (document-partitioned) index Global (term-partitioned) index
Structure Each partition indexes only its own rows The index itself is partitioned by the indexed value
Writes Cheap: one partition updated A write may update index entries on other partitions (often asynchronously)
Reads by B Scatter-gather across all partitions Go to the one index partition for that value
Consistency Consistent with the partition's data Often eventually consistent (DynamoDB GSIs) unless the database uses distributed transactions (Spanner, CockroachDB)
Examples Cassandra/ScyllaDB secondary indexes, MongoDB per-shard indexes, Elasticsearch shards, DynamoDB LSIs DynamoDB GSIs, Spanner/CockroachDB secondary indexes, manually maintained lookup tables
local index shard 1+ idx shard 2+ idx shard 3+ idx colour=red? scatter-gather: N requests global index data 1 data 2 data 3 idx A–M idx N–Z (red) colour=red? write on data 1updates idx N–Z(cross-node, async?)
Local versus global secondary indexes on data partitioned by user ID. With local indexes, each shard indexes its own rows by colour, so a query for 'red' must ask every shard. With a global index, entries are partitioned by the indexed value, so 'red' lives on one index partition; but writing a row may need to update an index partition on another node.

Denormalisation and materialized views

Normalised schemas avoid duplication and anomalies; read-heavy systems often denormalise selectively to avoid expensive joins or scatter-gather at read time: store the author's name on each post, keep a comment_count column, precompute a customer's lifetime value. Each duplicate is a derived value that must be kept in sync (in the same transaction, by triggers, or asynchronously via events), with a plan for repair (recompute jobs).

A materialized view stores the result of a query physically:

SQL
-- PostgreSQL materialized view: daily revenue by region, refreshed periodically
CREATE MATERIALIZED VIEW daily_revenue AS
SELECT date_trunc('day', paid_at) AS day, region, sum(amount_cents) AS revenue_cents, count(*) AS orders
FROM orders
WHERE status = 'PAID'
GROUP BY 1, 2;

CREATE UNIQUE INDEX ON daily_revenue (day, region);          -- required for CONCURRENTLY
REFRESH MATERIALIZED VIEW CONCURRENTLY daily_revenue;        -- readers aren't blocked
  • PostgreSQL materialized views are refreshed fully (no built-in incremental refresh; extensions like pg_ivm add incremental maintenance); good for periodic dashboards.
  • Oracle, SQL Server (indexed views), Snowflake, BigQuery and ClickHouse (materialized views triggered on insert) maintain some views incrementally.
  • Streaming materialized views (Materialize, RisingWave, Flink SQL, ksqlDB, Kafka Streams state stores) maintain query results continuously from change streams, giving fresh aggregates with millisecond-to-second lag.
  • Application-maintained read models (CQRS projections, below) are materialized views you build yourself.

Change data capture

Change data capture (CDC) captures every committed change (insert/update/delete) from the database's transaction log and publishes it as a stream:

  • Log-based CDC reads the WAL/binlog (PostgreSQL logical decoding/replication slots, MySQL binlog, SQL Server CDC, MongoDB change streams, DynamoDB Streams): low overhead, captures all changes in commit order, including those made by scripts and other applications, without changing application code.
  • Tools: Debezium (Kafka Connect or Debezium Server/Engine), AWS DMS, Google Datastream, Fivetran/Airbyte, Estuary; native features like PostgreSQL logical replication to other Postgres instances.
  • Alternatives: triggers writing to an audit table (higher overhead), polling by updated_at (misses deletes and intermediate states; needs indexes).

Uses: keeping caches, search indexes and read models in sync; feeding data warehouses and lakes; the transactional outbox relay (chapter 131); migrating databases with minimal downtime (copy + stream changes, then switch); auditing.

JSON
// Debezium PostgreSQL connector (Kafka Connect) — captures the orders and order_items tables
{
  "name": "orders-cdc",
  "config": {
    "connector.class": "io.debezium.connector.postgresql.PostgresConnector",
    "database.hostname": "orders-db.internal",
    "database.port": "5432",
    "database.user": "debezium",
    "database.password": "${secrets:orders-db/debezium-password}",
    "database.dbname": "orders",
    "plugin.name": "pgoutput",
    "slot.name": "debezium_orders",
    "publication.name": "dbz_orders",
    "table.include.list": "public.orders,public.order_items",
    "topic.prefix": "orders",
    "snapshot.mode": "initial"
  }
}

Operational cautions: a replication slot retains WAL until consumed, so a stopped CDC consumer can fill the primary's disk (monitor slot lag; set max_slot_wal_keep_size); schema changes must be handled downstream (schema registry, compatible evolution); initial snapshots of large tables need throttling; CDC events reflect table structure, which couples consumers to your schema (publishing curated domain events via an outbox decouples them better).

CQRS

Command Query Responsibility Segregation (CQRS) separates the write model (commands that change state, enforcing invariants, usually normalised and transactional) from one or more read models (shaped for specific queries, denormalised, possibly in different stores), connected by events or CDC.

client command sideinvariants, tx write DBnormalised commands eventsoutbox/CDC projectors order summary search index dashboard doc query API read models are eventually consistent: lag of ms to seconds
CQRS. Commands go to the write model, which validates them against invariants and commits to the write database; the change (via outbox events or CDC) flows to projectors that update one or more read models optimised for specific queries, such as a denormalised order-summary table, a search index and a per-customer dashboard document. Queries read only from read models, which are eventually consistent with the write side.

When CQRS helps:

  • Read and write workloads differ greatly in shape or scale (complex validation on writes; many different, high-volume query views).
  • Queries need data from several aggregates or services (a read model can join them ahead of time).
  • You need several representations: relational for reporting, search index for text, document for the UI.
  • Combined with event sourcing (chapter 131), where the write side stores events and read models are projections.

Costs: more moving parts, eventual consistency between writes and reads (handle in the UI: show the command's result directly, or wait for the projection to catch up using a version token), projection rebuilds (replay from events/CDC) and their duration, duplicated data. For simple CRUD, CQRS is overkill; a "light" form (separate query services reading the same database through optimised SQL views) captures many benefits cheaply.

Java
// Projector: idempotent upsert of a read model from order events (Spring Kafka)
@KafkaListener(topics = "orders.events", groupId = "order-summary-projector")
public void on(OrderEvent e) {
    jdbc.update("""
        INSERT INTO order_summary (order_id, customer_id, status, total_cents, version, updated_at)
        VALUES (?, ?, ?, ?, ?, now())
        ON CONFLICT (order_id) DO UPDATE
          SET status = EXCLUDED.status, total_cents = EXCLUDED.total_cents,
              version = EXCLUDED.version, updated_at = now()
          WHERE order_summary.version < EXCLUDED.version      -- ignore duplicates and out-of-order events
        """, e.orderId(), e.customerId(), e.status(), e.totalCents(), e.version());
}

Polyglot persistence

Different data in the same system can live in different stores suited to each: orders in PostgreSQL, sessions in Redis, product search in OpenSearch, media in S3, analytics in ClickHouse/BigQuery, recommendations' embeddings in a vector index. Benefits: each workload gets an appropriate engine. Costs: more technologies to operate and secure, data synchronisation (prefer one-way flows from a single source of truth via CDC/events), consistency between stores, and more skills required. Add a store only when a requirement justifies it; PostgreSQL extensions often delay the need.

Connection management

Databases (especially PostgreSQL, with a process per connection) handle hundreds of connections well, not tens of thousands. With many service instances × pool sizes, connection counts explode.

  • Size application pools from Little's law and database capacity (often small: 10–30 per instance), not "as large as possible".
  • Use a connection pooler: PgBouncer (transaction pooling), PgCat, RDS Proxy, Cloud SQL Auth Proxy with pooling, Supavisor; MySQL ProxySQL.
  • Beware transaction-pooling limitations (session-level features like prepared statements and advisory locks need care; newer PgBouncer versions support protocol-level prepared statements).
  • Serverless functions are especially prone to connection storms; use proxies or HTTP-based data APIs.

Schema evolution without downtime

Schema changes on large, live tables must not lock them or break running application versions (Vol. 4, Vol. 6 ch. 84):

  • Expand and contract: add new columns/tables (nullable or with defaults), deploy code that writes both, backfill in batches, switch reads, stop writing the old, drop it later. Each step is backward compatible, so rollbacks are possible.
  • Use online DDL: PostgreSQL CREATE INDEX CONCURRENTLY, adding columns with constant defaults is instant (PG 11+), NOT VALID constraints validated later; MySQL online DDL, gh-ost/pt-online-schema-change; Vitess/PlanetScale-style schema change workflows.
  • Set lock_timeout to avoid queueing behind long transactions and blocking everything.
  • Migrations as code (Flyway, Liquibase, Alembic, Atlas, sqlx/diesel migrations), reviewed and tested against production-like data volumes.
SQL
-- Safe-ish PostgreSQL migration steps for adding a NOT NULL column with an index
SET lock_timeout = '2s';
ALTER TABLE orders ADD COLUMN channel text;                         -- instant
-- backfill in batches from application/job: UPDATE ... WHERE id BETWEEN ... AND channel IS NULL
ALTER TABLE orders ADD CONSTRAINT orders_channel_nn CHECK (channel IS NOT NULL) NOT VALID;
ALTER TABLE orders VALIDATE CONSTRAINT orders_channel_nn;          -- no long exclusive lock
CREATE INDEX CONCURRENTLY orders_channel_idx ON orders (channel);

Backups and point-in-time recovery

  • Physical backups (base backups + continuous WAL archiving: pgBackRest, WAL-G, Barman; managed snapshots) enable point-in-time recovery (PITR) to any moment within the retention window: the remedy for "someone ran DELETE without WHERE at 14:03".
  • Logical backups (pg_dump) are portable but slow for large databases; good for partial restores and migrations.
  • Store backups in another account/region, immutable (object lock) against ransomware and accidents.
  • Test restores regularly and measure restore time against RTO: a large database can take hours to restore, which may violate your RTO and force other strategies (delayed replicas, smaller shards).
  • Back up derived stores only if rebuilding them takes too long; otherwise document the rebuild procedure (reindex from source, replay CDC).

Lab: replicas, read-your-writes and partitioning

A fresh PostgreSQL 16 primary (port 5440) and a streaming replica created with pg_basebackup -R -X stream (port 5441), asynchronous, on the same host. A note from building this lab: the first attempt replicated the main lab database (3 GB) and ran a bulk-write load without truncating; the replica's copy and its WAL filled the lab's disk allowance within seconds and PostgreSQL stopped with DiskFull: could not extend file. Replicas double storage, and write bursts multiply WAL on both sides; a small dedicated cluster was used instead.

Experiment 1: read-your-writes on an async replica

Python
P.execute("insert into ryw values (%s, 'placed') …", (oid,))       # primary
R.execute("select 1 from ryw where id=%s", (oid,)).fetchone()      # replica, immediately
Condition Missed reads Replica lag
idle primary 467 / 500 sub-millisecond
bulk-write load (20,000-row inserts in a loop) 298 / 300 replay_lag 70.9 ms, 10,159 KiB behind
under load, wait for pg_last_wal_replay_lsn() >= my LSN 0 / 300 waited p50 17.5 ms, max 97.4 ms

pg_stat_replication on the primary reports write_lag, flush_lag and replay_lag per replica, and pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn) gives the backlog in bytes; alert on both. The LSN-wait technique is what ProxySQL's GTID tracking and some PostgreSQL proxies automate; the cheaper and more common approach is "sticky primary reads for N seconds after a user writes".

Synchronous replication (synchronous_standby_names, with synchronous_commit = remote_apply) would make every read from that replica see committed writes, at the cost of every commit waiting for the replica: one network round trip per commit, and writes stall if the replica is down (unless several are configured with ANY 1 (…)).

Experiment 2: range partitioning and pruning

SQL
create table orders_part(id bigint, kitchen int, total int, created_at timestamptz not null)
  partition by range (created_at);
-- 12 monthly partitions: orders_p0 (Jan) … orders_p11 (Dec); 1.5 M rows; index on created_at
Operation One big table Partitioned
one week in March (index scan) only orders_p2 scanned
sum of one month 52.8 ms 11.8 ms
remove January DELETE 141.9 ms + vacuum later DROP partition 37.2 ms

Pruning needs the partition key in the WHERE clause; a query by kitchen alone scans all 12 partitions (try it with EXPLAIN). Too many partitions hurt as well: planning time grows with partition count, so monthly or weekly partitions are typical, not hourly ones for years. Tools such as pg_partman create future partitions and detach old ones on a schedule.

Experiment 3: what sharding adds

Moving from partitions in one database to shards on several servers keeps the pruning idea and loses three things the single database gave for free:

Lost Example Usual answer
cross-shard joins a kitchen's orders when sharded by customer denormalise, or a second copy sharded by kitchen (fed by CDC)
cross-shard transactions moving credit between two customers design so invariants live in one shard; sagas otherwise (chapter 131)
global uniqueness and sequences order numbers UUIDv7/ULID or Snowflake-style IDs

Citus (PostgreSQL), Vitess (MySQL) and natively distributed SQL databases (CockroachDB, YugabyteDB, Spanner, TiDB) hide some of this, but the costs of cross-shard work remain; they're paid in latency instead of code.

Try it yourself

  1. Configure the replica as synchronous with remote_apply and rerun Experiment 1 idle and under load. Measure commit latency on the primary.
  2. Stop the replica while a synchronous primary is taking writes. What happens to commits?
  3. EXPLAIN a query on orders_part filtered by kitchen only, then add a created_at range. Compare plans and times.
  4. Detach a partition with ALTER TABLE … DETACH PARTITION … CONCURRENTLY and move it to a cheaper tablespace or export it before dropping.

Revision sheet: database architecture

Key ideas

  • Choose the data model first (relational, document, key-value, wide-column, graph, time-series, search) by access patterns and invariants.
  • One well-tuned database goes far; indexes, query design and connection pooling before distribution.
  • Read replicas scale reads; async lag breaks read-your-writes and monotonic reads; route accordingly or wait for LSN/GTID.
  • Synchronous replication trades commit latency and availability for zero lag on chosen replicas.
  • Partitioning (range, list, hash) inside one database: pruning, cheap archiving, smaller indexes.
  • Sharding across servers: shard key choice (high cardinality, even load, aligned with queries and invariants), resharding, cross-shard joins and transactions, global IDs.
  • Distributed SQL (Spanner, CockroachDB, YugabyteDB, TiDB) and sharding middleware (Vitess, Citus).
  • Migrations at scale: expand and contract, online schema change, backfills in batches.

Numbers to remember

  • Lab: 93% of immediate replica reads missed a just-committed write, even idle.
  • Lab: waiting for LSN replay cost p50 17.5 ms (max 97 ms) under write load.
  • Lab: monthly partitions made a month's aggregate 4.5× faster; DROP partition 37 ms vs DELETE 142 ms + vacuum.

Pitfalls

  • Reading your own writes from a replica.
  • Sharding before exhausting one database (indexes, pooling, replicas, partitions).
  • Shard keys that create hot shards or force cross-shard queries for the main use case.
  • Partitioning without the key in queries (no pruning).
  • Replicas and WAL not counted in disk capacity.
  • Long transactions and replication slots retaining WAL indefinitely.

Glossary

  • WAL / LSN: write-ahead log / position in it.
  • Replication lag: how far a replica is behind the primary.
  • Partition pruning: skipping partitions that can't match.
  • Shard key: the attribute that decides which shard holds a row.
  • Resharding: changing the shard layout while running.