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 are running PostgreSQL with a 500GB dataset on a host with 200GB of total memory. How would you determine reasonable values for shared_buffers and work_mem? What would you monitor to know if you got it right (cache hit ratio, page read times, OS page cache usage), how would you avoid swapping, and how would you roll the change out safely in production?
Sample Answer
Direct answer
Since 500 GB doesn't fit in 200 GB of RAM, size shared_buffers to hold the actively hot
slice of the data, not the whole dataset, a widely used starting point is about 25% of
RAM (roughly 50 GiB here), leaving the rest to the operating system's own page cache,
which Postgres relies on as a second layer. Size work_mem conservatively, because it's
granted per sort or hash operation, not as one shared pool, and a single complex query
can request several of these at once, multiplied again by parallel workers. This matters most under
a typical OLTP workload (many short, concurrent transactions serving live application traffic, as
opposed to a few large analytical queries), since a high global default gets multiplied across every
concurrently active connection at once.
Reasoning through the two settings
shared_buffers: the 25% guideline is a documented starting point, not a law. Past
that point, growing it further competes with the OS page cache for the same physical
RAM (a page cached in both layers is partially wasted memory), while increasing
background-writer and checkpoint (the periodic point where Postgres flushes recently modified
in-memory pages to disk) overhead proportional to how much dirty data can
accumulate. It requires a full server restart to change, since it's allocated as shared
memory at startup, which shapes the rollout plan below.
work_mem: budgeted per sort, hash join, or merge operation. A single query with two
sorts and a hash join can request three allotments simultaneously; parallel workers each
get their own. The real ceiling isn't total_RAM / connection_count, it's headroom
divided by realistic peak concurrent operations. Setting it too high is a classic
out-of-memory or swap risk under concurrent load, not a free win for one query's sort.
Unlike shared_buffers, it can be changed per session or per role without a restart.
Rollout plan: because work_mem is a session/role-level setting, trial a higher value
on just the reporting role first, watch memory behavior under real concurrency, then
promote it to the default once validated. Because shared_buffers needs a restart, plan
a maintenance window, keep the previous value on hand, and know reverting also needs a
restart, it isn't a hot config reload either direction.
What to monitor: the buffer cache hit ratio (below), whether sorts are spilling to
disk (the query plan will say so explicitly, see below), OS-level free memory and swap
activity (a host that starts swapping is making everything slower, not just one
under-provisioned query), and page read/write timing if track_io_timing is enabled.
Avoiding swapping: never let shared_buffers + (work_mem × realistic peak concurrent operations) + other server overhead approach physical RAM. A work_mem value that's
safe at 5 concurrent users can be the thing that swaps the box at 50; set a deliberate
ceiling per role rather than raising it until one report "feels fast."
Worked example (executed on a real PostgreSQL 16 instance)
Defaults on a fresh container (small demo values, shown only to illustrate the commands,
not as a sizing recommendation for a 200 GB host):
SHOW shared_buffers; -- 128MB
SHOW work_mem; -- 4MB
SHOW effective_cache_size; -- 4GB
The concrete signal a query plan gives you when work_mem is too low, run against a
500,000-row, 87 MB table, ordering by a text column:
SET work_mem = '64kB';
EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM bench ORDER BY payload;
Sort Method: external merge Disk: 26008kB
Worker 0: Sort Method: external merge Disk: 26448kB
Worker 1: Sort Method: external merge Disk: 27024kB
SET work_mem = '64MB';
EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM bench ORDER BY payload;
Sort Method: quicksort Memory: 36981kB
Worker 0: Sort Method: quicksort Memory: 32689kB
Worker 1: Sort Method: quicksort Memory: 34701kB
"External merge" with a Disk: size means the sort didn't fit in its work_mem
allotment and spilled to disk, extra I/O the query wouldn't otherwise pay. "Quicksort"
with a Memory: size means it stayed fully in memory. That line in a plan is a direct,
observable signal that a hot query's work_mem is undersized; it's what you'd grep for
in a slow-query log, not just a number you infer from theory.
Cache hit ratio, executed against the same instance:
SELECT sum(heap_blks_hit) AS hit, sum(heap_blks_read) AS miss,
round(100.0*sum(heap_blks_hit)/nullif(sum(heap_blks_hit)+sum(heap_blks_read),0),2) AS pct
FROM pg_statio_user_tables;
-- hit=555554 miss=0 pct=100.00
The demo database fits entirely in this small container's memory, so 100% is expected
here and isn't the target for the 500 GB scenario; on the actual host you'd track this
ratio against a target you've validated for your workload, since 500 GB genuinely
cannot be fully cached in 200 GB of RAM, that gap is exactly why this sizing decision is a
real trade-off rather than a solved problem.
Trade-offs and pitfalls
- Treating "25% of RAM" as a formula rather than a starting point: a mostly-sequential-
scan analytical workload wants a smallershared_buffersand a larger
effective_cache_size(a planner hint about assumed total cache, it allocates no memory
itself) instead. - Setting
work_memglobally high enough to satisfy the worst report risks an OOM under
real peak concurrency; a lower global default plus a per-role override for the specific
workload that needs bigger sorts is the safer shape. effective_cache_sizebeing misconfigured (too low or too high) silently misleads the
query planner's cost estimates even though it allocates no memory itself, worth being
explicit about since it's a common point of confusion withshared_buffers.shared_bufferschanges need a restart to apply and to revert; roll it out in a
maintenance window with the previous value ready, not as a live config reload.
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.
Design a query-timeout policy for a reporting system serving many concurrent users. How would you decide timeout thresholds, for example by query complexity or user tier, what would you fall back to when a query times out (partial results, cached stale data), and how would you avoid silently dropping a retrieval that actually mattered?
Sample Answer
Direct answer
Tier the timeout, that is, set a different budget for different classes of caller and query, by who is asking and what they're asking. A single global number is
either too short for the legitimately expensive report or too long to protect the shared
system from a query that goes pathological. Pair every timeout with an explicit,
visible fallback, partial results or a labeled stale cache, rather than a bare error,
and log every timeout and fallback event so a request that mattered never just silently
vanishes.
Designing the policy
Setting thresholds. Classify by query complexity (a cost estimate the planner already
produces, or a simple static category like "single-table filter" versus "cross-tenant
aggregate") and by user tier (an interactive dashboard user waiting on a page load gets a
short budget; a scheduled overnight batch report gets a much longer one). Set each
threshold from the measured percentile distribution for that query class plus a margin,
not a guess.
Fallback design. Two shapes, chosen by what the user is more hurt by:
- Partial results, for a query aggregating across many partitions or tenants: return
the aggregate over whatever finished before the deadline, explicitly labeled as partial
(for example, "computed from 8 of 12 shards"), rather than blocking forever or, worse,
returning an incomplete number with no label that looks final. - Cached stale data, when any answer beats no answer: fall back to the last successful
result with its age surfaced ("as of 14 minutes ago") instead of a bare timeout error.
Avoiding silent drops. Every timeout and fallback event must be logged, and for the
tiers where it matters, alerted on, with enough context to retry or investigate. The
failure mode to design against is a timeout that returns an empty page with nothing
surfaced anywhere, which reads to a user, or an on-call engineer, as "no results" rather
than "the system gave up", two very different facts to act on. Pair this with an
automatic retry-with-backoff for queries confirmed safe to retry, and a way for a user to
explicitly request "run this the slow way, I'll wait" as an escape hatch rather than a
hard wall.
Worked example: setting the threshold from measured percentiles
Suppose one query class shows a measured distribution of p50 = 150 ms, p95 = 900 ms,
p99 = 3000 ms (the 50th, 95th, and 99th-percentile durations: the values below which
50%, 95%, and 99% of executions finish).
timeout=2×p99=2×3000ms=6000ms
Setting the timeout at twice the measured p99 kills the genuinely pathological outlier,
something well beyond even the worst observed-normal case, while giving legitimately
slow-but-real queries room to finish. Contrast a naive threshold set at p95 (900 ms):
that would time out roughly 4% of genuinely normal queries, everything between p95 and
p99, even though nothing was actually wrong with them, generating false-alarm partial
results and needless retries for traffic that was fine.
Trade-offs and pitfalls
- A single global timeout protects the shared system but actively harms the legitimate
long-tail request; tiering fixes that but adds policy complexity, more thresholds to
maintain, more edge cases in deciding which tier a given query belongs to. - Partial results are honest but require every downstream consumer to know how to
display partial-ness; a dashboard that silently renders a partial aggregate as if it
were complete has just moved the silent-failure problem one layer downstream instead of
solving it. - Auto-retrying every timed-out query, including non-idempotent or genuinely expensive
ones, can turn one slow user into a self-inflicted denial-of-service against the shared
cluster; only auto-retry query classes confirmed safe and cheap enough to retry.
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.
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.
Unlock Full Question Bank
Get access to all 25 Database Performance Tuning and Scaling interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.