Home›Design›System design, at the database
Course · ScaleLesson 14 of 330 read

System design, at the database

What does each system design idea actually mean for the database underneath?

25 concepts, one card each: what it means at the database, a step-through, and where it breaks. The engine details are one click away.

Most system design lists treat the database as one box. It is the box where most of these ideas get hard. A load balancer can spread reads, but every write still goes to one primary. An app tier scales in seconds; a replica first has to copy every byte.

Each card starts from the system design word and ends at the setting, the log or the query that decides how it behaves.

New to system design? Start with System design, from one server: what it means, the six things every design trades, one app growing step by step, and what to choose for the problem you have.

Traffic

1.Load balancing

Only reads can be balanced. Every write still goes to the one primary, so the balancer has to know which node that is right now.

Why it matters: Reads usually outnumber writes many times over, so spreading them across replicas is the cheapest capacity you can add.

Choose it when the primary is busy with reads and you have replicas to send them to.Skip it when there is one database. There is nothing to balance yet.

▶ Watch it, step by step

Where it breaks: A user saves, the next read lands on a replica that is a second behind, and the change looks lost.

Each engine, and a command to check it

PostgreSQL HAProxy or PgBouncer with a health check on pg_is_in_recovery(); Patroni exposes /primary and /replica

MySQL ProxySQL or MySQL Router, with writer and reader host groups

MongoDB the driver balances reads by readPreference

Cassandra the driver sends each request to a replica of its key (token aware)

CheckSELECT pg_is_in_recovery(); -- false on the primary

Scale

2.Auto scaling

The app tier scales in seconds. The database does not: a new replica first has to copy all the data. What does scale with the app is the number of connections.

Why it matters: Fortnite's account database went from slow to unreachable when a change in load turned slow queries into a storm of new connections. More app servers mean more connections, not more database. Fortnite, 2018 →

Choose it when traffic has spikes and the app tier holds no state.Skip it when the database is already the bottleneck. More app servers make it worse.

▶ Watch it, step by step

Where it breaks: The app scales out during a spike and the database runs out of connections at the worst moment.

Each engine, and a command to check it

Every engine each new app instance opens its own pool, so 10 to 50 instances with a pool of 20 is 200 to 1,000 connections

Managed storage auto scaling grows the disk, not CPU or memory

CheckSELECT count(*), current_setting('max_connections') FROM pg_stat_activity;

Stay up

3.High availability

A standby with its own copy of the data, and something that decides when to promote it. How fast that happens and what is lost depends on sync or async replication.

Why it matters: A dead MySQL master at GitHub used to mean someone waking up to fail over by hand. They automated it, with a target of 30 seconds or less. GitHub →

Choose it when an outage costs more than a standby server and the work of running failover.Skip it when a restore with a few minutes of downtime is acceptable, and nobody can look after a failover tool.

▶ Watch it, step by step

Where it breaks: Two primaries at once (split brain) when the old primary was only unreachable, not down.

Each engine, and a command to check it

PostgreSQL Patroni with etcd or Consul

MySQL InnoDB Cluster (Group Replication) or Orchestrator

MongoDB replica set election, built in

Redis Sentinel, or Redis Cluster

CheckSELECT client_addr, state, sync_state, replay_lag FROM pg_stat_replication;

Stay up

4.Fault tolerance

On one server, the log makes a crash survivable: COMMIT returns only after the WAL, redo log or journal is flushed. In PostgreSQL and InnoDB that is the default; in MongoDB only when the write concern asks for journaling (j: true). Across servers, a quorum of copies has to agree.

Why it matters: In our lab, a Redis failover lost 2,217 writes that clients had already been told were saved. Notebook 9 →

Choose it when losing a confirmed write is not acceptable: money, orders, anything a user was told is saved.Skip it when the data can be rebuilt, like a cache or a session store. Then speed can win.

▶ Watch it, step by step

Where it breaks: One setting changed for speed quietly trades away durability.

Each engine, and a command to check it

PostgreSQL synchronous_commit

MySQL innodb_flush_log_at_trx_commit and sync_binlog

MongoDB write concern w and j

Redis appendfsync; Notebook 9 lost 2,217 acknowledged writes on failover

Cassandra consistency level, QUORUM

CheckSHOW synchronous_commit;

Scale

5.Horizontal scaling

Reads scale out with replicas. Writes scale out only by splitting the data across servers, because every replica still replays every write.

Why it matters: Figma ran one PostgreSQL on AWS's largest physical instance, until there was no bigger machine to move to. Figma →

Choose it when the largest machine you can buy is not enough, or one machine is too much risk.Skip it when a bigger machine still fits. Scaling out adds work you pay for every day after.

▶ Watch it, step by step

Where it breaks: Adding replicas to fix a write bottleneck: each one adds read capacity and replication load, not write capacity.

Each engine, and a command to check it

Built in Cassandra, MongoDB sharded clusters, Redis Cluster

Added on Citus for PostgreSQL, Vitess for MySQL

CheckSELECT xact_commit FROM pg_stat_database WHERE datname = current_database(); -- run twice, a minute apart

Scale

6.Vertical scaling

Usually the first move for a relational database, and often the right one. More RAM means more of the working set fits in the buffer pool or cache, and reads stop going to disk.

Why it matters: It is the cheapest fix in engineering time: no code changes and no new ways to fail. Most databases should grow up before they grow out.

Choose it when the working set no longer fits in memory, or the CPU is busy with work you cannot remove.Skip it when you are at the largest size, or one bad query is the problem and a bigger machine would only hide it.

▶ Watch it, step by step

Where it breaks: A bigger machine with the old memory settings, so the new RAM sits unused.

Each engine, and a command to check it

PostgreSQL shared_buffers plus the OS page cache

MySQL innodb_buffer_pool_size

MongoDB the WiredTiger cache, 50% of (RAM minus 1 GB) by default, with a 256 MB floor

CheckSELECT blks_hit * 100 / nullif(blks_hit + blks_read, 0) AS hit_pct FROM pg_stat_database WHERE datname = current_database();

Scale

7.Caching

The database already caches pages in memory. An app cache such as Redis sits in front for results that are read far more than they change.

Why it matters: Instagram's 300 million photo-to-user mappings did not fit in Redis memory as plain keys. Stored as small hashes, 21 GB became under 5 GB. Instagram →

Choose it when the same results are read far more often than they change, and a few seconds of staleness is fine.Skip it when reads are slow because of a missing index. Fix the query first.

▶ Watch it, step by step

Where it breaks: The cache becomes the only copy of something, or a hot key expires and every request hits the database at once.

Each engine, and a command to check it

Inside shared_buffers, the InnoDB buffer pool, the WiredTiger cache

In front Redis or Memcached, filled on a miss (cache aside) and deleted on a write

CheckINFO stats -- keyspace_hits and keyspace_misses on Redis

Scale

8.CDN

A CDN keeps static files away from the app and the database. The database lesson is where files live: in object storage behind the CDN, with only the path in the table.

Why it matters: Files are usually most of the bytes an app serves. Keeping them off the app servers and out of the database keeps both small and backups fast.

Choose it when users download images, video, scripts or documents.Skip it when everything you serve is per-user data that cannot be shared or cached.

▶ Watch it, step by step

Where it breaks: Files in table rows: backups slow down and replicas fall behind on every upload.

Each engine, and a command to check it

Every engine images and documents stored as BYTEA, BLOB or GridFS make the database, its backups and its replicas grow with them

CheckSELECT pg_size_pretty(pg_total_relation_size('products'));

Traffic

9.API gateway

The gateway decides who gets in and how long a request may take. The database should give up no later than the gateway does.

Why it matters: Without one place for auth, limits and timeouts, every service invents its own, and the database feels the worst of them.

Choose it when many clients or services call your API.Skip it when one app talks to one backend. A reverse proxy is enough.

▶ Watch it, step by step

Where it breaks: The gateway times out at 30 seconds and returns an error, but the query keeps running for 10 minutes and holding locks.

Each engine, and a command to check it

PostgreSQL statement_timeout, idle_in_transaction_session_timeout

MySQL max_execution_time for SELECT

MongoDB maxTimeMS

CheckSET statement_timeout = '25s';

Traffic

10.Rate limiting

Two sides. The database can be the rate limiter (a counter per user per minute in Redis). And the pool size is a rate limit on the database itself: it caps how many queries run at once.

Why it matters: One client running a batch job can take every database connection and lock everyone else out.

Choose it when you have public APIs, batch jobs, or customers of very different sizes on one database.Skip it when a few internal callers you control are the only users. A fixed pool size may be enough.

▶ Watch it, step by step

Where it breaks: No limit in front, so one client running a batch job takes every connection.

Each engine, and a command to check it

Redis INCR plus EXPIRE per key, atomic on one thread

Relational a pool smaller than max_connections, so excess requests wait in the app, not in the database

CheckSELECT usename, count(*) FROM pg_stat_activity GROUP BY usename ORDER BY 2 DESC;

Traffic

11.Circuit breaker

When the database is slow, retries make it slower. A breaker stops calling after repeated timeouts. The database side is to fail fast: short lock and statement timeouts.

Why it matters: At Fortnite, a 200 ms client timeout abandoned slow queries and opened new connections instead. The account service was down for almost 18 hours. Fortnite, 2018 →

Choose it when a dependency can get slow and its callers retry.Skip it when nothing retries automatically. Then timeouts alone do the job.

▶ Watch it, step by step

Where it breaks: During a failover every client retries at once and the new primary is flooded before it is warm.

Each engine, and a command to check it

PostgreSQL lock_timeout, statement_timeout

MySQL innodb_lock_wait_timeout (50 s by default)

Drivers pool wait timeouts and retry with backoff

CheckSET lock_timeout = '2s';

Architecture

12.Message queues

A table can be a queue if workers take jobs with FOR UPDATE SKIP LOCKED. To publish an event reliably, write the row and the event in one transaction (an outbox), then relay it to the broker.

Why it matters: Work the user does not wait for, such as emails, thumbnails and reports, should not hold a request or a database transaction open.

Choose it when work can happen a few seconds later, or must survive a crash and be retried.Skip it when the user needs the result in the same response.

▶ Watch it, step by step

Where it breaks: Workers polling a table without SKIP LOCKED all wait on the same row.

Each engine, and a command to check it

PostgreSQL and MySQL 8 SELECT ... FOR UPDATE SKIP LOCKED

Redis Streams with consumer groups

Elsewhere Kafka or SQS, fed from the outbox

CheckSELECT id FROM jobs WHERE state = 'ready' ORDER BY id LIMIT 10 FOR UPDATE SKIP LOCKED;

Architecture

13.Event-driven architecture

The database's own log is already an event stream. Change data capture reads it and publishes every change, in commit order.

Why it matters: Notion had to move every change out of its sharded PostgreSQL into the warehouse. Before their new pipeline, a full resync took a week. After it, 2 hours. Notion →

Choose it when other systems need every change: search, analytics, caches, other services.Skip it when one service owns the data and nobody else needs it.

▶ Watch it, step by step

Where it breaks: A replication slot nobody reads keeps WAL forever, and the disk fills.

Each engine, and a command to check it

PostgreSQL logical decoding from the WAL, through a replication slot

MySQL row-based binlog, read by Debezium

MongoDB change streams on the oplog

CheckSELECT slot_name, active, pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) FROM pg_replication_slots;

Spread the data

14.DB replication

Every engine copies its log to other servers. Async: the commit returns first, so replicas lag and a failover can lose writes. Sync: the commit waits for a replica.

Why it matters: At Uber, one logical UPDATE became four physical writes, and all of it had to cross an ocean to the replicas. Uber →

Choose it when you need read capacity, a standby for failover, or a copy in another region.Skip it when you want a backup. A replica copies a DROP TABLE too.

▶ Watch it, step by step

Where it breaks: Reading from a replica as if it were the primary.

Each engine, and a command to check it

PostgreSQL WAL streaming, or logical publications

MySQL the binlog

MongoDB the oplog

Redis the command stream

Cassandra each write goes to its replicas directly

CheckSHOW REPLICA STATUS\G -- Seconds_Behind_Source on MySQL

Spread the data

15.DB sharding

Rows are split across servers by a key, and each shard is a full database. The key decides everything: which queries stay on one shard, and which have to ask all of them.

Why it matters: Slack sharded by workspace, and its biggest customers turned their shards into hot spots while the rest sat idle. They resharded by channel ID. Slack →

Choose it when writes or data size have outgrown the largest single machine.Skip it when reads are the problem, or partitioning and a bigger machine still work.

▶ Watch it, step by step

Where it breaks: A key that sends most writes to one shard, or a query that must visit every shard.

Each engine, and a command to check it

MongoDB a shard key, mongos routes

Cassandra the partition key, hashed to a token

Redis Cluster 16,384 hash slots

PostgreSQL and MySQL Citus, Vitess, or sharding in the app

Checksh.status() -- MongoDB: chunks per shard

Spread the data

16.Data partitioning

Inside one server, a big table is split into partitions by range, list or hash. Queries that filter on the key skip the rest, and old data goes with DROP PARTITION instead of a huge DELETE.

Why it matters: At Adyen one partition grew past 30 TB, and rebuilding an index on it took days. Partitions need a size plan too. Adyen →

Choose it when a table has hundreds of millions of rows and queries filter on time or tenant.Skip it when most queries do not filter on the partition key.

▶ Watch it, step by step

Where it breaks: Queries without the partition key read every partition.

Each engine, and a command to check it

PostgreSQL declarative partitioning

MySQL PARTITION BY RANGE, LIST, HASH

MongoDB no table partitioning; TTL indexes or time series collections instead

CheckEXPLAIN SELECT * FROM events WHERE created_at >= now() - interval '1 day'; -- look for pruned partitions

Architecture

17.Microservices

One database per service, and no other service reads its tables. The cost is that joins and transactions across services are gone, so you use events, sagas and the outbox.

Why it matters: Instacart split its database by domain, customers and fulfillment, and found only a few dozen of its hundreds of tables were needed by both. Instacart →

Choose it when teams are blocked on each other's schema changes and deploys.Skip it when one team owns the product. A well-organized app on one database is simpler.

▶ Watch it, step by step

Where it breaks: Services sharing tables "for now", which couples their deploys and schema changes forever.

Each engine, and a command to check it

Every engine each service brings its own pool, so ten services on one server multiply connections

CheckSELECT application_name, count(*) FROM pg_stat_activity GROUP BY 1;

Architecture

18.Service discovery

After a failover, the app has to find the new primary. That is service discovery for databases.

Why it matters: A 30 second failover only helps if every app finds the new primary just as fast. GitHub →

Choose it when the primary can move: failover, upgrades, maintenance.Skip it when there is one server and a fixed address. Add it with the first standby.

▶ Watch it, step by step

Where it breaks: An app that cached the old primary address keeps writing to a server that is now a replica, or gone.

Each engine, and a command to check it

PostgreSQL Patroni writes the leader to etcd or Consul; HAProxy follows it

MySQL MySQL Router or ProxySQL

MongoDB the driver discovers the replica set

Redis clients ask Sentinel for the master

CheckSENTINEL get-master-addr-by-name mymaster

Traffic

19.Reverse proxy

Database proxies pool connections, split reads from writes and hide a failover from the app.

Why it matters: Each PostgreSQL connection is a process with its own memory, so thousands of app connections need a pooler between them and the database. Connection pooling →

Choose it when many app processes connect, or you want failovers hidden from the app.Skip it when one app holds a few long-lived connections.

▶ Watch it, step by step

Where it breaks: Transaction pooling breaks session state: SET, advisory locks and, in older PgBouncer, prepared statements.

Each engine, and a command to check it

PostgreSQL PgBouncer, RDS Proxy

MySQL ProxySQL, MySQL Router

MongoDB mongos in a sharded cluster

CheckSHOW POOLS; -- in the PgBouncer admin console

Traffic

20.DNS management

Managed databases fail over by moving a DNS name to the new primary. It only works if clients look the name up again.

Why it matters: During a failover, every minute an app keeps the old address cached is a minute of failed writes.

Choose it when a managed database or a failover tool moves a name to the new primary.Skip it when a proxy or service discovery already routes to the primary.

▶ Watch it, step by step

Where it breaks: The DNS record moved in seconds, but the app kept the old address for minutes.

Each engine, and a command to check it

RDS and Aurora the cluster endpoint moves on failover

Clients the JVM and some drivers cache DNS longer than the record TTL

Checkdig +short mydb.cluster-xxxx.us-west-2.rds.amazonaws.com

Stay up

21.Disaster recovery

A full backup plus the archived log lets you restore to any second (point-in-time recovery). Decide how much data you can lose (RPO) and how long a restore may take (RTO), then test it.

Why it matters: GitLab had five backup methods in 2017. When 300 GB was deleted, none of them worked, and 6 hours of writes were lost for good. GitLab, 2017 →

Choose it when always. The only choice is how much data you can lose and how long a restore may take.Skip it when never. Skip the parts nobody tests instead, because those are the parts that will fail.

▶ Watch it, step by step

Where it breaks: Treating a replica as a backup: a DROP TABLE replicates in milliseconds.

Each engine, and a command to check it

PostgreSQL pgBackRest or WAL-G, base backup plus WAL archive

MySQL XtraBackup plus binlogs

MongoDB snapshots plus the oplog

CheckSELECT last_archived_wal, last_failed_wal FROM pg_stat_archiver;

Architecture

22.Zero-downtime deploys

The code deploy is easy. The schema change is the hard part: expand first, move the code, then contract. Some DDL is instant, some rewrites the table.

Why it matters: GitHub upgraded 1,200 MySQL hosts from 5.7 to 8.0 without dropping a query. It took over a year of planning and testing. GitHub →

Choose it when users are online at every hour, so there is no maintenance window.Skip it when a short planned window is acceptable. It is much simpler.

▶ Watch it, step by step

Where it breaks: An ALTER waits for a lock behind one long transaction, and every query queues behind the ALTER.

Each engine, and a command to check it

PostgreSQL ADD COLUMN with a constant default is instant from 11; a volatile default (for example gen_random_uuid()) still rewrites the table; CREATE INDEX CONCURRENTLY

MySQL ALGORITHM=INSTANT in 8.0; gh-ost or pt-online-schema-change

Upgrades logical replication or blue/green for major versions

CheckSET lock_timeout = '3s'; ALTER TABLE orders ADD COLUMN note text;

Architecture

23.Distributed tracing

Tracing shows the slow span is a query. To get from there to the plan, the query has to carry the trace: a comment with the trace ID, or the service name.

Why it matters: Without it, a slow request is a guess between the app, the network and the database.

Choose it when one request touches several services or databases.Skip it when one app and one database. pg_stat_statements and the slow query log go a long way.

▶ Watch it, step by step

Where it breaks: A slow span in the trace and no way to find which plan it was.

Each engine, and a command to check it

PostgreSQL application_name, pg_stat_statements, auto_explain

MySQL performance_schema, the slow query log

All sqlcommenter adds the trace ID as a SQL comment

CheckSELECT query, calls, mean_exec_time FROM pg_stat_statements ORDER BY total_exec_time DESC LIMIT 5;

Architecture

24.Network segmentation

The database lives in a private subnet with no public address. Only the app tier may reach its port, and the connection uses TLS.

Why it matters: A database reachable from the internet will be found by automated scanners. Only the app tier should ever see its port.

Choose it when always, for any database with real data in it.Skip it when never in production. A database on your laptop is the only exception.

▶ Watch it, step by step

Where it breaks: A database port open to 0.0.0.0/0 "for a quick test".

Each engine, and a command to check it

Ports 5432 PostgreSQL, 3306 MySQL, 27017 MongoDB, 6379 Redis, 9042 Cassandra

Most exposed Redis and MongoDB left open to the internet without auth

CheckSELECT name, setting FROM pg_settings WHERE name IN ('listen_addresses', 'ssl');

Stay up

25.Multi-region setup

Distance adds a round trip of tens of milliseconds between regions. Wait for the far region on every commit, or accept that a regional failover loses whatever had not arrived yet.

Why it matters: With asynchronous replication between regions, a regional failover loses whatever was still on its way.

Choose it when users on several continents need fast reads, or the business must survive losing a whole region.Skip it when most users are in one region. A standby in a second region is enough.

▶ Watch it, step by step

Where it breaks: Writing in two regions at once without a plan for conflicts.

Each engine, and a command to check it

Relational one primary region, async replicas elsewhere: reads stay local, writes travel

Aurora Global Database, a secondary region promoted on failover

Cassandra one data center per region, LOCAL_QUORUM

MongoDB replica set members spread across regions

CheckSELECT now() - pg_last_xact_replay_timestamp() AS lag; -- on the far replica

Connected

Where this shows up

The same mechanism, sharding and partitioning, replication and failover, caches and memory, elsewhere on the site: in real incidents, in measurements, and in designs.

Part 3 of 4 · Design · 24 pagesAll pages

Which database does my application need? What kind of application data goes in which database, and why, as design docs, plus the anti-patterns and the decisions behind them.