Medium system-design fundamentals

Your database is getting slow as traffic grows. What do you do, in what order?

The 30 second answer

I climb a ladder from cheapest to most expensive. First find the slow queries and fix them with indexes and better queries, then add connection pooling and caching, then move reads to replicas, then scale the machine up. Only when writes or data size outgrow one primary do I partition, and sharding is the last step because it changes the application.

Could you say this in an interview?

The ladder.

  1. Measure. Find the top queries by total time, then read their plans. PostgreSQL's EXPLAIN shows the plan and EXPLAIN ANALYZE runs it and reports real row counts and timings, which tells you whether you have a missing index or a bad estimate.
  2. Indexes and query fixes. PostgreSQL's docs describe indexes as the common way to make the server find rows much faster than without them, and also note that they add overhead to the whole system, so index for the queries you actually run. Remove N+1 queries and SELECT * on wide tables.
  3. Connection pooling. Many short connections cost a lot of server memory and CPU. A pooler such as PgBouncer, or the pool in your application, keeps the number of server connections bounded.
  4. Caching. Put hot, read-mostly data in a cache (see the cache question above), and cache whole responses at the CDN where they are public.
  5. Read replicas. Send reporting and read-heavy traffic to replicas; keep read-after-write paths on the primary because replicas such as RDS read replicas are asynchronous.
  6. Vertical scaling. A bigger instance is often the cheapest step in engineering time; it has a ceiling and keeps one point of failure.
  7. Partitioning on one server. Split big tables by time or key so queries and maintenance touch less data, and old data can be detached.
  8. Sharding or a different store. When write volume or data size outgrow one primary, shard, or move a specific workload to a store built for it. This is the most expensive step.

How I explain the order. Each step costs more and changes more code than the one before it. Steps 1 to 4 often remove the problem entirely, and the estimate tells you whether the remaining load fits one primary. Writes are the hard part: caches and replicas only help reads.

Common mistakes interviewers listen for.

  • Jumping to "shard it" or "switch to NoSQL" without a query plan.
  • Adding an index for every column, which slows writes.
  • Adding replicas to fix a write bottleneck.

Deeper PostgreSQL query work is on PostgreSQL query writing and optimization, and switching databases is discussed in When to switch databases.

Sources (5)
  1. PostgreSQL: Using EXPLAINpostgresql.org
  2. PostgreSQL: Indexespostgresql.org
  3. PgBouncer: lightweight connection pooler for PostgreSQLpgbouncer.org
  4. AWS: Working with DB instance read replicasdocs.aws.amazon.com
  5. PostgreSQL: Table partitioningpostgresql.org