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.
A database is projected to grow 5x in storage and IOPS over the next 12 months. Walk through how you would build a capacity plan for it: how you would model the growth, what safety margins you would build in, how you would project cost, and what automation or alerting you would put in place so capacity never becomes an unplanned outage.
Sample Answer
Direct answer
Capacity planning is forecasting a real growth curve from actual trend data, provisioning ahead of it with a safety margin sized to how long it takes you to actually add capacity, and wiring alerts so the response is scheduled work rather than a page. For a projected 5x in 12 months, the model you pick matters more than the headline number: a smooth compound curve behaves very differently from a step change tied to a known launch, and your alert thresholds should be set from your own provisioning lead time, not a round number borrowed from a blog post.
How to think about it
Model the growth. Compound growth is the safe default without better information: solve for the monthly rate that gets you from current usage to 5x over 12 months.
(1+r)12=5so r=51/12−1. If you instead know about a specific step (a big customer signing, a feature launch), layer that as a discrete jump on top of the smooth trend rather than smoothing it away.
Safety margin sized to lead time. WARN and PAGE thresholds should not be arbitrary round numbers. WARN needs to fire early enough that the provisioning action (a resize request, an approval, the resize itself) finishes before usage reaches PAGE. If it cannot, lower WARN, do not accept the risk.
Cost projection. Project the same curve onto the billing metric, storage dollars per GB-month, provisioned input/output operations per second (IOPS, how many read or write operations the storage layer can do each second) dollars per IOPS-month, so finance sees the number rising before the invoice does, not after.
Forecasting inputs people forget. Compute and storage do not always grow at the same rate and should be modeled separately. Scheduled scaling events (a known launch, a marketing campaign) should be layered on top of the organic trend, not baked into it. Write-ahead log (WAL, the durability log a database writes before committing a change) volume and retention grow faster than data size on write-heavy workloads, and if WAL is retained for a replication window or point-in-time recovery, that retention is its own growing volume. Backup and archival storage across your retention policy is the item most often missed entirely: a 5x growth in live data usually means 5x-or-more growth in backups, especially under a multi-year retention requirement, since old backups do not shrink just because live data changed shape.
Automation and alerting. Alert on the trend, not just the level; a sudden change in growth rate is often the earliest real signal something changed, before any threshold is crossed. Tie WARN to a ticket and runbook, PAGE to on-call, and where the platform allows it, wire the resize itself to fire automatically once a threshold is crossed and a change window is open, instead of requiring a human to notice a graph.
Scaling triggers as a companion to alerting. A trigger is a pre-agreed threshold that fires a specific scaling ACTION, not just a notification: "at 1,000,000 queries per second (QPS) sustained for 15 minutes, add a read replica" is a trigger. "Storage at 85%, page a human who decides what to do" is an alert. A complete capacity plan has both.
Worked example
Pinned inputs, reproducible on re-run:
current_storage_gb = 800
current_iops = 6000
growth_multiple = 5.0
horizon_months = 12
alert_warn_pct = 0.70
alert_page_pct = 0.85
lead_time_months = 1.0
r = growth_multiple ** (1 / horizon_months) - 1
Real output from running it:
implied monthly compound growth rate: 14.3530%
month storage_gb iops
0 800 6000
6 1789 13416
12 4000 30000
provision AT LEAST 4706 GB / 35294 IOPS so month 12's actual usage
(4000 GB / 30000 IOPS) lands at the 85% page threshold, not above it
alert thresholds: WARN at 3294 GB (70%), PAGE at 4000 GB (85%)
at this growth rate, WARN fires roughly 1.4 months before PAGE would,
against a 1-month provisioning lead time (sufficient)
The 1.4-month runway against a 1-month lead time is the check that matters: if that number had come out below the lead time, the fix is to lower WARN, not hope the resize finishes in time.
A second, QPS-based variant shows the scaling-triggers framing on a different metric: 100,000 QPS growing to 1,000,000 QPS over 18 months instead of 12. Same method, different multiple and horizon: r=101/18−1≈13.65% a month, giving 100,000 at month 0, about 215,000 at month 6, about 464,000 at month 12, and 1,000,000 at month 18 (each value is 100000×(1+r)m, computed directly from the pinned rate above). The companion trigger here would be concrete and actionable, for example "add a read replica once sustained QPS crosses 500,000 for 15 minutes," not just a dashboard threshold.
The same method scales to a longer horizon too, for example a 10x-over-3-years warehouse case (multiple 10, horizon 36 months): the growth-rate formula is unchanged, but at that horizon the WAL retention and backup and archival line items above stop being a footnote and start dominating, since backup windows and cross-region replication bandwidth become material costs at multi-terabyte, multi-year scale in a way they are not at 12 months.
Trade-offs and pitfalls
Setting WARN too close to PAGE leaves no time to act, exactly what the runway check above exists to catch. Alerting on absolute usage only, and missing rate-of-change, means the earliest real signal gets ignored until a static threshold trips. Treating compute and storage as one number hides real divergence: a read-heavy service can 5x its IOPS while barely growing on disk, and a write-heavy audit log can do the reverse. The single most common gap is forgetting backups and WAL retention, teams size the live database carefully and then get surprised when the backup bill, or the backup window and recovery time objective, breaks first.
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).
Write PostgreSQL SQL to create a materialized view summarizing daily user metrics, and show how you would refresh it concurrently without blocking readers. What are the locking implications of a concurrent refresh, and how would you schedule refreshes to minimize impact on users?
Sample Answer
Direct answer
A materialized view (a database object that stores a query's computed result as an actual table,
rather than recomputing it on every read, until it is explicitly refreshed) that summarizes daily user
metrics:
CREATE MATERIALIZED VIEW daily_user_metrics AS
SELECT
date_trunc('day', occurred_at) AS day,
user_id,
count(*) FILTER (WHERE event_type = 'login') AS logins,
count(*) FILTER (WHERE event_type = 'purchase') AS purchases,
count(*) FILTER (WHERE event_type = 'click') AS clicks
FROM user_events
GROUP BY 1, 2
WITH DATA;
-- required before CONCURRENTLY will work at all:
CREATE UNIQUE INDEX daily_user_metrics_day_user_uidx
ON daily_user_metrics (day, user_id);
REFRESH MATERIALIZED VIEW CONCURRENTLY daily_user_metrics;
A plain REFRESH MATERIALIZED VIEW rebuilds the view under an exclusive lock that blocks
every reader for the whole refresh. CONCURRENTLY instead computes the new result into a
separate temporary structure, diffs it row by row against the current contents, and
applies only what changed, so readers keep querying the old data throughout and are
never blocked, at the cost of needing a unique index to match old rows to new ones, and
doing roughly double the work.
Locking implications and the unique-index requirement
Executed against a real PostgreSQL 16 instance: attempting CONCURRENTLY without the
unique index fails immediately, before doing any work:
ERROR: cannot refresh materialized view "public.daily_user_metrics" concurrently
HINT: Create a unique index with no WHERE clause on one or more columns of the
materialized view.
The index is required because CONCURRENTLY needs a way to match each row in the newly
computed result to a row in the existing one, to know which rows are unchanged, which
changed, and which were added or removed, so it can apply a targeted diff instead of a
wholesale replace. After adding the index, the same command succeeds.
Demonstrating the actual blocking difference, on a 4.2 million row source table so
the refresh takes long enough to observe: a plain (non-concurrent) REFRESH ran for
about 2.0 seconds; a SELECT count(*) issued against the view 0.3 seconds into that
refresh, from a second session, didn't return until the refresh finished, waiting roughly
1.7 seconds for a lock it couldn't acquire. Repeating the same test with REFRESH MATERIALIZED VIEW CONCURRENTLY (about 2.7 seconds to run, more total work, as expected):
the same SELECT, issued 0.3 seconds in, returned in about 0.09 seconds, effectively
unblocked. Absolute timings will vary by hardware; the qualitative result, blocked versus
not, follows directly from Postgres's documented lock rules for each command and isn't a
timing artifact.
Scheduling refreshes to minimize impact
Match the cadence to how stale the dashboard can tolerably be, for example every 15
minutes via a scheduler like pg_cron or an external job runner, and avoid overlapping
refreshes with periods that are already I/O-sensitive: nightly backup windows, known
traffic peaks. CONCURRENTLY protects readers from being blocked, but it doesn't make
the refresh free: it's still a full recompute plus a diff, real CPU and I/O work. A view
refreshed every few seconds can become the very bottleneck it was meant to solve if the
cadence isn't matched to how long a refresh actually takes and how much the underlying
data actually changes between refreshes.
Trade-offs and pitfalls
- Forgetting the unique index and only discovering the
CONCURRENTLYrequirement when the
first scheduled refresh fails in production; add the index in the same migration that
creates the view. CONCURRENTLYcosts more work per refresh (build a full new copy, then diff) than a
plain refresh of the same data; on a view with no natural unique key, for example a
single aggregate row, you may need to add a synthetic key purely to satisfy the
constraint.CONCURRENTLYisn't lock-free, just weaker-locked; it can still conflict with, for
instance, concurrent DDL on the view, and refreshes scheduled more frequently than one
can complete will pile up behind each other.
Tell me about a time you optimized a database's performance in production. What was slow, what metrics did you start with (latency, throughput), what did you actually do (indexing, partitioning, denormalization, query rewrites, or something else), how did you validate the improvement, and what trade-offs did you accept?
Sample Answer
Direct answer
Pick one real incident with one measurable starting symptom, latency or throughput are
the usual candidates, name specifically what you tried and why each step was chosen over
the alternatives, and close with how you validated the improvement and what it cost you
elsewhere. A grab-bag of "things I've optimized over the years" reads as unfocused; one
incident, narrated end to end, reads as judgment.
A scaffold for the story
Situation. State the symptom in a measurable way: "the checkout endpoint's p95
(95th-percentile) database time was regularly exceeding 400 ms during traffic peaks" beats "the database
was slow." Latency and throughput are the two most common starting metrics, latency
because users feel it directly, throughput because it caps how much load the system can
absorb before latency degrades for everyone.
Task. What target made the incident worth fixing: an SLA being missed, a
capacity ceiling being approached, a specific complaint.
Action. Narrate three concrete techniques in the order you tried them, not a list.
The available categories a real answer usually draws from are indexing, query rewrites,
partitioning, denormalization (storing redundant, precomputed copies of data to avoid recomputing it
on every read), or connection/configuration tuning; pick whichever three
actually applied to your incident. A representative shape:
- Confirmed the query's plan with
EXPLAIN ANALYZE(the command that runs the query and
reports the real plan and timing, not an estimate) and added an index matching the
filter and sort the query actually used, verifying the plan flipped from a sequential
scan to an index scan. - Found the query was also pulling unused joined columns (
SELECT *where three columns
were used); rewrote it to select only what was needed and pushed a filter earlier in
the plan. - Noticed via the database's activity view that many requests were queued waiting for a
pooled connection, not for query execution; resized the pool and added a
statement_timeoutso one runaway query couldn't starve it.
Result. Validate against the same metric you started with, measured under
comparable load, not a different, easier one. Watch it hold up over days in production,
not just at deploy time, since delayed effects (maintenance overhead, data growth) can
erode a fix that looked clean on day one.
Trade-off accepted. A senior answer names a real cost. For example: the new index
sped up reads but added overhead to a high-insert table's write path; that was monitored
afterward and accepted as a small, budgeted latency increase on writes rather than
blocking the read fix on eliminating it entirely.
Trade-offs and pitfalls
- Listing several unrelated wins instead of one incident reads as a highlight reel, not
evidence of how you reason through a problem under pressure. - Skipping the "why this technique, in this order" reasoning makes it sound like guessing
that happened to work, which is the opposite of what the question is testing for. - Claiming an improvement without describing how it was validated, and against what
baseline, is the single most common gap; interviewers will ask. - Not naming a trade-off accepted reads as either inexperience or a curated story; real
fixes cost something somewhere.
A production service is returning intermittent errors, and metrics show its database connection pool is occasionally hitting its max. How would you diagnose whether this is caused by leaking connections, an undersized pool, slow queries holding connections too long, or a sudden traffic spike? What database and application metrics or logs would you check, and what would you do to restore availability immediately?
Sample Answer
Direct answer
Intermittent errors plus a pool occasionally hitting its max means something is consuming connections faster than the pool releases them. The fastest way to tell which of the four causes it is, a leak, an undersized pool, slow queries, or a real traffic spike, is to look at the database's own view of its connections, not just the application's pool metrics, because the database always knows exactly how many connections are open, what state each one is in, and how long it has been there.
How to think about it
Signal from pg_stat_activity | Most likely cause |
|---|---|
Many connections in idle in transaction, held for minutes, no active query | A leak: a transaction was opened and never committed or rolled back, often a missing cleanup on an exception path |
Connections active, same query text, query_start age far beyond that query's normal duration | Slow queries holding connections too long (check the plan, a missing index, or a lock wait) |
Connections active, query_start age looks normal, but total connection count has jumped | A traffic spike: legitimate concurrency growth, or a retry storm from a client that times out and reconnects |
Pool reports max reached, but pg_stat_activity shows fewer real connections than the pool's configured max | An undersized pool relative to real demand, or a pool-library bug that is not actually releasing connections back |
Metrics and logs to check: pg_stat_activity (state, query, query_start, xact_start, wait_event), specifically filtered to state = 'idle in transaction' for leaks; pg_stat_database.numbackends against the configured connection limit; application-side pool metrics (checked-out count, wait-for-a-connection time), which distinguish a database-side leak from legitimately being at capacity; and slow-query logs to catch the second case directly.
A real, pinned demonstration of the query pattern: a session holding an open transaction and a normal active query, distinguished by transaction age versus query age.
pid | state | xact_age | since_state_change | last_query
-----+--------+------------------+---------------------+-----------------------------
60 | active | 00:00:08.595573 | 00:00:08.595572 | BEGIN; SELECT * FROM orders...
Here xact_age and since_state_change matching each other on a session that began with BEGIN and has been open for seconds, on a table where that lookup should take milliseconds, is exactly the shape a leaked or stuck transaction produces; in a genuine idle-in-transaction leak, state reads idle in transaction with no query running at all, distinguishing it clearly from case two above where a query is genuinely still executing.
Parameter tuning once the cause is known, since the fix is usually a parameter, not just "add more connections." On the application pool side (HikariCP-style naming; PgBouncer, a separate pooling proxy that sits in front of Postgres, exposes equivalent settings under different names): connectionTimeout, how long a caller waits for a pool slot before failing fast, should be short enough that callers fail visibly instead of queuing invisibly and turning an incident into a mystery hang; idleTimeout and maxLifetime, recycling connections instead of holding them forever, which also self-heals a leaked-but-recycled connection faster; maxPoolSize, which should follow a sizing formula grounded in the database's own CPU core count (roughly (core_count x 2) + effective_spindle_count, with throughput on typical hardware tending to plateau around 50 total connections), not get raised reflexively mid-incident, raising it while queries are genuinely slow just moves the bottleneck onto the database's own CPU or IO. On PgBouncer specifically, server_idle_timeout and switching to transaction-mode pooling are the equivalent levers.
On a managed cloud database you do not have OS-level access, so the same triage happens entirely through the engine's own stats views plus the vendor's connection-count monitoring metric; the diagnostic logic is identical, only the access path changes.
Worked example
Immediate remediation, matched to the cause: for a leak, identify and terminate the oldest idle-in-transaction sessions with pg_terminate_backend to free slots right now while the code fix ships; for slow queries, consider pg_cancel_backend (soft) or pg_terminate_backend (hard) on the worst offenders to shed load, and lower statement_timeout at the pool or session level so future slow queries fail fast instead of pinning a connection indefinitely; for an undersized pool with genuine headroom on the database server, raise maxPoolSize a bounded amount as a stopgap, then re-run the sizing formula properly; for a real traffic spike, this is the one case where adding capacity, more replicas or a pooler in front, is the correct immediate lever rather than a code change.
Trade-offs and pitfalls
Raising the pool size as a reflexive first response conflates the four causes, and can make the slow-query case worse by adding more concurrent load onto an already saturated database. Killing sessions is a blunt immediate tool; always confirm the sessions being killed are the leaked or stuck ones, not a legitimate long-running batch job. Terminating a session mid-write can leave the application in an inconsistent retry state if it does not handle the resulting connection error gracefully, pair any forced termination with application-level retry and idempotency, not treat it as a silent fix on its own.
Unlock Full Question Bank
Get access to all 18 Database Performance Tuning and Scaling interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.