Database Performance Tuning and Scaling Questions
System-level performance work beyond a single query: configuration and resource tuning, capacity planning, handling large data volumes, and scaling read and write throughput. Covers identifying bottlenecks, growth management, the vertical-versus-horizontal scaling decision, materialized views for expensive queries, and maintenance work such as vacuuming, index rebuilds, bulk loads, and safe schema changes on large tables. Tests whether a candidate can keep a database healthy as load grows.
You need to cut p95 read latency for a global user base from 120 milliseconds to under 40 milliseconds at 50,000 reads per second. Design a read-scaling architecture layering edge or CDN caching, in-memory caching, and read replicas. How would you decide what to cache and for how long, using a pattern like stale-while-revalidate, and what consistency guarantees would you be willing to give up to hit that target?
Sample Answer
Direct answer
Layer three caches in front of the primary: an edge / content delivery network (CDN) tier for data that is the same for everyone or close to it, a regional in-memory cache (Redis or similar) for personalized or fast-changing data, and regional read replicas as the fallback source once both caches miss. Whether this works comes down to one number: because a request from a distant user has to cross real physical distance to reach a single origin region, a cache miss alone can already exceed a 40 millisecond budget, so hitting p95 (95th-percentile) latency under 40 milliseconds at 50,000 reads per second requires the combined edge-plus-in-memory cache hit ratio to sit at roughly 95% or higher. The guarantee you give up to get there is strong, always-fresh reads for everyone except the user who just wrote the data: cached and replica-served reads become eventually consistent, bounded by a stated staleness window per data type, while the acting user's own write is routed around the cache so they never see their own action appear to have failed.
Structured elaboration
Why distance alone rules out an origin-only design
Signal propagation through fiber-optic cable travels at roughly two-thirds the speed of light in vacuum. That is a physical limit, not a database tuning problem: a round trip between two points thousands of kilometers apart costs real milliseconds no query optimization can remove. A single-origin-region architecture, however well-tuned the database is, cannot put a p95 under 40 milliseconds for users on the other side of the planet. That is the architectural reason edge and regional caching are not optional here, they are the only way to physically shorten the path for most requests.
Classifying data to decide what goes in which tier
| Data shape | Cache tier | Reasoning |
|---|---|---|
| Same for (almost) every user, changes rarely (catalog, public profile pages, static configuration) | Edge / CDN, long time-to-live (TTL) | Few distinct cache keys shared by many users means very high hit ratios are achievable at the point closest to the user |
| Personalized or computed per-user (a feed, an aggregate, a leaderboard) | Regional in-memory cache, shorter TTL | Too many distinct keys for edge caching to pay off; centralizing in one regional cache still avoids hitting the database on every read and is easier to invalidate correctly |
| The user's own just-written data | No cache; routed to the primary or a replica confirmed to have absorbed the write | This is the one case where staleness is not acceptable: a user should never read back something that looks like their own write silently failed |
| Anything that must be correct at the instant of read (for example, a balance immediately before authorizing a debit) | No cache, always the primary | An explicit, named exception, not something quietly caught by a general TTL |
Stale-while-revalidate (SWR) and why it, not active invalidation, should carry most of the load
Under stale-while-revalidate, a cache serves the value it already has immediately, even if its soft freshness window has passed, while kicking off a background refresh from the layer below (an in-memory cache refreshing from a replica, or an edge node refreshing from origin). The next request after the refresh completes gets the new value. The user never waits on the refresh. Compare that to actively pushing invalidation messages to every edge node whenever underlying data changes: that turns cache freshness into its own distributed consistency problem across every point of presence (PoP) in the network, and for most read-mostly data it is slower and more fragile than simply letting a short TTL expire. Reserve active invalidation for the small set of high-value keys where even a short TTL window of staleness is unacceptable (for example, a price that just changed).
Read replica routing and the freshness floor they set
Give each major region its own read replica, route reads to the nearest one, and continuously track each replica's replication lag (how far behind the primary it is). If a replica's lag exceeds the staleness budget promised by the cache tiers above it, fail toward the primary for that traffic rather than silently serving data staler than what was promised. Replication lag is also the floor beneath every promise this design makes: no cache TTL should be tighter than what the replica feeding it can actually guarantee.
Worked example
Two numbers actually gate this design: how close a hit has to be to beat 40 milliseconds, and how far a miss is from a distant origin region. The second one is physics, not opinion, so it is worth computing rather than assuming.
C_VACUUM = 299_792.458 # km/s, speed of light in vacuum
FIBER_INDEX = 1.47 # typical single-mode fiber refractive index
v_fiber = C_VACUUM / FIBER_INDEX # km/s, signal speed in fiber
routes_km = {
"cross-country (US east-west)": 4200,
"cross-continent (US-Europe)": 6000,
"antipodal (US-Singapore)": 15300,
}
for name, km in routes_km.items():
rtt_ms = 2 * km / v_fiber * 1000 # round trip: there and back
print(f"{name}: {rtt_ms:.1f} ms of propagation delay alone")
# p95 sizing: if a hit is comfortably under 40ms and a miss stays near today's
# 120ms baseline (the same WAN + database round trip that produced it), then
# for the 95th-percentile request to land under 40ms, at most 5% of requests
# may miss.
miss_budget_pct = 5.0
print(f"required combined edge+in-memory hit ratio >= {100 - miss_budget_pct:.0f}%")
read_qps = 50_000
target_hit_ratio = 0.97 # 2 points of margin above the 95% floor
miss_qps = read_qps * (1 - target_hit_ratio)
regions = 5
print(f"miss traffic reaching replicas: {miss_qps:,.0f} reads/sec, "
f"~{miss_qps/regions:,.0f} reads/sec per region across {regions} regions")
write_tps = 5_000
print(f"write target: {write_tps:,} TPS (transactions per second), unaffected by "
f"any of the caching above; it lands entirely on the primary")
Output (executed):
cross-country (US east-west): 41.2 ms of propagation delay alone
cross-continent (US-Europe): 58.8 ms of propagation delay alone
antipodal (US-Singapore): 150.0 ms of propagation delay alone
required combined edge+in-memory hit ratio >= 95%
miss traffic reaching replicas: 1,500 reads/sec, ~300 reads/sec per region across 5 regions
write target: 5,000 TPS (transactions per second), unaffected by any of the caching above; it lands entirely on the primary
Two things fall out of this. First, cross-continent and antipodal round trips already exceed 40 milliseconds on propagation delay alone, before a single database query runs, which is why no amount of origin-side tuning closes this gap for a global user base; the cache hit ratio has to do essentially all the work. Second, at a 97% hit ratio the replica tier only has to absorb about 300 reads per second per region, comfortably inside what a single well-indexed read replica handles, so the hard part of this design is the cache hit ratio, not replica capacity.
The companion write target matters here because it sets the freshness floor discussed above: 5,000 writes per second all land on the primary (caching and read replicas do nothing for writes), and the primary has to both sustain that rate and ship its write-ahead log (WAL, the durable record of every change) to every regional replica fast enough that replication lag stays inside whatever staleness window the cache tiers are promising. If write volume grows further, replication lag grows with it, and that is the point at which every cache TTL and every "how stale can a replica read be" assumption in this design needs to be re-validated, not treated as a one-time decision.
flowchart TD
U[Global user request] --> E["Edge / CDN PoP\ncache-only, long TTL"]
E -- hit --> RU[Response]
E -- miss --> R["Regional in-memory cache\nRedis, short TTL, SWR"]
R -- hit --> RU
R -- miss --> RR[Regional read replica]
RR -- fresh enough --> RU
RR -- lag over budget --> P[Primary]
P --> RU
W[Write / user action] --> P
P -- WAL replication --> RR
P -- fresh write --> OW["Read-your-own-write\nbypass cache, route to primary"]
Trade-offs & pitfalls
- Cache stampede on expiry. When a hot key's TTL lapses, many concurrent requests can all miss at once and hammer the layer below simultaneously. Stale-while-revalidate already helps (it keeps serving the old value during refresh), but pair it with request coalescing (only one in-flight refresh per key, other requests wait on that result) and TTL jitter (randomizing expiry slightly so many keys do not expire in the same instant).
- Over-caching mutable, high-stakes data. The temptation to cache everything for uniform simplicity is real; resist it for anything where staleness has a real cost (money, inventory at the moment of purchase, access control decisions). Naming the exceptions explicitly, as this design does, is safer than a blanket policy with silent edge cases.
- Edge caching does not help personalized data. If a page or response is unique per user, the edge tier will have as many cache keys as users and its hit ratio collapses; that traffic belongs in the regional in-memory tier, not forced into the edge tier for architectural tidiness.
- The 40ms budget math here is a simplified two-class model (hit versus miss), used to size the required hit ratio, not a promise about the real latency distribution. Validate the actual design against measured percentile telemetry once it is live; a real cache miss is not always exactly 120 milliseconds, and a real hit is not always a few milliseconds.
- Read-scaling work does not touch the write path. If the write target grows past 5,000 TPS, that is a primary-capacity and replication-fan-out problem, a different constraint than anything cache tiers or read replicas solve, and it should be sized and reasoned about on its own terms.
You manage a transactions table with 5 years of history, about 3 billion rows, where most queries target the last 90 days and older data is only queried occasionally for audits. Propose a partitioning and retention strategy: how would you choose the partition key and size, archive or drop old data, and migrate the existing table into this scheme with minimal disruption?
Sample Answer
Direct answer
Choose the partition key to match how the table is actually queried, here almost every query filters by recency, so range-partition by the timestamp column at a grain that keeps each partition small enough to manage but large enough to avoid creating thousands of tiny ones; monthly is the usual sweet spot for a five-year, three-billion-row table. Archive or drop whole partitions instead of running row-by-row deletes, since dropping a partition is a fast metadata operation while a row-by-row delete on billions of rows generates enormous write-ahead log volume and dead-tuple bloat (space left behind by deleted or updated rows that has not yet been reclaimed, making the table physically bigger than its live data). Migrate the existing table by building the new partitioned table alongside the old one and backfilling in the background, so the live table keeps serving traffic the whole time, not through an in-place conversion that locks it.
How to think about it
Choosing the key and grain. Range-partition on the timestamp column the 90-day query filter already uses. Monthly partitions balance partition count (five years is 60 partitions, manageable for the planner and for scheduled maintenance) against partition size (three billion rows over 60 months is roughly 50 million rows per partition, still comfortably indexable). Daily partitioning would create over 1,800 partitions, too many for most planners and tooling to manage cleanly at this volume; yearly would put roughly 600 million rows in one partition, defeating the point of pruning for a 90-day query window.
Partition pruning. The planner only scans the partition or partitions that overlap the query's filter range once the filter is on the partition key. This is what keeps hot-data queries fast as history grows unbounded: query cost stops scaling with total table size and starts scaling with the size of the relevant partitions only.
Archive versus drop. For a 90-day-hot, occasional-audit pattern, the middle path is usually right: keep the last few months as normal query-serving partitions, then either detach older ones and move them to cheaper, compressed storage for audit access, or drop them entirely if the retention policy genuinely allows deletion after a fixed window. Detach-and-archive preserves audit access at lower storage cost; drop is only correct once there is no compliance or audit requirement needing that data queryable in the live database.
Storage-cost reduction beyond partitioning itself. Compress older partitions once they stop being written to, use narrower column types where the schema is wasteful (an eight-byte integer key when the range never approaches a four-byte integer's ceiling, an arbitrary-precision numeric where a fixed-precision type would do), and tier cold, detached partitions to cheaper storage classes.
Migration with minimal disruption. Create the new partitioned table empty alongside the old one, backfill historical data in batches so no single giant transaction or lock is ever held, keep the old table receiving live writes (through a trigger or dual-write) during the backfill, cut reads over once the backfill has caught up to the present, then cut writes over and retire the old table. This is the same build-in-parallel, backfill, cut-over, keep-a-rollback-path shape any large schema migration should follow.
A named implementation technique, verified against Microsoft's current documentation: SQL Server's ALTER TABLE source SWITCH PARTITION n TO target [PARTITION m] reassigns a whole partition's data to another table or partition as a metadata-only operation, no rows are physically moved. This is the concrete mechanism behind a daily sliding-window purge: switch the oldest partition out to a staging table, then archive or drop that staging table, instead of running a DELETE against the live partitioned table. It requires the source and target to be in the same filegroup, matching aligned indexes, and, the detail that most often trips people up, the target partition must already exist and be empty before the switch.
Worked example
A real, pinned demonstration: a 90,000-row transactions table range-partitioned by month into three partitions (July, August, September 2026). EXPLAIN ANALYZE on a two-week query window shows the planner touching only the September partition:
Aggregate
-> Seq Scan on transactions_2026_09 transactions
Filter: (created_at >= '2026-09-01' AND created_at < '2026-09-15')
Execution Time: 2.499 ms
Note the plan names only transactions_2026_09, the other two partitions are never touched, pruning working exactly as intended. Dropping the oldest partition for retention:
DROP TABLE transactions_2026_07;
-- Time: 14.026 ms
That single statement removed roughly 30,000 rows from the logical table in 14 milliseconds. A row-by-row DELETE over that same volume would instead generate write-ahead log entries and dead tuples proportional to every row deleted, work that a metadata-only partition drop skips entirely.
Trade-offs and pitfalls
Picking too fine a grain, daily, creates planner and tooling overhead that outweighs the pruning benefit at this scale. A dropped partition's data is genuinely gone; always archive first if there is any chance of a later audit need, a drop is a one-way door. Migrating in place with a single giant rewrite instead of the parallel build-and-backfill approach risks locking the live table for the whole migration. Indexes on a partitioned table generally need to be created per partition, forgetting this leaves new partitions unindexed and silently slow compared to the old ones.
Why does a database need connection pooling at scale, and what breaks without one? Explain how pool size affects latency and throughput, what a 'connection storm' is and how you would mitigate one, and give rules of thumb for sizing a pool for a service under high concurrency.
Sample Answer
Direct answer
Every open connection to a relational database consumes a real operating-system process (or thread) and memory on the server, and there is a hard configured cap on how many can exist at once. Without pooling, each request opening its own new connection pays a TCP handshake plus authentication on every single request, and under any real concurrency the application either overwhelms that cap or spends most of its time on connection setup instead of doing work. A connection pool holds a small set of already-open, already-authenticated connections and hands them out to callers, so the expensive setup happens once and the database only ever sees a bounded number of clients.
How to think about it
What actually breaks without one. In Postgres, each new connection is a forked backend process with real per-process memory overhead. A burst of naive per-request connections either queues at the accept layer or gets rejected outright once the server's connection cap is hit, a hard failure, not a graceful slowdown.
What a connection storm is. A spike where many clients open new connections at once, faster than they close. Two classic triggers: a deploy or autoscaling event starting many application instances simultaneously, each opening its own pool, and a downstream slowdown that makes queries take longer, so callers pile up holding connections instead of releasing them, which looks like "we need more connections" but is really "connections are being held too long." Mitigation is a pooling proxy in front of the database (PgBouncer for Postgres, or a managed equivalent) that multiplexes many client-side connections onto a much smaller, bounded set of real database connections, and queues or sheds load once that bound is hit, rather than letting the database itself absorb the storm.
Session vs transaction pooling, verified against PgBouncer's own current documentation:
| Pool mode | Server connection released | What still works |
|---|---|---|
| Session (default) | Only when the client disconnects | Everything: prepared statements, temp tables, SET, advisory locks. Almost no multiplexing benefit, one client ties up one real connection for its whole session |
| Transaction | As soon as each transaction finishes | Many idle or slow clients share a small pool of real connections, the mode that actually absorbs a storm. Session state is not guaranteed to survive between transactions: prepared statements from one transaction may run on a different physical connection next time, SET may not persist, advisory locks and temp state can behave unexpectedly |
| Statement | After each individual query | Multi-statement transactions are disallowed outright; rare, used only for simple single-statement high-fanout clients |
A model-serving endpoint issuing one query per inference request is exactly the profile transaction pooling is built for: short, independent, no session state needed. An extract-transform-load (ETL) job that opens a session, sets session-level parameters once (like a statement timeout or search path), and then runs many statements over minutes needs session pooling, or it has to re-issue those SET statements inside every transaction under transaction pooling.
Sizing rules of thumb. This is not "as many connections as application threads." The database has a fixed number of CPU cores; once queries running concurrently equal that core count, more connections add queueing and per-connection memory overhead instead of throughput. A widely used starting formula, from HikariCP's own published connection-pool sizing guidance:
connections=(core_count×2)+effective_spindle_countwhere effective spindle count accounts for genuine disk-wait headroom, usually 0 or small on modern SSD-backed cloud storage, since there is little seek-time blocking left to hide behind extra connections. That same guidance reports Postgres throughput plateauing around 50 connections on typical hardware: past a fairly small number, more connections make things worse, not better. Size the pool small, and size it per service instance: if 20 application pods target one database and the formula says 20 connections total, each pod's local pool needs roughly one, not 20, and this arithmetic has to be redone separately for every distinct target a service talks to, a primary and its replicas are separate budgets, not one shared number.
Worked example
A real, reproducible demonstration of what exhaustion actually looks like, executed against a live PostgreSQL 16 instance: Postgres started with max_connections = 8 and the default superuser_reserved_connections = 3, a non-superuser application role connecting (the realistic case, since a real service authenticates as its own role, not as the database superuser), five long-running connections opened concurrently to simulate sustained load, then one more connection attempted:
$ psql -U app_user -c "SELECT 1;"
psql: error: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432"
failed: FATAL: remaining connection slots are reserved for roles with the SUPERUSER attribute
That is the database's own real error text for this exact setup, not a simulated one, and it is more specific than a blanket "too many clients": a non-superuser role can use at most max_connections minus the reserved pool, five connections here, so the sixth fails immediately with this message, before the server's raw eight-connection cap is ever reached. Only once every slot, including the three reserved ones, is actually exhausted, for example by superuser connections filling all eight, does the server instead report the more generic FATAL: sorry, too many clients already. The two messages tell you different things: the reserved-connections message means an application workload hit its own quota with the reserved pool still intact, while the generic message means the server is genuinely out of slots for everyone, including superuser access needed to intervene. This is exactly the failure a pooling proxy prevents, by queueing or shedding a storm at the proxy layer instead of letting every caller hit either cap directly.
Trade-offs and pitfalls
A pool sized too large can crash the database under its own weight (memory, context switching) instead of protecting it. A pool sized too small moves the real bottleneck from "the database is slow" to "requests are queued waiting for a pool slot," which shows up as application-level latency, not database-level slow queries, a genuinely different diagnostic picture. Switching pool modes without checking a client driver's own assumptions is the single most common cause of a transaction-pooling outage, always verify the driver's guidance before changing modes. Pooling solves the CPU and memory overhead of connection setup; it does nothing for a genuinely slow query still holding a connection for its full duration, making the pool bigger to compensate just hides that problem for longer.
A database is showing high write latency and you suspect it is I/O-bound, but you are not certain. How would you collect evidence to distinguish a CPU-, memory-, or I/O-bound bottleneck, and what remediation would you consider for each, for example filesystem or I/O-scheduler tuning, batching writes, or reconsidering the storage engine?
Sample Answer
Direct answer
Distinguish CPU-, memory-, or I/O-bound by looking at where time is actually being spent, not by guessing from symptoms. The database's own stats views, buffer cache hit ratio, pg_stat_io, and wait events in pg_stat_activity, together with operating-system tools, triangulate which resource is actually saturated. High write latency specifically points first at input and output (I/O), because a write, unlike a read, always eventually has to reach durable storage through the write-ahead log; a write-latency problem that is not I/O-bound is usually lock contention or unexpected CPU cost (an expensive trigger or constraint check) rather than the storage layer itself.
How to think about it
CPU-bound signals. Active backends in pg_stat_activity show wait_event_type mostly null, meaning they are actually running, not waiting. Operating-system tools show high user CPU with load average tracking the core count. EXPLAIN ANALYZE (Postgres's command for showing a query's actual execution plan and per-step timing) shows expensive in-memory work, sorts, hash joins, function evaluation, rather than I/O waits. Remediation: query and index tuning to reduce work per row, cutting per-row trigger or function overhead, and only as a last resort, more or faster cores.
Memory-bound signals. Buffer cache hit ratio (blks_hit over blks_hit plus blks_read) trending down as the working set outgrows available memory. Operating-system level page-cache thrashing, swap activity specifically, is a hard memory signal distinct from a buffer-cache one. Remediation: more memory or a larger buffer cache, or shrinking the working set through better indexing or partitioning so a given query touches less resident data at once.
I/O-bound signals. wait_event_type = 'IO' on active backends. pg_stat_io showing nonzero read and write time on the relevant backend type. pg_stat_bgwriter.buffers_backend climbing relative to buffers_checkpoint and buffers_clean, a strong I/O-bound write signal specifically: it means backend processes are being forced to write out dirty buffers themselves because the checkpointer and background writer are not keeping up, adding that write's full latency directly onto the foreground query instead of it happening asynchronously. Operating-system level: high device utilization and growing queue depth.
Worked example
Real pg_stat_io rows from a running instance, illustrating the shape of this evidence (columns: backend type, object, I/O context, reads, writes, extends):
backend_type | object | context | reads | writes | extends
autovacuum worker | relation | normal | 267 | 0 | 29
checkpointer | relation | normal | | 39 |
client backend | relation | normal | 738 | 0 | 2659
And the real pg_stat_bgwriter snapshot from the same instance: checkpoints_timed=0, checkpoints_req=4, buffers_checkpoint=1989, buffers_clean=0, buffers_backend=2854. Backend-driven writes (2854) exceeding checkpointer-driven writes (1989) here is exactly the I/O-bound-write pattern described above, backends are doing more of the dirty-buffer writing than the checkpointer is. On a sustained production workload showing this same ratio, that translates directly into elevated write latency; this demo's numbers come from a short burst of heavy update activity in one session, not sustained load, but the metric and how to read it are the real evidence to look for.
Two concrete triage patterns worth having memorized. First, the 99th percentile (p99, the latency value slower than 99% of requests) spikes at the same time the buffer cache hit ratio drops: that combination points at memory pressure specifically, not pure I/O or CPU, the working set stopped fitting in the buffer cache, so reads that used to be free cache hits now cost a real disk read; the fix path is finding out why the working set grew, data growth, a new query pattern, a lost index, before reaching for more memory. Second, p99 latency roughly doubles specifically while a concurrent batch or extract-transform-load (ETL) job is running: this is resource contention, the batch job is competing for the same CPU, I/O, or lock budget as the transactional queries at the same time; the fix is workload isolation, a replica or separate store for the batch job, off-peak scheduling, or resource governance limiting its input/output operations per second (IOPS) and CPU share, rather than tuning the transactional queries, which may not have changed at all, only their competition for resources did.
Trade-offs and pitfalls
Jumping straight to a bigger instance without checking which resource is actually saturated wastes money on the wrong dimension, a memory-bound workload gets no benefit from more CPU cores. Trusting a single snapshot instead of a time series over the incident window cannot distinguish a brief spike from sustained saturation. Conflating a lock wait (wait_event_type = 'Lock', a concurrency problem) with an I/O wait looks similar from the outside, "the query is slow," but needs a completely different fix.
Your team runs a single relational database instance that is approaching its performance ceiling as traffic grows. Explain the difference between scaling it vertically (a bigger instance) and scaling it horizontally (multiple instances). What are the practical limits and cost implications of each, and how do they affect availability and operational complexity as the system keeps growing?
Sample Answer
Direct answer
Vertical scaling means moving the same single database instance onto bigger hardware: more vCPUs, more RAM, faster disks. Horizontal scaling means splitting the workload across multiple database instances, either read replicas for read traffic or shards for both reads and writes. Vertical buys time with almost no application changes; horizontal buys a much higher ceiling at the cost of new failure modes and a genuinely harder system to operate. For most teams the right sequence is: get everything reasonable out of a single well tuned instance first, and only take on horizontal scaling once the growth curve shows you will hit the ceiling of the largest instance your vendor sells, or once a single write bottleneck is the actual limiter, not a guess.
How to think about it
Two terms worth pinning down first. ACID (atomicity, consistency, isolation, durability) is the set of guarantees a relational database makes about each transaction. OLTP (online transaction processing) means many small read/write transactions, like placing one order. OLAP (online analytical processing) means fewer, larger queries that scan and aggregate a lot of data, like a nightly revenue report. The vertical-vs-horizontal decision plays out differently for each, covered below.
| Dimension | Vertical (bigger instance) | Horizontal (multiple instances) |
|---|---|---|
| Ceiling | Bounded by the largest instance size the vendor sells; once you are on it, vertical room is gone | Effectively open ended; add another node |
| Cost curve | Close to linear up to a commodity tier, then jumps, since the largest instance types are a scarcer SKU and carry a premium per core | Close to linear per node, plus a small and growing coordination tax (networking, cross-node consistency work) as node count rises |
| Availability | A single point of failure; a crash or maintenance window takes the database down (a standby helps, but there is still one active writer) | Failure of one node can often be isolated to a shard or absorbed by a replica, but a shared router or network becomes a new single point of failure |
| Operational complexity | Same backup/restore, same monitoring, same query patterns as always; complexity barely changes as you resize | New problems appear immediately: topology to track, routing logic, rebalancing, cross-node joins and transactions, multiple sets of logs and metrics |
| Backups | One backup job, one restore path, one pair of recovery targets (recovery point objective, how much data you can afford to lose, and recovery time objective, how long a restore can take) to reason about | Backups must be coordinated across nodes for a consistent cross-shard snapshot; restoring one shard without the others can leave data inconsistent |
| Failover (switching live traffic to a backup instance when the primary fails or needs maintenance) | Promote a standby; the connection string barely changes | Failover is per shard or per replica, and the routing layer must always know which node currently owns which key range |
| Migration effort | A resize is often close to zero application change | Introducing shards touches the data access layer, and changing a chosen shard key later is a full data migration |
Worked example
Start with the clearest pair of archetypes. A single-node, ACID-compliant financial ledger, for example a payments settlement system where every debit must match a credit inside one transaction, is the clearest case for staying vertical as long as possible: the correctness property you need, one atomic transaction across arbitrary rows, gets much harder once those rows can live on different nodes. Contrast that with a globally distributed social feed or clickstream store, where reads vastly outnumber writes and individual records rarely need cross-row transactions; sharding by user id is the natural fit from day one. That is also the concrete case for still choosing vertical scaling: any workload whose correctness depends on cross-row transactions over the whole dataset, not just a subset of it, should stay on a single node until there is no other option.
Now a growth scenario. A SaaS billing OLTP database is at 40% CPU on a 16 vCPU instance, and volume is projected to triple in 6 months. First confirm the bottleneck is real capacity, not a missing index or an undersized connection pool, since those get mistaken for "we need to shard" constantly. If the ceiling really is coming, the cost shape matters, not just the size of the number. The script below models unit economics illustratively (the dollar figure is a made-up placeholder for comparing the SHAPE of the two cost curves, not a real vendor price):
unit_cost_per_core = 10 # illustrative $/core-month at the commodity tier
premium_tier_cores = 64 # cores beyond this require premium, fewer-vendor SKUs
premium_multiplier = 2.5
def vertical_cost(total_cores):
if total_cores <= premium_tier_cores:
return total_cores * unit_cost_per_core
commodity_part = premium_tier_cores * unit_cost_per_core
premium_part = (total_cores - premium_tier_cores) * unit_cost_per_core * premium_multiplier
return commodity_part + premium_part
def horizontal_cost(total_cores, node_cores=8):
import math
n_nodes = math.ceil(total_cores / node_cores)
coordination_overhead_pct = 0.03 * (n_nodes - 1)
return n_nodes * node_cores * unit_cost_per_core * (1 + coordination_overhead_pct)
Running it prints this table (real output, this run):
total_cores vertical_$/mo horizontal_$/mo horizontal_nodes
8 80 80 1
32 320 349 4
64 640 774 8
96 1440 1277 12
128 2240 1856 16
256 5440 4941 32
Below the premium tier (64 cores here), vertical is cheaper because horizontal pays a coordination tax with no benefit. Past it, vertical's premium-SKU jump outweighs horizontal's coordination tax, and horizontal wins. The crossover point, not a fixed rule of thumb, is what should drive the decision, and it moves with your own vendor's real pricing tiers.
A gentler-growth variant worth naming: a 5 TB machine-learning training dataset growing 50% a year, with a mix of scheduled batch training runs and interactive analyst queries. A 50%-per-year slope is far gentler than the 3x-in-6-months case above, so a single well-provisioned instance can absorb years of that growth without forcing a decision at all; the batch-vs-interactive mix affects maintenance-window planning (batch tolerates a pause, interactive access does not), not the scale decision itself.
For OLAP workloads specifically, horizontal has an extra cost most people underweight: a "total revenue across all shards" query has to scatter to every shard, gather the partial results, and merge them, so its cost is bounded by the slowest shard plus a network fan-in step, and that shape is much less predictable than a single node's query planner cost. Horizontal analytics only pays off once a single node's OLAP query latency, not OLTP throughput, is the real ceiling, and that is usually solved by separating the analytical workload out to its own store rather than sharding the OLTP database itself.
Resolving the disagreement, and trade-offs and pitfalls
When a product owner wants to start sharding now and a CEO wants to just buy a bigger managed instance, treat it as a data problem, not an opinion problem. Ask for three things: the actual growth trajectory (current queries per second, QPS, and storage plus the last two quarters' real trend, not a guess), which resource is closest to its ceiling today and how far that is from the largest instance the vendor offers, and whether the write path has one genuine hot-table bottleneck sharding would relieve, versus a mostly-read workload that a replica or cache would fix more cheaply. Commit to a number from that data, for example "we are at 45% of the largest available instance's ceiling and growing 15% a month, giving roughly five to six months before a resize stops being an option." A migration plan that includes rollback: build the router or shard layer behind a feature flag, dual-write to the old and new topology during cutover, keep the pre-migration instance caught up as a fallback for a defined rollback window, and only decommission it after the new topology has run through at least one full peak cycle without incident.
The most common mistake is paying the operational complexity tax of horizontal scaling years before the ceiling actually required it. The second is assuming vertical scaling is free forever: vendors sell a finite, discrete set of instance sizes, so there is always a last resize available. The third is easy to miss entirely: as a single instance's data grows, backup and restore duration grow with it, and that is a second capacity ceiling, your recovery time objective, independent of CPU or input/output operations per second (IOPS, how many read or write operations the storage layer can do each second).
Unlock Full Question Bank
Get access to all 28 Database Performance Tuning and Scaling interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.