Skip to content
Tech Interview Prep
Technical interview guide

Database Scaling (Sharding & Replication)

Splitting data across machines (sharding) and copying it across machines (replication): solving two different scaling problems.

Minutes to read
4
Practice MCQs
25
Interview Q&A
25
Edition
v4
Editorial status
Reviewed

Scope: Vendor-neutral distributed-systems principles; current AWS architecture guidance.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-2

Explain read replicas: what they solve and what they break.

Answer

Core (first 90 seconds). A read replica is a second copy of the database that continuously applies the primary's write log and serves read-only queries. It solves read scale and workload isolation: N replicas give roughly N× read capacity, and moving reporting off the primary removes CPU contention and buffer-pool eviction. An analytical scan over a large table can push the hot pages the OLTP workload depends on out of cache. It does not solve write throughput: every write still goes to the primary and is shipped to every replica, so each replica adds log-shipping work and, under synchronous replication, commit latency. What replicas break is consistency. Reads can be stale, and the failures are user-visible correctness bugs, not slow queries.

Mechanism. The primary writes a log (PostgreSQL WAL, MySQL binlog) and ships it. Asynchronous replication returns the commit to the client before any replica has applied it, so lag is unbounded in principle. Synchronous replication bounds it: PostgreSQL synchronous_commit = on (the default) only flushes local WAL; remote_write waits for the standby to write, and remote_apply waits until it has replayed. That is what makes a read on that standby see the write. synchronous_standby_names = 'ANY 1 (a, b)' gives quorum. MySQL semi-sync waits for one replica's ACK, but rpl_semi_sync_source_timeout defaults to 10000 ms; after that the source silently reverts to async, so the durability guarantee disappears exactly when a replica is in trouble.

Measuring lag. On the primary:

SQL
SELECT application_name, state, sent_lsn, replay_lsn, replay_lag
FROM pg_stat_replication;
-- replica-1 | streaming | 0/1A2B3C40 | 0/1A2B3B00 | 00:00:00.041

replay_lag (PostgreSQL 10+) is the time between the primary flushing WAL and the standby reporting it replayed; 41 ms here is a typical same-region cross-AZ figure, not a guarantee. On the standby, pg_last_wal_replay_lsn() and pg_last_xact_replay_timestamp() give the same picture, and pg_wal_lsn_diff('0/1A2B3C40','0/1A2B3B00') returns 320: the byte gap, meaningful only alongside a write rate. MySQL's Seconds_Behind_Source (in SHOW REPLICA STATUS, 8.0.22+) is a trap: it is NULL when the replica SQL thread is idle and is derived from event timestamps, so it can read 0 while a long transaction is still applying.

What breaks, and the fix.

AnomalySymptomFix
Read-your-writesUser saves, next read hits a lagging replica, sees the old value, saves againsynchronous_commit = remote_apply; MySQL WAIT_FOR_EXECUTED_GTID_SET(); pin that session to the primary for a window; or return the written value from the write response
Monotonic readsTwo requests hit replicas at different positions; data appears to go backwardsSticky routing per session, or track a per-session LSN/GTID and read only replicas that have reached it
Decision-informing readBalance checked before a withdrawal, uniqueness checked before an insertMust go to the primary; a stale read there is a correctness bug, not a display glitch
FailoverAn async replica promoted is behind; the last commits are goneAccept RPO > 0, or run synchronous replication with quorum

The failure mode people miss. A long query on a standby conflicts with WAL replay. PostgreSQL cancels it after max_standby_streaming_delay (default 30s) with ERROR: canceling statement due to conflict with recovery; setting hot_standby_feedback = on avoids the cancellation but makes the primary retain dead rows, causing bloat and delayed vacuum. So a heavy report routed to a replica either fails or drives lag up. Alert on replay_lag, or ReplicaLag (seconds) in CloudWatch for RDS, AuroraReplicaLag (milliseconds) for Aurora. A replica silently minutes behind turns a correct routing decision into a wrong one with no code change.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-9

Explain the trade-offs between synchronous and asynchronous replication.

Answer

The 60-second answer. Replication mode is decided by one question: does the commit return to the client before or after a standby has acknowledged the write? Asynchronous returns first, synchronous returns after. Latency, data-loss window and availability all follow from that ordering. Async gives you RPO > 0 and no added write latency. Sync gives you RPO 0 for acknowledged commits, at the cost of a network round trip per commit and a system whose availability now depends on two nodes instead of one.

Asynchronous. The primary flushes WAL locally and returns; standbys stream in the background. Write latency is the local flush alone, and a stalled standby has no effect on the primary. The loss window equals replication lag, and lag is measurable rather than assumed: pg_stat_replication exposes write_lag, flush_lag and replay_lag (PostgreSQL 10+), MySQL exposes Seconds_Behind_Source in SHOW REPLICA STATUS. The trap is treating lag as a bound. A standby that stalls for 30 s means 30 s of committed writes are gone if the primary dies in that window.

Synchronous. The commit waits. In PostgreSQL, synchronous_commit = on waits for the standby to flush WAL to disk; remote_apply waits until the standby has applied it and the rows are visible to reads there. synchronous_standby_names = 'ANY 1 (sb1, sb2, sb3)' requires one acknowledgement from any of three standbys (quorum commit, PostgreSQL 10+). MySQL uses rpl_semi_sync_source_enabled = ON (renamed in 8.0.26 from rpl_semi_sync_master_enabled) with rpl_semi_sync_source_timeout, default 10000 ms.

AsyncSync (on)Sync (remote_apply)
Commit returns afterlocal WAL flushstandby flushed WALstandby applied
RPO> 0, equal to lag0 for acked commits0
Added write latencynone+ 1 RTT+ 1 RTT + apply
Standby unreachableno effectcommits blockcommits block

The availability inversion is the part that surprises people. With synchronous_standby_names set and no listed standby reachable, the primary does not fail writes: it blocks commits indefinitely. Recovery is ALTER SYSTEM SET synchronous_standby_names = '' followed by SELECT pg_reload_conf(), which drops you to async. MySQL's semi-sync does this for you: after the 10 s timeout it reverts to async and logs a warning, so the durability guarantee silently disappears rather than erroring.

Latency arithmetic. A local commit is roughly 1–2 ms. A same-AZ standby adds about 0.2–0.5 ms RTT; cross-AZ within a region about 1 ms. Cross-region on AWS's backbone (approximate, path-dependent): us-east-1 to us-west-2 is ~65 ms, us-east-1 to eu-west-1 ~75 ms, us-east-1 to ap-southeast-1 ~220 ms. So a 2 ms commit becomes ~77 ms to Ireland, a 38x increase. If commits are serialized on one connection, throughput caps at 1/RTT: 13 commits/s at 75 ms. Group commit amortizes the wait across concurrent transactions, which is the only reason sync replication is usable at all; a single-threaded writer still gets 13/s.

Quorum instead of all. ANY 1 (sb1, sb2, sb3) tolerates one slow or dead standby while keeping durability. Kafka does the same shape with acks=all plus min.insync.replicas=2 on a replication.factor=3 topic: one broker down is fine, two down and the produce is rejected with NotEnoughReplicasException. Fail fast, unlike PostgreSQL's hang.

How I decide. What does losing N seconds of committed writes cost? For a ledger or payments path, sync with remote_apply and quorum. For clickstream or activity logs, async. You do not have to choose per cluster: synchronous_commit is a user-settable GUC, so SET LOCAL synchronous_commit = remote_apply inside the critical transaction gives that write the stronger guarantee while the rest of the session stays async. And note what sync does not buy: it does not protect against a replicated DROP TABLE or standby corruption. RPO 0 is not a backup.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

How do you detect, mitigate, and architect around replication lag in read-heavy database clusters?

Answer

Replication lag occurs because asynchronous replicas process write operations serially through log replay or secondary execution after the primary commits. When read clusters scale out, queries observe stale snapshots unless the system actively measures and routes around that skew.

1. Detection: Distance Over Clock Delta

Wall-clock lag metrics (such as PostgreSQL's pg_last_xact_replay_timestamp() or MySQL's Seconds_Behind_Source) hide write-idle lag: if no writes occur for an hour, wall-clock staleness reads as 3,600 seconds, while during massive bursts it can falsely report near-zero if the last applied transaction was recent.

Reliable detection relies on byte offset distance:

SQL
-- PostgreSQL primary WAL write vs replica replay distance
SELECT
  client_addr,
  application_name,
  pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn) AS lag_bytes
FROM pg_stat_replication;

In managed environments (like AWS RDS), monitor both the byte delta and synthetic heartbeat writes (a continuous table updating once per second to track real replication delay).

2. Mitigation: Addressing the Root Causes

Lag spikes stem from three concrete bottlenecks:

  • Replay Serialization: Primary transactions commit concurrently across many worker threads, but replay on the replica is often constrained to fewer threads or serialized by table locks.
  • Replica Query Conflicts: Long analytical reads on a replica hold locks or buffer snapshots. In PostgreSQL, when replaying incoming WAL records requires dropping a page still needed by an open replica query, the engine blocks WAL replay until max_standby_streaming_delay (default 30s) expires, causing lag to spike by that exact duration before cancelling the query.
  • I/O and Network Saturation: High write-throughput (such as bulk imports or schema updates) generates Write-Ahead Logs faster than the replica's disk can fsync or the network can transmit.

Remediation tactics:

BottleneckDirect Mitigation
Replay Lock ContentionIncrease replica compute; tune max_standby_streaming_delay; offload analytics to warehouse
Write Volume SpikesChunk bulk writes into small batches (e.g., 1,000 rows); throttle background migrations
Network/Disk StarvationProvision higher IOPS on replicas; enable log compression across replication streams

3. Architecture: Read-Your-Own-Writes

No database-level tuning prevents lag completely during write bursts. The application layer must isolate stale reads from operations that require freshness.

Pattern A: Session-Aware Routing (Read-After-Write Window) When a mutation executes, record a timestamp or Log Sequence Number (LSN) in the user's session token or local cache (Redis). Route all read traffic for that specific user to the primary for an empirically determined window (e.g., 5 seconds) or until the read replica catches up to that specific LSN.

Pattern B: Monotonic Read Consistency via Replica Version Tracking

Write Request: Client -> Primary -> Returns Write LSN: 0/3000F80
Read Request:  Client passes Header: X-Minimum-LSN: 0/3000F80
Routing Layer: Evaluates replica pool:
               Replica A (LSN: 0/2F00000) -> SKIP (Stale)
               Replica B (LSN: 0/3001050) -> EXECUTE READ

If no replica is caught up, either route to the primary or block for up to a bounded timeout (e.g., 150ms) before degrading gracefully.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Walk me through what happens when the primary in a replicated database fails: how the failure is detected, how a replica gets promoted, and what that does to in-flight writes.

Answer

Start with the thing that surprises people: Postgres has no built-in failover. The primary does not know it is dead, and no replica promotes itself. You get failover from a coordinator (Patroni, repmgr, pg_auto_failover) or from a managed service that runs one for you. So the question is really about the coordinator, not the database.

Detection. The coordinator holds a lease in a consensus store (etcd, Consul, ZooKeeper) and renews it on a heartbeat. Patroni's defaults are loop_wait: 10, retry_timeout: 10, ttl: 30: a leader that fails to renew for 30 s is declared dead. That number is a tunable with a real trade: shorter detects faster and fires on a 40 s stop-the-world GC pause or a congested link.

Promotion. The coordinator picks the replica with the most advanced WAL position, fences the old primary, and promotes. Promotion increments the timeline ID: the new primary writes on timeline 2. That is the mechanism that makes divergence detectable rather than silent: timeline 1 WAL from the old primary cannot be merged back, and rejoining requires pg_rewind or a full rebuild.

In-flight writes. This is where sync versus async decides everything.

Sync (synchronous_standby_names='1 (s1,s2)')Async
Commit returns afterstandby flushes WALlocal flush only
Data-loss windowzero for acknowledged commitseverything not shipped and not replayed
Availability costcommits block if the standby is unreachablenone in steady state

With async and 200 ms of lag at 5k writes/s, a failover loses roughly 1,000 transactions. Quorum commit, ANY 1 (s1,s2,s3), removes the sync availability trap: one of three standbys must ack, so you survive a single standby loss without stalling writes.

Separately, the client mid-transaction on the old primary gets a connection reset. That transaction is gone and must be retried, which is how you get double charges unless retries carry idempotency keys.

Split-brain. Two nodes accepting writes on different timelines. Postgres does not prevent this; the lease does. Only the leaseholder may be primary, and the old primary must be fenced (STONITH, a watchdog device, or the managed service's fencing) before promotion. The dangerous case is a node that has lost the DCS but can still reach clients: it must self-demote, and a watchdog is what guarantees it.

How clients find the new primary. Three options. A failover-aware connection string: libpq's host=a,b,c target_session_attrs=read-write tries each host and picks one that accepts writes. Simple, but every client pays the retry and it breaks with server-side pooling. A proxy (HAProxy, PgBouncer, ProxySQL, RDS Proxy) that health-checks for read-write rather than TCP. Or a discovery layer: Consul DNS, a service registry, or the managed endpoint flipping a CNAME, where the DNS TTL (set it to 5 s) is the real failover time.

Monitoring after failover. "Up" is not healthy. Watch replication lag on the new replicas, which are now streaming a new timeline; whether the old primary rejoined or is sitting fenced; replication slots, which are per-node and do not follow the promotion, so a logical subscriber can lose its slot; max_connections and config drift on the new primary; write latency and WAL generation rate; and the promotion count itself: one promotion is a failover, three in an hour is a flapping cluster.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Compare partitioning within one database against sharding across several.

Answer

The first 90 seconds

Partitioning is a physical layout change inside one database: one server, one connection pool, one backup, and a planner that skips partitions your WHERE clause excludes. Sharding is a topology change: N independent databases, each with its own schema, backup, and failure domain. Partition when one machine still fits the data and you want pruning or cheap retention. Shard when a single machine's write throughput or storage is the binding constraint, and accept that cross-shard joins, cross-shard transactions, and global unique constraints are gone.

What partitioning buys

Pruning. With events range-partitioned by month, EXPLAIN on a query filtered to one month shows an Append over one child, not 24. PostgreSQL prunes at plan time for constants and at execution time for parameters (runtime pruning, PG 11+).

Retention, which is the bigger win. Worked example, figures assumed:

  • events: 400M rows/month at ~250 B/row → ~100 GB/month of heap.
  • 12-month retention → ~1.2 TB to remove each month.
  • DELETE FROM events WHERE created_at < ... writes WAL for every tuple and index entry, leaves ~1.2 TB of dead tuples for autovacuum, and has to be batched to avoid one enormous transaction.
  • ALTER TABLE events DETACH PARTITION events_2024_02; then DROP TABLE events_2024_02; is a catalog update plus file unlinks: seconds, no row WAL, no vacuum. PG 14+ adds DETACH PARTITION CONCURRENTLY, which avoids the ACCESS EXCLUSIVE lock on the parent.
SQL
CREATE TABLE events (id bigint, created_at timestamptz NOT NULL, payload jsonb)
  PARTITION BY RANGE (created_at);
CREATE TABLE events_2024_03 PARTITION OF events
  FOR VALUES FROM ('2024-03-01') TO ('2024-04-01');

What partitioning costs

  • Unique constraints must include the partition key. UNIQUE (id) on a table partitioned by created_at is rejected outright: "unique constraint on partitioned table must include all partitioning columns". MySQL has the same shape: every unique key must contain the partitioning columns.
  • Unfiltered queries touch every partition.
  • A partition must exist for every incoming key or the insert fails, so you need a default partition or a job that creates the next one ahead of the boundary.
  • MySQL: partitioned InnoDB tables cannot have foreign keys.

What sharding costs

  • Cross-shard joins and transactions move into application code or a coordinator (Citus's coordinator node, Vitess's 2PC support).
  • Every migration, backup, upgrade and investigation runs N times.
  • Rebalancing is a project, not a setting: MongoDB moves 128 MB chunks by default; Citus defaults citus.shard_count to 32 and moves shards between workers with rebalance_table_shards().

Composition and the rule

They compose: shard first, then partition inside each shard, which is common for time-series. The decision rule: if one machine can hold and serve the data, partition; if it cannot, shard. And don't partition a table that is merely large: check for a missing index first. Partitioning earns its constraints when there is a natural key that queries filter on and a retention requirement; with only the first, an index usually suffices.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-3

When would you shard, and how would you choose the shard key?

Answer

Short answer (first 90 seconds). Shard when one primary's write path is the measured bottleneck, not when the data is merely large: a 2 TB table with the right indexes on one node is fine. I'd want production numbers first: writes/s at p99, replication lag, connection count, and which resource is actually saturated (CPU, fsync/IO, memory, connections). Then the shard key: present in nearly every query, evenly distributed, immutable.

Sizing. Run shards at ~60% of the measured per-node ceiling so a failover or a burst doesn't tip one over:

Python
# Python 3.12
peak_writes = 40_000        # measured writes/s at p99
per_shard   = 12_000        # one primary's measured ceiling at p99 < 10 ms
headroom    = 0.6
shards = -(-peak_writes // int(per_shard * headroom))   # ceil
print(shards)

Trace: 12_000 * 0.6 = 7200; 40_000 // 7200 = 5 (5 × 7200 = 36 000); -(-40_000 // 7200) = -(-6) = 6. Prints 6. Six shards, not four: the headroom term is the whole point.

Worked skew example (hypothetical figures). 8 shards, 100 tenants, 40 000 writes/s total; one tenant, acme, is 12 000 writes/s (30%). Sharding by tenant_id puts all of acme on one shard: that shard carries 12 000 + (28 000 / 8) = 15 500 writes/s while the others carry 3 500. Max/mean = 3.1×, and the hot shard is already past a 12 000 writes/s ceiling even though aggregate capacity is 96 000. Fix: split acme by hash(user_id) % 4 into four sub-shards → 3 000 each, at the cost of acme-wide queries fanning out to four shards.

Choosing the key.

keydistributionquery localityrebalance cost
tenant_idskewed by tenant sizegood if every query carries tenantmove one tenant
user_idusually evenbreaks tenant-wide queriesmove one user
created_atworst: all writes hit the newest shardgood for range scansappend-only, but write capacity = 1 node
hash(user_id)evenkills range scanseven movement
tenant_id + bucketeven, tunabletenant queries fan out to B shardsmove one bucket

Failure modes, with detection. Hot shard: DynamoDB throttles with ProvisionedThroughputExceededException; on Postgres/Citus watch per-shard p99 write latency diverge from the mean. Scatter-gather: a query without the shard key fans out to all N shards; serialized, p99 ≈ N × per-shard p99 (8 × 8 ms = 64 ms), parallel it's ≈ max + coordinator (~9 ms). Measure fan-out count per query. Cross-shard writes lose atomicity and unique constraints (Vitess solves the latter with a lookup vindex; otherwise you maintain a separate uniqueness table). Rebalancing: modulo hashing moves ~(N−1)/N of keys going N→N+1; consistent hashing or a lookup table moves ~1/(N+1). MongoDB's balancer moves 128 MB chunks by default (64 MB before 4.0); Citus defaults to 32 shards.

Sequence. Measure the saturated resource → exhaust replicas, pooling, functional partitioning → size shards with headroom → pick the key against the three requirements → plan the outlier tenant explicitly.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

What are the trade-offs between directory-based routing and algorithmic hash or range routing when you have to dynamically reshard a database?

Answer

Shard routing falls into two structural models: algorithmic routing (where the partition key deterministically maps to a shard via hashing or range boundaries calculated locally) and directory-based routing (where an external lookup service or catalog maps individual keys or key ranges to physical nodes).

The difference becomes acute during dynamic resharding: moving data while maintaining uninterrupted read/write traffic.

1. Algorithmic Routing (Hash / Range)

  • Mechanism: The client or routing proxy computes shard_id = hash(key) % N (or walks a consistent hashing ring / sorted range boundary table) in-process without network I/O.
  • Resharding Trade-off: Changing shard topology requires moving data and atomically flipping routing rules across clients. Simple modulo (hash(k) % N) forces a complete reshuffle of roughly $(N-1)/N$ of all data when $N$ changes. Consistent hashing (e.g., using virtual nodes on a ring) limits data movement to $K/N$ keys, but during the transition, the router must handle dual-states.
  • Migration Execution:
    1. Backfill historical data from source shard to target shard.
    2. Stream replication via change data capture (CDC) or double-writes.
    3. Flip router boundaries. Any client with stale cache or un-updated ring topology routes writes to the old shard, causing split-brain unless the old shard actively rejects writes or forward-proxies.

2. Directory-Based Routing (Lookup Service)

  • Mechanism: A centralized metadata store (e.g., etcd, ZooKeeper, or a dedicated relational catalog) maintains explicit key-to-shard or chunk-to-shard mappings (tenant_123 -> shard_B). Routers cache these entries locally.
  • Resharding Trade-off: Resharding granularity is decoupled from mathematical rings. You can move a single hot tenant, split an overloaded chunk, or isolate a noisy neighbor without disturbing unrelated keys. However, it introduces an external dependency and cache invalidation overhead.
  • Migration Execution:
    1. The migrator replicates chunk $C$ from $Shard_1$ to $Shard_2$.
    2. The migrator marks chunk $C$ as MIGRATING in the directory, briefly quiescing or locking writes for chunk $C$ (or applying a versioned fencing token).
    3. The catalog updates the mapping for $C$ to $Shard_2$ with a higher version (v2).
    4. $Shard_1$ rejects writes with a stale version error (STALE_CONFIG), forcing routers to invalidate their local cache and fetch the new pointer.

Comparison Table

DimensionAlgorithmic (Hash / Range)Directory-Based
Routing Latency$O(1)$ in-memory CPU calculation; 0 ms network overhead.In-memory lookup on cache hit; 1-5 ms network hop on cache miss / invalidation.
Rebalancing Blast RadiusAffects entire ring ranges or mathematically tied buckets.Isolated strictly to the chunk/tenant being moved.
Skew ManagementPoor for hash; uneven key density or hot keys cannot be split without re-hashing or sub-key salting.Excellent; hot partitions can be mapped independently to dedicated hardware.
Consistency During CutoverRequires coordinated client rollout or fencing proxies to prevent stale writes.Controlled via monotonic chunk versioning and authoritative lookup checks.

Failure Modes & Cutover Mechanics

Under directory routing, the critical failure mode is directory unavailability or cache stampede. If the metadata layer fails, routers cannot invalidate or discover new routes. Mitigate this with versioned fencing tokens: physical shards validate that incoming write requests carry the current chunk version $\ge$ the shard's local state, rejecting stale router requests without querying the central catalog on every write.

Under algorithmic routing, dynamic splits typically require proxy layers (e.g., Vitess VTGate) that handle split-range routing at the proxy layer, shielding downstream clients from state changes but moving the architectural burden into proxy connection management.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

Explain how connection pooling affects database scaling.

Answer

What a strong candidate says first

A database's useful concurrency sits far below its connection limit. PostgreSQL's max_connections defaults to 100 and MySQL 8.0's to 151, but throughput on a 16-core box flattens well before that. Past roughly twice the core count you are paying for context switches, per-backend memory and lock contention, and adding connections makes throughput worse. The resource to manage is in-flight work, not connections. A pooler multiplexes many client connections onto a small number of server connections: the application thinks it has hundreds, the database sees 10–20.

The PostgreSQL wiki's sizing heuristic is connections = (core_count × 2) + effective_spindle_count: for a 16-core SSD-backed instance that is about 32, not 100.

Size the pool from arithmetic, not vibes

Little's Law: concurrency = arrival rate × service time.

  • 2,000 transactions/s at 5 ms each → 2,000 × 0.005 = 10 concurrent transactions. A pool of 10–20 covers it.
  • Same pool, transaction duration drifts to 50 ms → 10 / 0.05 = 200 transactions/s ceiling. The application now blocks in getConnection() and throws after HikariCP's connectionTimeout (default 30 s) while database CPU sits at 30%.

That second case is the classic misdiagnosis. Connection-acquisition timeouts look like a pool that is too small, but the pool is correctly sized and the transactions are too long. Raising default_pool_size from 20 to 100 buys a little headroom and then makes it worse.

Memory is the other half

Each PostgreSQL connection is a backend process with roughly 5–10 MB of base memory, plus work_mem (default 4 MB) per sort or hash node. 100 connections running a query with three such nodes: 100 × (10 MB + 3 × 4 MB) ≈ 2.2 GB, on top of shared_buffers. That memory is held whether or not the connection is doing work.

Defaults worth knowing

SettingDefaultWhere
max_connections100PostgreSQL postgresql.conf
max_connections151MySQL 8.0
work_mem4 MBPostgreSQL
default_pool_size20PgBouncer pgbouncer.ini
pool_modesessionPgBouncer
max_client_conn100PgBouncer
maximumPoolSize10HikariCP
connectionTimeout30 sHikariCP

Pooling mode decides what breaks

Session mode pins one server connection per client for the client's lifetime: safe for everything, and PgBouncer's default. Transaction mode hands the server connection back at COMMIT, which is where the efficiency comes from and where the bugs live: session-level SET, advisory locks held outside a transaction, LISTEN/NOTIFY, and temporary tables all assume the same backend across statements. PgBouncer 1.21 (2023) added protocol-level prepared-statement support in transaction mode via max_prepared_statements, off by default; before that, prepared statements were the classic breakage.

Failure modes and how you see them

  • Pool exhaustion under long transactions. Symptom: SQLTransientConnectionException from HikariCP after 30 s, database CPU low. Detect with pool wait-time metrics and pg_stat_activity counts.
  • Idle in transaction. A client opens a transaction and stalls; in transaction mode it pins a server connection. Detect via pg_stat_activity where state = 'idle in transaction'; bound it with idle_in_transaction_session_timeout.
  • Deploy storm. 200 pods × maximumPoolSize 10 = 2,000 connections against max_connections 100. A pooler in front, or a much smaller per-pod pool, is the fix.

When not to pool

A single long-lived worker holding one connection gains nothing. And if the application genuinely needs session state and cannot be changed, session pooling is the answer: transaction pooling will fail intermittently and confusingly.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

How does caching help database scaling, and where does it go wrong?

Answer

What a strong candidate says in the first 90 seconds

Caching helps database scaling by removing reads, not by serving them faster. A cache hit never reaches the database, so the database's read throughput requirement drops by the hit ratio. If a service serves 50k reads/s at a 95% hit ratio, the database sees 2,500 reads/s: a 20× reduction, usually the difference between one primary and a sharded cluster.

Assumptions that decide the answer: the workload is read-heavy, the data is read far more often than it changes, and it tolerates bounded staleness. If any of those is false (a ledger, a read-after-write path a user is watching) caching is the wrong tool and you scale the database instead.

The standard pattern is cache-aside: read the cache, on a miss read the database and populate. It degrades gracefully, because a cache outage means slower, not broken.

Where it goes wrong

Invalidation is the hard part, and there are three honest strategies:

StrategyFreshnessWrite-path costFailure mode
Cache-aside + TTLbounded by TTLnonestale until TTL expires
Cache-aside + delete on write~immediateevery write path must deleteone missed delete → stale until TTL
Write-throughimmediatewrite blocks on cachecache down = writes down
Write-behindimmediate readasync flushcache dies before flush = lost writes

My default is TTL plus explicit delete on write: the delete gives freshness in the common case, the TTL bounds the damage when a write path forgets, and one eventually will, via a script, a new service, or an admin action.

Cache-aside with negative caching (Python 3.12, redis-py 5.x):

Python
import json, redis
r = redis.Redis(host="cache", port=6379, decode_responses=True)

def get_user(tenant_id: int, user_id: int):
    key = f"user:{tenant_id}:{user_id}"      # tenant is part of the key
    cached = r.get(key)
    if cached == "":                          # negative-cache marker
        return None
    if cached is not None:
        return json.loads(cached)
    row = db.query("SELECT * FROM users WHERE tenant_id=%s AND id=%s",
                   tenant_id, user_id)
    if row is None:
        r.set(key, "", ex=30)                 # short TTL on the miss
        return None
    r.set(key, json.dumps(row), ex=300)
    return row

Trace it. First call for tenant 7, user 42: GET returns None, not "", so we query, get a row, SET ... EX 300, return it. Second call: GET returns the JSON string, json.loads it, database untouched. Call for user 999 who does not exist: GET returns None, query returns None, SET key "" EX 30, return None. Next call for 999: GET returns "", return None. The database is not touched again for 30 seconds.

Stampede, with arithmetic. A hot key serves 20k req/s and the database read takes 50 ms. On expiry, every request in the next 50 ms misses: 20,000 × 0.05 = 1,000 concurrent identical queries. With a 100-connection pool, 100 run and 900 queue; p99 for the whole service climbs even though only one key expired. Fixes: a single-flight lock (SET lock:user:7:42 <uuid> NX EX 5, released with a compare-and-delete Lua script so you never delete someone else's lock), serving stale while one request refreshes, or probabilistic early expiration (XFetch) to spread refreshes before the TTL fires.

Penetration. Requests for keys that never exist bypass the cache every time: the negative cache above is the fix.

Stale repopulation. A read that starts before a write and finishes after the delete can write the old value back with a full 300 s TTL ahead of it. Nastier than a plain miss. Mitigate by deleting after the write commits, or reading the primary inside that window.

Key design. The key must contain everything the value depends on. Drop the tenant and you serve one customer's row to another: the worst bug in this area, from an easy omission.

Bounded memory. Set maxmemory (e.g. 4gb) and a policy. allkeys-lru is the safe default; allkeys-lfu is better when a small set of keys dominates traffic; volatile-lru only evicts keys with a TTL. An unbounded cache is an incident on a timer.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

How would you reduce database load without changing the schema?

Answer

Assumption first. "Without changing the schema" I read as no new columns, tables or types: nothing that changes what the data model is. Indexes are DDL, but they are additive, reversible with DROP INDEX CONCURRENTLY, and don't change the logical schema, so I'd include them and say so out loud. If the interviewer means no DDL at all, the answer shifts entirely to query, cache, replica and demand-side work.

Order of attack. Measure first: pg_stat_statements ordered by total_exec_time tells you where the load actually is. Without it you optimise the query you remember, not the one that's hot.

Then, roughly by impact per unit of risk: query fixes, indexes, caching, batching writes, read replicas, a connection pooler, config and maintenance, and finally reducing demand at source.

Worked example: the two biggest wins, with numbers.

N+1: 500 orders, one query per order to fetch the customer. At 0.4 ms round trip that is 500 × 0.4 = 200 ms of pure network latency before any execution cost, plus 500 executions. One WHERE id = ANY($1) with 500 ids is 2 round trips and roughly 1 ms: about 100× fewer round trips.

OFFSET: a 10M-row table, 20 rows per page, page 50,000 means OFFSET 1000000. Postgres walks and discards 1M index entries before returning 20 rows; at ~1 µs per row that is ~1 s. Keyset pagination, WHERE (created_at, id) < ($1, $2) ORDER BY created_at DESC, id DESC LIMIT 20, seeks straight to the position: sub-millisecond, and flat as the page number grows. The figures are illustrative, but the shape is the point: OFFSET cost is O(offset), keyset is O(page size).

Trade-offs: cache vs replica vs batch.

optionuse whendon't use when
cacheread:write ratio high, working set fits in memory, staleness tolerablehit rate is low, or invalidation correctness is hard to get right
replicareads tolerate seconds of lag, heavy analytics/reportingread-your-writes is required, or lag grows under write load
batchmany small writes to the same rowswrites are latency-sensitive

The deciding criterion is the staleness budget. Seconds stale → replica. Minutes stale and hot → cache. Must be fresh → fix the query instead.

Failure modes. Replica lag: streaming replication is typically sub-second but spikes under write bursts. Detect by comparing pg_last_wal_replay_lsn() against the primary and alerting on lag. Pooler: transaction pooling breaks session state (prepared statements, SET, advisory locks). Detect as errors appearing right after deploy. Cache: stampede at TTL expiry. Detect as a load spike at TTL boundaries; mitigate with jittered TTLs. Statement timeout: the default is 0 (off); once set you will start killing legitimate long reports, so set it per-role rather than globally.

Config and maintenance. shared_buffers defaults to 128MB, effective_cache_size to 4GB, autovacuum_vacuum_scale_factor to 0.2: all sized for a much smaller machine. pgbouncer's default_pool_size is 20; multiplexing a few hundred app connections onto 20–50 server backends is usually a step change, since each Postgres backend is a process with a few MB of private memory. Failing vacuum causes bloat that inflates every scan, and a long-running transaction blocking cleanup is free to fix once found.

Reduce demand at source. Is 5-second refresh needed, or would 30 do? Is the job scanning everything when a delta would work? Is the dashboard polling when it could be pushed? These remove load rather than accommodate it, and they are usually available precisely because nobody has questioned the requirement since it was written.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-20

Explain what you would do if a single query is bringing down the database.

Answer

First 90 seconds: stop it, block the source, then diagnose.

Kill the query, not the database. On PostgreSQL, find it:

SQL
SELECT pid, usename, state, wait_event_type, wait_event,
       now() - query_start AS runtime,
       now() - xact_start  AS xact_age,
       left(query, 80)     AS query
FROM pg_stat_activity
WHERE datname = current_database()
ORDER BY query_start;

Cancel before you terminate. pg_cancel_backend(pid) sends SIGINT: the current statement stops, the session and its pool slot survive. pg_terminate_backend(pid) sends SIGTERM and drops the connection, forcing the pool to reconnect. Cancel first; terminate only if the backend ignores it or is idle-in-transaction holding locks.

SQL
SELECT pg_cancel_backend(pid)
FROM pg_stat_activity
WHERE state = 'active'
  AND now() - query_start > interval '30 seconds'
  AND pid <> pg_backend_pid();

If retries re-issue it, killing is a treadmill. Block the source: disable the feature, rate-limit the endpoint, or revoke the role.

Worked trace: a blocking chain, not a slow query. Hypothetical pg_stat_activity output:

pidusenamestatewait_event_typewait_eventxact_agequery
8123appidle in transactionClientClientRead00:14:22UPDATE orders SET status='shipped' WHERE id=88121
8140appactiveLocktransactionid00:13:58SELECT ... FROM orders WHERE id=88121 FOR UPDATE
8141appactiveLocktransactionid00:13:57SELECT ... FROM orders WHERE id=88121 FOR UPDATE

8123 opened a transaction, updated order 88121, then stopped: the client hung before COMMIT. It holds a row lock for 14 minutes. 8140 wants the same row and waits on the transactionid lock; 8141 waits behind 8140. SELECT pg_blocking_pids(8140); returns {8123}: that is the head. pg_cancel_backend(8123) releases 8140, 8141 and everything queued behind them at once. This is why you find the head of the chain, not the tail: killing the visible waiters changes nothing.

Blast radius. With a 20-connection pool, 20 waiters exhaust it and the whole application stalls, not one endpoint. Check whether the long transaction blocked autovacuum, and expect a flood of queued work the moment the lock releases.

Diagnose. Was it always this bad, or did something change? Run EXPLAIN (ANALYZE, BUFFERS) and compare estimated to actual rows. A nested loop chosen on an estimate of 1 row against an actual 2.4M is a statistics or plan problem, not a query problem. Look for a changed parameter: a wider date range, a new tenant.

Prevent: the part usually skipped. In PostgreSQL, statement_timeout, lock_timeout and idle_in_transaction_session_timeout all default to 0, meaning disabled. idle_in_transaction_session_timeout = '30s' alone would have killed 8123 at 30 seconds instead of 14 minutes. Set them per role: ALTER ROLE app SET statement_timeout = '5s';. With 20 connections and a 5s timeout, a pool where every request times out still completes 20/5 = 4 requests per second: degraded, not deadlocked. Then bound user-supplied date ranges, route reporting to a replica with its own pool and role, and alert on pg_stat_statements mean time.

MySQL's equivalents: KILL QUERY <id> stops the statement, KILL CONNECTION <id> drops the session, and max_execution_time (default 0, SELECT only) is the timeout.

The retrospective point: the specific query is less interesting than the fact that any query could do this. Fixing the query without adding the timeout leaves the same exposure for the next one.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Explain what happens to a database as data volume grows, even without more traffic.

Answer

The 90-second answer. Nothing about your queries changed, but three things did. The working set, index pages plus the hot heap pages, outgrew the memory you gave it, so a growing share of reads now goes to disk. The planner's cost comparisons, which are computed from row and page counts, tipped far enough that some plans flipped. And the background work that keeps the table healthy (vacuum, backups, index rebuilds) now takes longer than the interval it runs on. All three are functions of size, not of request rate, which is why a flat QPS graph can sit above a degrading p99.

Indexes: one more level, then a cliff. PostgreSQL B-tree pages are 8 KB with fillfactor 90 by default. A bigint key plus the 6-byte TID and line pointer is roughly 20 bytes, so an internal page holds a few hundred entries: call it 400. Height 3 covers 400³ ≈ 64M rows, so a 100M-row table needs height 4. The extra page read is not the problem; the top levels are tiny and always cached. The leaf level is: 100M entries × 20 bytes ≈ 2 GB, which does not fit in the 128 MB default shared_buffers. Read the real height with pageinspect:

SQL
CREATE EXTENSION IF NOT EXISTS pageinspect;
SELECT level, root, fastlevel FROM bt_metap('orders_pkey');

MySQL's InnoDB has the same shape with 16 KB pages and a 128 MB default innodb_buffer_pool_size.

Cache arithmetic. [hypothetical] A 2 GB index over 1 GB of cache with uniform access misses on half the leaf lookups. Real access is skewed, so the true rate is better, but the shape is what matters: the miss rate tracks index size ÷ cache size, and it moves as the table grows even when the query mix does not.

Plans flip. The planner weighs seq_page_cost (1.0 by default) against random_page_cost for an index path, multiplied by estimated pages. At 1M rows a sequential scan of a 200 MB table is cheap; at 100M rows the same plan reads 20 GB. At 500 MB/s that is 40 seconds. The flip is a step, not a slope: that is why degradation looks sudden.

Autovacuum falls behind. Defaults are autovacuum_vacuum_threshold = 50 and autovacuum_vacuum_scale_factor = 0.2, so vacuum fires once 50 + 20% of the table is dead. At 1M rows that is ~200k dead tuples; at 100M rows it is ~20M. Dead tuples accumulate 100× longer before anything runs, and the vacuum then has 100× more work. Bloat inflates every scan and index, which makes the next vacuum slower still.

Restore time. [hypothetical] A 20 GB heap plus 2 GB of indexes restored at 100 MB/s is ~4 minutes of data movement, plus index rebuild, which usually dominates. That is an RTO problem, not a latency one, and it surfaces during the incident.

What to do. Bound how much data every query can touch. Decide retention early: partitioning is far easier before the table is enormous. Trend growth weekly:

SQL
SELECT relname, pg_size_pretty(pg_total_relation_size(relid)) AS total,
       n_live_tup, n_dead_tup, last_autovacuum
FROM pg_stat_user_tables
ORDER BY pg_total_relation_size(relid) DESC
LIMIT 10;

That gives a runway estimate in months, which is the difference between a scheduled partition change and an outage. Because these effects are volume-driven, they are predictable: table growth is one of the easiest things to trend.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

What is the role of archiving in database scaling?

Answer

Archiving is the one common scaling lever that shrinks the problem instead of accommodating it. It removes rows the operational database no longer has to serve, so indexes fit in memory, scans touch fewer pages, backups finish sooner, and autovacuum has less dead space to chase. Replicas, sharding and bigger instances all buy capacity for data you are still storing.

The prerequisite is a retention policy, and that is a business and legal decision: a minimum from regulation (financial records are often kept 7 years), a maximum from privacy rules such as GDPR's storage-limitation principle. Those pull in opposite directions, and no engineering change resolves them.

Worked example. An orders table, 1.2B rows at ~400 bytes/row, is ~480 GB of heap. Range-partitioned monthly that is 10M rows and ~4 GB per partition, plus a btree index at roughly 30 bytes per entry, so ~300 MB per partition. A 24-month retention policy leaves 24 partitions: ~96 GB heap and ~7 GB of index. Dropping the other 96 partitions removes ~384 GB of heap and ~29 GB of index. A pg_basebackup at 100 MB/s takes ~80 minutes at 480 GB and ~16 minutes at 96 GB. Sizes are estimates: measure with pg_total_relation_size and pg_relation_size.

Dropping a partition is metadata; deleting rows is work. Postgres 14+:

SQL
ALTER TABLE orders DETACH PARTITION orders_2019_01 CONCURRENTLY;
DROP TABLE orders_2019_01;

DETACH ... CONCURRENTLY cannot run inside a transaction block; it takes SHARE UPDATE EXCLUSIVE on the parent and a brief ACCESS EXCLUSIVE at commit. DROP TABLE unlinks that partition's files and touches nothing else. Compare:

SQL
DELETE FROM orders WHERE created_at < '2022-01-01';  -- 120M rows

Every deleted row writes a WAL record and leaves a dead tuple. The heap file does not shrink: autovacuum makes the space reusable, but the high-water mark stays, and the indexes bloat too. VACUUM FULL rewrites the table under ACCESS EXCLUSIVE. On a 480 GB table that is hours of blocked writes against milliseconds for the detach.

Where the data goes. Three options, chosen by the policy:

Policy saysActionCost
Not neededDrop the partition~0
Must keep, rarely readExport to object storageS3 Standard $0.023/GB-month vs Glacier Instant Retrieval $0.004/GB-month (AWS us-east-1 list, 2024): 384 GB is $8.83 vs $1.54 per month
Only trends matterAggregate to a daily rollup, drop detailRollup is roughly 1/1000 the rows

TimescaleDB wraps the first two as add_retention_policy / drop_chunks; MySQL uses ALTER TABLE ... DROP PARTITION; Percona's pt-archiver moves rows in batches when the table was never partitioned.

Failure modes. The application still reads old rows: SELECT ... WHERE order_id = ? returns nothing once the partition is gone. Track the not-found rate and keep a read path into the archive. A foreign key from a live table into an archived one blocks the drop or leaves dangling references. An archive nobody has restored is not an archive: restore a sample quarterly. A legal hold overrides the policy for specific rows; keep a hold table and exclude those rows from the drop. And partition pruning only happens when the query filters on the partition key: check EXPLAIN for a scan across every partition.

When not to. If the table is small, or the growth is in a hot table you already prune, archiving buys nothing. If the data must stay queryable at interactive latency, you are moving it rather than archiving it, and you have added a second system to operate.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

How would you scale a write-heavy workload?

Answer

Core answer (first 90 seconds). Pin down three things before touching anything: the sustained write rate and its peak-to-mean ratio, the durability requirement (can we lose the last few hundred milliseconds of acknowledged writes on a crash?), and whether writes are spread across keys or concentrated on a few rows. Then work in this order: cut write volume at the source, cut the cost of each write, remove contention, and only then add machines.

On a single node the ceiling is usually commits per second, not rows per second. With PostgreSQL's default synchronous_commit = on, every commit waits for a WAL fsync: roughly 0.5–2 ms on a local NVMe SSD. At 1 ms, one connection doing one-row commits tops out near 1,000 commits/s before any row work happens. Two levers fix that: batch (1,000 rows per statement is 1,000× fewer fsyncs) and synchronous_commit = off, which returns before the flush. The documented exposure is up to 3 × wal_writer_delay (default 200 ms) = 600 ms of acknowledged transactions lost on an OS crash, with no corruption. That is a real trade, not a free win.

Cut per-write cost. Every secondary index adds a B-tree insert and its own WAL records. A table with four indexes does five B-tree writes per row. Keep only indexes a named query needs. Leave table fillfactor below 100 so HOT updates, where no indexed column changed and the new tuple fits on the same page, skip new index entries entirely. Note that "update the row to the value it already holds" still writes a new tuple version under MVCC; HOT is what makes it cheap.

Remove contention. A single counter row serialises every writer no matter how fast the disk is. Shard it into N rows (UPDATE counters SET v = v + 1 WHERE shard = $1, shard chosen at random) and read SELECT sum(v). N = 16 turns one lock queue into 16; the cost is a 16× more expensive read and a non-atomic sum. Better still, append events and aggregate later: inserts at the right edge of a B-tree don't hold a lock for the length of a transaction the way updates to one row do.

Spread. Partitioning keeps indexes smaller and makes retention O(1): DETACH PARTITION is a catalog update, while deleting a day's rows writes WAL for every row and leaves dead tuples for autovacuum. Partitioning alone does not spread writes: the newest partition is still the only target. Sharding is the only way to add write capacity horizontally, and the shard key has to spread the writes: hashing user_id works, sharding by tenant_id when one tenant is 40% of traffic just relocates the hot spot.

If the workload is append-dominant with point or range reads, an LSM store (Cassandra, RocksDB, ScyllaDB) converts random writes into a sequential commitlog append plus a memtable write, acking after the append. The price is read amplification and compaction I/O competing with foreground writes.

Failure modes. synchronous_commit = off plus a failover can lose commits a client already saw: detect by reconciling application-side ack counts against row counts. A queue in front of the database makes the queue the durability boundary; watch consumer lag, not queue depth. Sum-on-read counters are not atomic with the increment, so a reader can see a partial sum: fine for view counts, not for balances.

Worked check: 10,000 inserts/s peak into page_views with four secondary indexes:

  • Per row: 1 heap tuple + 4 index entries = 5 B-tree writes → 50,000/s.
  • Drop to the one index a named query needs → 20,000/s. 60% of the write work gone.
  • Batch 1,000 rows per statement → 10 commits/s instead of 10,000. At ~1 ms per fsync that is 10 ms of fsync per second instead of 10 s.
  • Partition by day and DETACH for retention.
settingdefaulteffect
synchronous_commitonoff returns before WAL flush; lose up to 3 × wal_writer_delay (600 ms) on OS crash, no corruption
commit_delay / commit_siblings0 / 5group commit: one fsync covers several transactions
wal_buffers-1 (auto: 1/32 of shared_buffers, capped at 16 MB)absorbs bursts before flush
full_page_writesonfirst write to a page after a checkpoint writes the full 8 kB page to WAL; off risks torn pages
table fillfactor100below 100 leaves page room so HOT updates skip new index entries

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

How would you scale a system where reads and writes have very different requirements?

Answer

Ask two things before designing: the read:write ratio, and how stale a read is allowed to be. If reads outnumber writes 40:1 and 200 ms of staleness is acceptable, this is a routing problem, not an architecture problem. One schema, writes to the primary, reads to replicas. Split the models only when the two workloads want incompatible physical shapes: one append-heavy and narrow, the other wide and indexed for a handful of query patterns.

Replicas first. Postgres 16 streaming replication is asynchronous by default: the primary commits and ships WAL, the replica replays it. Lag is single-digit milliseconds on an idle primary and grows under write bursts or long analytical queries on the replica. Two settings do the real work. hot_standby_feedback = on stops replica queries being cancelled with "conflict with recovery". synchronous_commit = remote_apply (with synchronous_standby_names set) makes a commit wait until a replica has replayed it, which buys read-your-writes on that replica and adds a network round trip to every commit: I would rather not pay that globally.

Then split the models. Write side: append-only, minimal indexes, normalised. Read side: denormalised, indexed for the actual query patterns, possibly precomputed. That is CQRS in substance. The write side publishes changes through an outbox table written in the same transaction, or through change data capture: Debezium reading a Postgres logical replication slot (wal_level = logical) into Kafka. The read side consumes and projects.

The property that makes this safe is that the read model is derived: rebuildable from the write model, owning nothing. If both sides are authoritative for overlapping data, inconsistencies become unresolvable. Design the rebuild path from the start (replay the topic from offset 0 into a fresh table, then swap) because you will need it for a projection bug, a schema change, or a backfill.

Failure modes. A projection that silently stops leaves the read side quietly wrong: alert on consumer lag and on a periodic row-count reconciliation between write and read models. Replica lag spikes past the staleness budget: reads that inform a write decision, and a user's own recent writes, must go to the primary. Dual-writing to both stores without a shared transaction loses updates under partial failure.

Worked example (hypothetical figures).

write pathread path
shapeappend-only, 2 indexesdenormalised, 6 covering indexes
targetp99 commit 8 msp99 query 30 ms
scales bypartitioning by tenantadding replicas, then cache
consistencylinearizable per keyeventual, ≤200 ms stale

Routing rule with a sticky window:

Python
PRIMARY = "pg-primary"
REPLICAS = ["pg-replica-1", "pg-replica-2"]
STICKY_S = 2.0

def route(last_write_ts, now, lag):
    if now - last_write_ts < STICKY_S:
        return PRIMARY
    for r in REPLICAS:
        if lag[r] < 0.5:
            return r
    return PRIMARY

Trace: a user wrote at t=100.0. At now=100.5 with lag {replica-1: 0.9, replica-2: 0.2}, 100.5 - 100.0 = 0.5 < 2.0, so it returns pg-primary. At now=103.0, 3.0 >= 2.0, replica-1's lag 0.9 fails the check, replica-2's 0.2 passes, so it returns pg-replica-2.

Arithmetic: 2,000 writes/s and 80,000 reads/s is 40:1. A replica serving 12,000 indexed reads/s needs 7 replicas. If 5% of reads are read-your-writes, that is 4,000 reads/s landing on the primary: check it has headroom before committing to the sticky window.

I would not start here. One database, replicas when reads justify them, separate models only when the workloads genuinely conflict. The intermediate steps are cheap and often sufficient; the separated design's cost is permanent.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

How do you handle a query that must join or aggregate across shards, and a transaction whose rows land on different shards?

Answer

Core answer (first 60–120 seconds): In a sharded system, cross-shard operations are the exception you design around, not the norm. The first move is to choose a shard key that co-locates the rows a single logical operation touches, if a query joins orders and customers, shard both by customer_id. When that’s impossible, you have four concrete options, and each trades latency, correctness, and operational complexity differently.

For reads (joins/aggregations):

  1. Scatter-gather: send the query to every shard, merge in the application. Latency is the max of all shard latencies plus merge time. The p99 is the killer: if each shard’s p99 is 20 ms, querying 10 shards makes the overall p99 roughly the 99.9th percentile of a single shard. Often 50–100 ms. Correctness is fine if shards are read-only snapshots, but partial failures need handling. Operational complexity: fan-out load, timeouts, partial results.
  2. Denormalized copy: keep a read-optimized copy of the needed data on the shard that needs it, updated via CDC or an outbox. Latency is local and fast. Correctness is eventual; you must monitor lag and have a rebuild path. Complexity: sync mechanism, idempotency, monitoring.

For writes (transactions across shards):

  1. Two-phase commit (2PC): a coordinator prepares all shards, then commits. Latency adds at least one round trip and holds locks across shards, increasing contention. Correctness is atomic but blocking: coordinator failure leaves participants in doubt until recovery. Operational complexity: coordinator HA, recovery logs, monitoring.
  2. Sagas: a sequence of local transactions with compensating actions. Latency is lower than 2PC, but correctness is eventual and compensations must be idempotent. Complexity: designing compensations, handling partial failures.
  3. Avoid it: redesign so the transaction is single-shard. Co-locate by shard key, or route the write to the shard that owns the aggregate root.

Detection: Monitor cross-shard query rate, fan-out count, p99 latency, and coordinator involvement. If cross-shard access dominates, say >10% of queries or >50% of p99 latency, revisit the shard key first. Co-locating the hot access pattern is the highest-leverage fix. If that’s impossible, denormalize the specific read path. For writes, try to make transactions single-shard before reaching for 2PC.

Failure modes: Scatter-gather: one slow shard stalls the whole query; use hedged requests or timeouts. Denormalization: stale data, sync lag; monitor and alert. 2PC: coordinator crash leaves locks; need recovery. Sagas: compensation failure leaves inconsistent state; need idempotent retries and dead-letter queues.

Table:

OptionLatencyCorrectnessOperational complexity
Scatter-gatherp99 amplificationSnapshot-consistentFan-out, timeouts, partial results
Denormalized copyLocal, fastEventualCDC/outbox, monitoring, rebuild
Co-location (shard key)LocalStrongResharding or careful key design
2PC+1 RTT, locksAtomic, blockingCoordinator HA, recovery
SagasLower than 2PCEventualCompensations, idempotency

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

How would you handle one tenant that is far larger than all the others?

Answer

Quantify the skew first, then work three levers in order of cost: bound what the tenant can break, make the planner see them, and only then split them out.

Quantify

rows in events7-day windowshare of table
median tenant50,000~4800.0000025%
p95 tenant2,000,000~19,0000.1%
largest tenant (id 42)400,000,000~3,800,00020%
all 10,000 tenants2,000,000,000—100%

Illustrative figures for a 2B-row table with two years of history. The largest tenant is 8,000x the median and a fifth of the table. Anything sized for the median is wrong for them by three orders of magnitude.

1. Bound the blast radius

Cheapest lever, and it keeps the other 9,999 tenants alive while you work on the rest.

SQL
ALTER ROLE app SET statement_timeout = '5s';
ALTER ROLE app SET idle_in_transaction_session_timeout = '30s';

A separate PgBouncer pool (or a separate max_connections budget) for the large tenant, so their nightly export cannot take all 100 connections. Per-tenant rate limiting at the API layer, keyed on tenant id. Tuning for the largest tenant is a treadmill: they keep growing; bounding them is not.

2. Make the planner see them

Two mechanisms.

Statistics. With default_statistics_target = 100 and 10,000 distinct tenant ids, only the top ~100 tenants appear in the MCV list. Tenants below that get the average-of-non-MCV estimate. Raising the target is cheap:

SQL
ALTER TABLE events ALTER COLUMN tenant_id SET STATISTICS 1000;
ANALYZE events;

Prepared statements. This is the one that bites the largest tenant. With plan_cache_mode = auto (the default), PostgreSQL starts comparing a generic plan against the custom ones after five executions, and a generic plan cannot use the parameter value: tenant_id = $1 falls back to 1/n_distinct and created_at >= $2 to the default inequality selectivity of 1/3.

SQL
PREPARE tenant_report(bigint, timestamptz) AS
SELECT u.email, count(*) AS n
FROM events e JOIN users u ON u.id = e.user_id
WHERE e.tenant_id = $1 AND e.created_at >= $2
GROUP BY u.email ORDER BY n DESC LIMIT 10;

EXPLAIN (ANALYZE) EXECUTE tenant_report(42, now() - interval '7 days');
Limit
  -> Sort
       -> HashAggregate
            -> Nested Loop  (actual rows=3835616 loops=1)
                 -> Index Scan using events_tenant_created_idx on e
                      Index Cond: (tenant_id = 42 AND created_at >= ...)
                      (rows=66667) (actual rows=3835616 loops=1)
                 -> Index Scan using users_pkey on u
                      Index Cond: (id = e.user_id)
                      (rows=1) (actual rows=1 loops=3835616)

The generic plan estimates 66,667 rows: 2B x (1/10,000) x 1/3. The truth is 3,835,616, a 58x miss, and it drives 3.8M random index lookups on users. Forcing a custom plan lets the planner read tenant 42 out of the MCV list and pick a hash join instead:

SQL
SET plan_cache_mode = force_custom_plan;   -- or SET LOCAL for one query

Also raise work_mem for this query class: the default 4 MB hash table spills once the aggregate sees millions of groups.

3. Isolate them

If that is not enough, move the largest tenants out.

SQL
CREATE TABLE events (tenant_id bigint NOT NULL, created_at timestamptz NOT NULL, ...)
  PARTITION BY LIST (tenant_id);
CREATE TABLE events_t42  PARTITION OF events FOR VALUES IN (42);
CREATE TABLE events_rest PARTITION OF events DEFAULT;
ALTER TABLE events_t42 SET (autovacuum_vacuum_scale_factor = 0.01);

Hash partitioning by tenant_id does not isolate them: tenant 42's 400M rows spread across all 64 partitions. LIST partitioning does, and it lets you set per-partition autovacuum. The default partition still holds 1.6B rows, so hash-partition that one too.

Autovacuum is the reason this matters. With the default autovacuum_vacuum_scale_factor = 0.2 and autovacuum_vacuum_threshold = 50, a 2B-row table needs 400,000,050 dead tuples before autovacuum fires. At 6M dead tuples/day across all tenants, that is 67 days of bloat. Per-partition, events_t42 (400M rows) fires at 80M dead tuples instead.

The heavier option is a separate database or cluster for the top tenants. It removes them as a noisy neighbour entirely and lets you tune for their shape, at the cost of a routing layer and a second operational path you have to keep alive.

Failure modes

  • The large tenant's batch job saturates the shared connection pool; other tenants see connection timeouts. Detect with per-tenant connection counts.
  • Autovacuum never catches up on the shared table; index bloat slows scans for everyone. Detect via pg_stat_user_tables.n_dead_tup and last_autovacuum.
  • A generic plan that is fine for 9,999 tenants is catastrophic for one. Detect via pg_stat_statements, comparing mean_exec_time for the same queryid across tenants.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

What would you do if a database migration is too slow to complete in a maintenance window?

Answer

The premise deserves questioning first: a migration that needs a maintenance window is usually one that could be restructured to need none. Maintenance windows are a decreasingly acceptable answer, and designing to avoid them is generally cheaper than negotiating them.

Restructure into an online sequence. Expand–migrate–contract: add the new structure as optional; deploy code writing both old and new; backfill in bounded batches; then deploy code reading the new; then remove the old. Each step is fast, independently reversible, and requires no window. The write and read steps must be separate deploys, because both versions run concurrently during a rollout and rollback must stay safe.

Batch the backfill with a pause between batches so no single transaction holds locks long or generates unmanageable WAL, and make it resumable and idempotent so a failure mid-run is re-run rather than reconciled by hand.

Watch replication lag during the backfill. A large one pushes replicas behind, and that is frequently what actually breaks: before anything on the primary does.

Avoid the operations that require rewrites or long locks. Adding a constraint validated against every row takes a long lock unless added NOT VALID and validated separately. Building an index concurrently avoids blocking writes at the cost of a slower build.

If the table is too large even for batched backfill, the fallback is a shadow table with triggered dual writes and an atomic rename at the end. Considerably more work, so I would exhaust the batched approach first.

Rehearse on a production-sized copy and measure there. A migration timed on staging data tells you nothing about production duration, and that mismatch is how migrations end up half-complete in a window.

And I would make sure it can be abandoned midway. A migration that must complete once started is the dangerous kind, if the backfill can be paused and the system left in a consistent intermediate state, then running out of time is an inconvenience rather than an incident.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-1

Walk through how you would approach a database that is running out of capacity.

Answer

The 90-second version. Before touching anything, find which resource is saturated: CPU, disk I/O, memory, connections, or lock waits. They point in different directions: an I/O-bound box gains nothing from more cores, and a connection-bound box gains nothing from either. Then rank queries by total execution time, not mean, because a 40 ms query called 1.2M times a day costs more than an 88 s report called 2,000 times. Then check maintenance, which is free to fix. Only then climb the ladder: index → pool → cache → bigger box → replicas → partition → shard. Each rung trades something permanent (consistency, operational simplicity, query flexibility) for capacity, so measure before each step and be willing to stop.

Assume Postgres 16, single primary, 8 vCPU / 32 GB, 400 GB of data, OLTP plus a reporting path.

1. Name the saturated resource. pg_stat_statements for query time, pg_stat_activity for waits, pg_stat_user_tables for bloat. If wait_event_type = 'IO' dominates it is I/O; if 'LWLock' or 'Lock', it is contention.

2. Rank by total time.

SQL
SELECT queryid, calls, mean_exec_time, total_exec_time,
       total_exec_time / sum(total_exec_time) OVER () AS share
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;

Hypothetical output for this box:

querycalls/daymean_exec_timetotal_exec_time/dayshare
A: SELECT ... FROM events WHERE tenant_id=$1 AND created_at > now() - interval '30 days'2,00088 s176,000 s32%
B: SELECT ... FROM orders WHERE customer_id=$11,200,00042 ms50,400 s9%
C: UPDATE orders SET status=$1 WHERE id=$2900,0001.8 ms1,620 s0.3%

8 cores × 86,400 s = 691,200 core-seconds/day; at 80% sustained that is ~553,000 s of execution. A and B are 41% of it.

3. Fix A. events is 1.2B rows / 300 GB with an index on (tenant_id) only, so the planner bitmap-scans every row for the largest tenant: ~160M rows, ~40 GB of heap at the ~450 MB/s this box sustains, which is the 88 s. A composite index turns it into a range scan of the last 30 days for that tenant, ~4.4M rows, ~1.1 GB, ~2.5 s:

SQL
CREATE INDEX CONCURRENTLY idx_events_tenant_created
  ON events (tenant_id, created_at DESC);

2,000 calls × 2.5 s = 5,000 s/day, down from 176,000: about 25% of the box's daily budget back. CONCURRENTLY avoids blocking writes but can fail and leave an invalid index; check pg_index.indisvalid and drop it if false. The cost is real: every insert into events now maintains one more index.

4. Maintenance. SELECT relname, n_dead_tup, last_autovacuum FROM pg_stat_user_tables ORDER BY n_dead_tup DESC LIMIT 10;: bloat inflates every scan and looks exactly like insufficient memory. Default autovacuum_vacuum_scale_factor = 0.2 means a 1.2B-row table waits for 240M dead tuples; override per table with ALTER TABLE events SET (autovacuum_vacuum_scale_factor = 0.01);. A single transaction open for hours holds the xmin horizon and blocks cleanup database-wide: find it in pg_stat_activity by now() - xact_start.

5. The ladder.

rungchangescostreversible?trades away
index / rewrite querywork donelowyeswrite throughput
connection poolingconcurrencylowyessession state
cache / matviewread loadmediumyesfreshness
vertical scalespeed of everythinghigh $, minutes of failoveryesmoney
read replicaread capacitymediumyesread-your-writes
partitiontable size, retentionmediumhardcross-partition plans
shardwrite capacityvery highnojoins, transactions, ops

Pooling is often the step change: Postgres forks a process per connection, and 500 connections on 8 cores context-switch more than they execute. pgbouncer with pool_mode = transaction, default_pool_size = 20 is the usual shape, but transaction mode breaks session-scoped state, and you will see prepared statement "S_1" does not exist when it does.

Replicas are async streaming by default, so check pg_stat_replication.replay_lag before routing reads; a replica 30 s behind serves stale rows. Sharding last, because it is the only rung that scales writes and the only one you cannot walk back.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

How would you decide whether a slow report should be optimised, moved, or precomputed?

Answer

Assumptions I'd state up front: the report is read-only, the engine is PostgreSQL (or an MVCC engine with the same shape), and "slow" means p95 over the last week rather than one bad run.

The decision comes from two measurements, not from taste: how much work the query does versus how much it needs to, and how often it runs. pg_stat_statements gives mean_exec_time, calls, shared_blks_read and shared_blks_hit per query. Rows read per row returned tells you whether to optimise; calls per hour tells you whether to precompute; read volume against shared_buffers tells you whether to move.

Optimise when the query reads far more than it returns. A worked trace, on a 200M-row orders table with shared_buffers = 8GB:

SQL
EXPLAIN (ANALYZE, BUFFERS)
SELECT customer_id, sum(total)
FROM orders
WHERE date_trunc('day', created_at) = DATE '2024-06-01'
GROUP BY customer_id;
HashAggregate  (actual time=18420.113..18431.902 rows=548213 loops=1)
  Buffers: shared hit=1200 read=1048576
  ->  Seq Scan on orders  (actual time=0.041..16210.552 rows=548213 loops=1)
        Filter: (date_trunc('day'::text, created_at) = '2024-06-01'::date)
        Rows Removed by Filter: 199451787
        Buffers: shared hit=1200 read=1048576
Execution Time: 18435.771 ms

date_trunc on the column makes the predicate non-sargable, so no index can be used: 1,048,576 blocks read is 8 GiB of heap to return 548,213 rows. 365 rows read per row returned. Rewriting to a range predicate on the bare column, with an index on (created_at, customer_id):

SQL
WHERE created_at >= TIMESTAMP '2024-06-01 00:00:00'
  AND created_at <  TIMESTAMP '2024-06-02 00:00:00'
Index Scan using orders_created_at_customer_id_idx  (actual time=0.038..206.114 rows=548213 loops=1)
  Buffers: shared hit=3100 read=12400
Execution Time: 214.882 ms

18,436 ms to 215 ms, 8 GiB to 97 MB. No ongoing cost, so this is always checked first.

Move it when the query is already efficient but its footprint is the problem. The 8 GiB scan above, run 20 times an hour, evicts a working set that fits in 8 GB of shared_buffers, and the cache stays cold after the query ends: that is the damage to unrelated transactional traffic. Detection is shared_blks_read climbing on other queries in pg_stat_statements while the report runs. Routing to a replica removes the contention without touching the query. Caveats: replication lag (check pg_last_xact_replay_timestamp; reports usually tolerate seconds), and long reads cancelling WAL replay on the replica. max_standby_streaming_delay defaults to 30s, after which the conflicting query is cancelled, so raise it deliberately or set hot_standby_feedback and accept bloat on the primary.

Precompute when the query is efficient, isolated, and still too slow or too frequent. A dashboard viewed 400 times an hour at 12s of CPU each is 4,800 CPU-seconds per hour: 1.33 cores running continuously. A materialised view refreshed hourly costs 12s, 0.33% of that, and turns the scan into a lookup.

The costs are real: staleness bounded by the refresh interval and labelled on the page (as of 04:00), a backfill path for a missed refresh, and a reconciliation job that recomputes a sample live and compares. A rollup that drifts silently is worse than none. REFRESH MATERIALIZED VIEW CONCURRENTLY needs a unique index and still does a full scan plus a diff, so it is not free.

MeasurementRemedyOngoing cost
Rows read / rows returned > 100OptimiseNone
Report read volume > shared_buffers, other queries' blks_read risingMove to replicaLag tolerance, replica config
Efficient, isolated, > ~100 calls/hourPrecomputeStaleness ≤ refresh interval

They compose in that order, and I'd also ask whether the report needs to be live at all: a scheduled email often serves the need better than a page nobody waits for.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

How do you decide between scaling the database and changing the application?

Answer

I decide by measuring where the time goes, then asking whether the work is necessary, correctly shaped, and correctly timed. My rule: if the database is doing work the application could avoid or batch, fix the application first. If the workload is irreducible and the database is already efficient, scale. I bring numbers: query counts per request, p99 latency, CPU/IO saturation, and cost per month.

Worked example (hypothetical but realistic). An order history page gets 1,000 requests/min. Each request does 1 query for orders, then N+1 queries for line items (average 20 orders per page, so 21 queries). Total 21,000 queries/min. p99 latency is 850 ms. Database CPU is at 70%. Scaling to a bigger instance costs $X/month and reduces p99 to 400 ms. Changing to a single JOIN query reduces to 1,000 queries/min, p99 to 120 ms, and CPU to 15%. That's a clear application win.

Python
# Python 3.11, SQLite 3.39
import sqlite3
conn = sqlite3.connect('shop.db')
cur = conn.cursor()

# N+1: 1 + N queries
cur.execute("SELECT id, user_id FROM orders WHERE user_id = ?", (user_id,))
orders = cur.fetchall()
for order in orders:
    cur.execute("SELECT * FROM order_items WHERE order_id = ?", (order[0],))
    items = cur.fetchall()

# Single query with JOIN
cur.execute("""
    SELECT o.id, o.user_id, oi.product_id, oi.quantity
    FROM orders o
    JOIN order_items oi ON oi.order_id = o.id
    WHERE o.user_id = ?
""", (user_id,))
rows = cur.fetchall()

Trace: for a user with 20 orders, N+1 issues 21 queries; JOIN issues 1 query. If each query takes 1 ms round-trip, N+1 takes 21 ms plus application overhead; JOIN takes 1 ms. At 1,000 requests/min, that's 21,000 queries/min vs 1,000 queries/min: a 21x reduction.

Decision signals. Enable pg_stat_statements and find the top queries by total time. If the top query has high calls and low mean_exec_time (e.g., 0.5 ms), it's an N+1 or chatty pattern: fix the application. If it has low calls and high mean_exec_time (e.g., 200 ms), it's a single expensive query: consider indexing, caching, or scaling. EXPLAIN (ANALYZE, BUFFERS) shows whether the query is doing sequential scans.

SignalApplication changeDatabase scaling
pg_stat_statements top queryHigh calls, low mean timeLow calls, high mean time
CPULow after batchingHigh even after batching
Write volumeCan be reduced (e.g., last-seen timestamp)Irreducible (e.g., financial ledger)
Latency budgetCan tolerate staleness (e.g., 5 min TTL)Needs strong consistency
CostOne-off engineering costRecurring instance cost

Failure modes. Buying time and forgetting the fix. Scaling read replicas for write-heavy workloads: replicas don't help writes. Caching without invalidation: Redis default maxmemory-policy is noeviction, so a cache that fills up will start returning errors instead of evicting; set allkeys-lru or volatile-lru. Background jobs without idempotency. Connection pool exhaustion: HikariCP default maximumPoolSize is 10; PostgreSQL default max_connections is 100. If you have 20 app instances, you can exhaust the database connections. Detect with connection wait time metrics.

Leadership framing. Infrastructure spend is a recurring cost that grows; application efficiency is a one-off cost that compounds in the other direction.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-22

What does it mean that scaling steps trade something away, and how do you decide what to trade?

Answer

The 60-second answer. Every step down the scaling ladder buys one resource (read QPS, write QPS, dataset size) by spending another: freshness, transactional scope, query flexibility, or money. Deciding what to trade means naming the invariant the domain cannot lose, then picking the cheapest step that does not touch it. A payments ledger cannot spend atomicity across accounts, so sharding it requires each transaction to fit inside one shard. A content site can spend freshness freely, so caching and replicas are nearly free there. Same problem, different right answer.

The ladder, with the knob that sets the price.

StepBuysSpendsConcrete knobReversible
Cacheread QPS, p99freshnessRedis maxmemory-policy, TTLyes: delete keys
Read replicaread QPSread-your-writespg_stat_replication.replay_lag; MySQL 8.0.22+ Seconds_Behind_Sourceyes
Verticalcapacity, no code changemoney, resize downtimeinstance class; resize needs a reboot (Multi-AZ failover ~60–120 s)yes
Partitioningscan sizequery flexibilitypartition key must appear in every unique indexmostly
Shardingwrite QPScross-shard transactions and joinsshard key choiceno
Denormalisationread latencywrite amplificationN physical writes per logical writehard
Asyncthroughput, smoothingimmediacySQS visibility timeout, default 30 s, max 12 hyes

Two pieces of arithmetic that make the cost concrete.

Fan-out tail. Hypothetical: 16 shards, each with p99 = 20 ms, and 1% of single-shard queries exceed 20 ms. A query that does not filter on the shard key fans out to all 16. P(at least one shard is slow) = 1 − 0.99¹⁶ ≈ 15%. So the fan-out p99 is not 20 ms: 20 ms is now roughly the p85 of that query. That is the real price of sharding for a non-shard-key query, and a single-shard benchmark will never show it.

Consistency pricing. DynamoDB charges 1 RCU per 4 KB strongly consistent read and 0.5 RCU eventually consistent. 1,000 reads/s of a 4 KB item is 1,000 RCU strong or 500 RCU eventual: the freshness trade is a straight 2× on that line of the bill. Cassandra makes the same trade explicit: replication factor 3 with QUORUM reads and writes (2 + 2 > 3) gives read-your-writes; ONE/ONE does not.

Failure modes and how you see them.

  • Stale read after write: a user renames a profile, refreshes, sees the old name. Detect with a synthetic read-your-writes probe and an alert on replay_lag.
  • Cache stampede: a popular key expires and 1,000 concurrent misses hit the database. Detect a connection spike aligned to TTL boundaries; fix with jittered TTLs or single-flight.
  • Redis left on the default maxmemory-policy noeviction: once maxmemory is hit, writes fail with OOM command not allowed when used memory > 'maxmemory' instead of evicting. The cache becomes an outage.
  • Wrong cross-shard aggregate: a sum that misses one shard returns a plausible number. Detect by reconciling against a single-shard source of truth on a schedule.

Two selection rules. Prefer the reversible trade when benefits are close: dropping a cache is a config change, un-sharding is a migration. And prefer the trade that fails loudly: replica lag produces a bug report; a subtly wrong cross-shard sum produces a wrong number nobody notices for months.

Write it down. One line in the design doc: "Accepted: up to 2 s replica lag on the profile read path. Rejected: strong reads, because they would put the read traffic back on the primary." Without that line, the next engineer finds the staleness, files it as a defect, and either "fixes" it, restoring the capacity problem, or builds on a guarantee that was deliberately given up.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-24

What is the relationship between database scaling and availability?

Answer

They are orthogonal axes that share components. Scaling changes how much load the system absorbs; availability changes what it survives. A change can move one without the other, and the coupling is mechanical: most scaling techniques work by adding components, and every component is a new failure mode and a new dependency edge.

ChangeCapacity effectAvailability effectKnob that decides it
Read replica+ read throughput+ promotion target; − new dependency if synchronoussynchronous_standby_names, synchronous_commit
Sharding+ write throughputpartial failure, but fan-out multipliesshard count N
Cache− database load− new hard dependencyRedis maxmemory-policy (default noeviction)
Connection pooler+ multiplexing− new single point of failurePgBouncer default_pool_size 20, max_client_conn 100
Vertical+ per-node capacityroughly neutral, larger blast radiusinstance size

Sharding cuts both ways, and the arithmetic says which. Take per-shard availability of 99.9% (8.8 h/yr). A shard-local query sees 99.9%. A query that touches all 16 shards sees 0.999^16 ≈ 98.4%, about 139 h/yr. Sharding raises availability for shard-local work and lowers it for fan-out work; which dominates is a property of your query mix, not of sharding.

A cache is a capacity measure that becomes a dependency. At a 95% hit rate the database is sized for 5% of query volume, so losing the cache presents it with 20× its provisioned load. Redis's default maxmemory-policy is noeviction, so a full cache returns OOM errors on writes instead of evicting: the cache fails while the database is still cold. The remedy is sizing the database to survive a cold cache, or degrading deliberately (serve stale, shed load) rather than falling through.

Synchronous replication trades availability for durability. PostgreSQL defaults to asynchronous streaming replication; synchronous_commit defaults to on but only engages when synchronous_standby_names is non-empty. Turn it on and every commit waits for a standby round trip: a 1 ms local commit becomes at least 2 ms with a same-AZ standby, 30–70 ms cross-region. Availability drops from one node's to the series combination: 99.9% × 99.9% = 99.8%, so 8.8 h/yr becomes 17.5 h/yr, unless the system can fall back to async.

The pooler is on the critical path for every query. PgBouncer defaults to default_pool_size 20 and max_client_conn 100; 1000 application connections multiplex onto 20 server connections against PostgreSQL's default max_connections of 100. It was added to stop connection exhaustion and is now a single point of failure for all of them.

Detection, concretely: cache loss shows as pg_stat_activity climbing to max_connections and clients getting FATAL: sorry, too many clients already; a stalled synchronous standby shows in pg_stat_replication.sync_state and as a step in the commit-latency histogram; fan-out damage shows as p99 and error rate on cross-shard queries only, while shard-local traffic looks healthy.

The design question is to list the failures you must survive and the capacity you need, answer them separately, then reconcile. The failure mode to watch is a capacity measure that quietly becomes a single point of failure: the cache everything depends on, the pooler every connection goes through, the one primary all writes require.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

How would you plan database capacity for a product expecting rapid growth?

Answer

What I'd say first. Three clarifications before any number: what's growing (write volume, read volume, or stored bytes. They scale differently), what the SLA is, and what the data model looks like. A write-heavy event stream and a read-heavy catalog need different plans. Then I'd instrument before I build, because you cannot plan capacity you cannot measure.

Trend four signals, not one. Data volume alone misses the failure that actually pages you.

signalwhereaction threshold
stored bytespg_database_size() sampled daily>70% of provisioned disk
query time by totalpg_stat_statements by total_exec_timetop query >20% of total DB time
connectionspg_stat_activity vs max_connections>80% of the pool
replication lagpg_stat_replication.replay_lag>5 s sustained

The top-queries query is the one people skip and the one that pays:

SQL
-- Postgres 13+; total_exec_time replaced total_time in PG13
SELECT queryid, calls,
       round(total_exec_time::numeric) AS total_ms,
       round(mean_exec_time::numeric, 2) AS mean_ms
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;

Turn the trend into a runway. This is the whole point: capacity stops being anxiety and becomes a date.

Worked example (hypothetical, but the arithmetic is the method): primary on a 2 TB gp3 volume, 400 GB used, growing 12 GB/day. Usable at 80% = 1.6 TB. Headroom = 1.2 TB. 1200 / 12 = 100 days ≈ 3.3 months. That's the date I put in the ticket. If it's under one quarter, partitioning or a resize gets scheduled now, not when the disk alarm fires.

Decide retention early. It's a business and legal conversation that takes weeks, and it decides whether partitioning is even worth it. A common shape: 90 days hot in Postgres, 12 months in a monthly-partitioned table, older to S3 as Parquet. Partitioning is far cheaper to introduce before the table is huge.

Pick a shard key you're not using yet. High cardinality, even distribution: tenant_id or user_id. You don't shard now; you just avoid a key that can never be one.

Build the cheap things now. PgBouncer in transaction mode (pool_size ~ 2–4× vCPU) so 500 app threads don't open 5000 connections; a read replica; monthly partitioning on the big table; Redis in front of hot reads. Each is low cost now and painful to retrofit under an incident.

Don't build the expensive things. No sharding, no CQRS, no distributed store until the measurement demands it. The cost is immediate and permanent; the benefit is speculative.

Name the failure modes. Connection exhaustion: Postgres degrades hard past a few hundred backends, and the symptom is timeouts, not a clean error. Autovacuum falling behind on a high-write table: bloat grows the disk faster than the data does; watch n_dead_tup in pg_stat_user_tables. Replica lag under a write burst: reads go stale; that's why lag is on the dashboard.

Rehearse the next step. Know what you'd do at the next threshold and roughly how long it takes. The goal isn't to be ready for 100× today; it's to never be surprised and never be trapped.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

How would you explain a scaling decision and its cost to non-technical stakeholders?

Answer

In terms of what changes for users and for the business, with options rather than a verdict.

I would state the problem concretely: 'the database is at about 80% of what this machine can do. At current growth we hit the limit in roughly four months, and past that the site gets slower for everyone during peak hours.' That gives a what, a when, and a consequence, which is what they need to prioritise it.

Then the options with their real costs:

'A bigger machine. Roughly £X more per month, takes a day, changes nothing else. Buys about eighteen months at current growth.'

'Engineering work to make the current queries more efficient. Roughly two weeks, no ongoing cost, likely buys a similar amount, and it makes the bigger machine last longer if we do it too.'

'Splitting the database across several machines. Two to three months, significant ongoing complexity, and some features become harder to build afterwards. Necessary eventually if growth continues at this rate, but not yet.'

Then a recommendation, because leaving them to choose between things they cannot evaluate is not helpful: 'I recommend the bigger machine now to remove the immediate risk, and the engineering work next quarter so we are not back here in eighteen months.'

The part I would make sure they understand, because it is genuinely their decision: any option that trades freshness, showing data that is a minute old rather than instant, makes several of these much cheaper. That is a product decision, not a technical one, and asking it explicitly often unlocks the cheapest path.

What I would avoid is technical detail they cannot act on, and false precision: 'roughly four months' is honest; 'seventeen weeks' is not, and being caught being over-precise costs credibility on the next estimate.

And I would be explicit about what happens if we do nothing, because that is the option that gets chosen by default when it is not stated.

Curated: · Written: · Reviewed:

Difficulty: Medium