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 dashboard's average load time is 8 seconds, and the business needs it under 2. Walk through your remediation plan: how you would measure where the time is going, what quick wins you would try first, what medium-term and long-term architecture changes you would consider, and how you would know if a change made things worse.
Sample Answer
Direct answer
Don't start by changing anything. Measure where the 8 seconds actually goes, apply the
cheap low-risk fixes first, then the structural ones, and re-measure against the same
baseline metric before calling it done, with every step independently revertible. A
concrete example: on a comparably-shaped dashboard I traced a slow aggregate to two
co-occurring symptoms, table bloat and a skewed partition, that each looked fine in
isolation but compounded together.
The remediation plan
1. Measure first. Run EXPLAIN (ANALYZE, BUFFERS) (the command that actually
executes the query and reports the real plan, row counts, and buffer usage, as opposed to
plain EXPLAIN's estimate) on the dashboard's queries. Check the database's query-stats
extension for which statement accounts for the most total time. Check the dead-tuple
ratio (rows a DELETE or UPDATE left behind that haven't been reclaimed yet) in
pg_stat_user_tables. If the table is partitioned, confirm partition pruning is actually
limiting the scan to the relevant partition, and don't assume that alone means the query
is healthy.
2. Quick wins (hours, low risk). Add a missing index the plan reveals is needed.
Rewrite an obviously wasteful query, SELECT * pulling unused columns, an N+1 loop
issuing one query per row instead of one query for all of them. Add a statement_timeout
so one slow request can't starve the rest. If slight staleness is acceptable, add a short
server-side cache in front of the aggregate.
3. Medium-term (days to weeks). A materialized view (a query's result saved as its own table and refreshed on a schedule, instead of recomputed on every read) or precomputed rollup refreshed
on a schedule. Connection-pool tuning. VACUUM (reclaims space left behind by deleted or updated rows so it can be reused, though it does not shrink the file on disk) or reindex maintenance if bloat turns out to
be structural rather than a one-off. Moving the report off the primary database to a read
replica.
4. Long-term / architecture (weeks+). A real incremental pre-aggregation pipeline
that updates rollups at write time instead of computing them at read time. A partitioning
redesign if one partition has become the effective bottleneck. Moving the analytical
workload off the OLTP (online transaction processing, the primary system handling live
reads and writes) primary entirely, onto an OLAP (online analytical processing, a system
built for scanning and aggregating large amounts of historical data) engine designed for
this shape of query.
5. Knowing if a change made things worse. Track the same metric before and after,
ideally the 99th-percentile dashboard load time from real traffic, not a single manual
test run. Watch the query's estimated row count versus actual in the plan (a growing gap
signals stale statistics or a regression). Watch for new lock contention or replication
lag the fix itself introduced. Ship each change behind something independently revertible
(a config value, a feature flag) rather than as one combined deploy.
Worked example: index bloat and partition skew as co-occurring symptoms
I reproduced the bloat side of this on a real PostgreSQL 16 instance to ground the
numbers rather than assert them. A 500,000-row, 78 MB table had half of its rows deleted, executed against a real
PostgreSQL 16 instance:
DELETE FROM bench WHERE id % 2 = 0; -- 250,000 rows removed, half the table
-- after the stats collector flushes:
SELECT n_live_tup, n_dead_tup FROM pg_stat_user_tables WHERE relname='bench';
-- n_live_tup | n_dead_tup
-- ------------+------------
-- 250000 | 250000
A second delete removed half of the remaining rows, checked after the stats collector
caught up, and shows the cumulative dead-tuple count, not just this delete's share:
relname | n_live_tup | n_dead_tup | n_tup_del
---------+------------+------------+-----------
bench | 125000 | 375000 | 375000
n_dead_tup (375,000) counts every row version deleted since the last vacuum or
analyze, from both deletes combined, so it is not the same number as "how many dead
row versions are still physically sitting in the table right now": PostgreSQL prunes
some dead line pointers from a page opportunistically whenever it revisits that page
for any reason, including the second DELETE's own scan, not only during an explicit
VACUUM. A direct on-disk check with the pgstattuple extension right before running
VACUUM confirms only about 125,000 tuples were still physically dead at that point,
matching what VACUUM actually finds:
VACUUM (VERBOSE) bench;
tuples: 125020 removed, 125000 remain, 0 are dead but not yet removable
VACUUM removed 125,020 tuples, not 375,000, because roughly 250,000 of the
cumulative dead-tuple count had already been reclaimed by that opportunistic pruning
before VACUUM ever ran; a second VACUUM immediately after confirmed there was
nothing left to reclaim (0 removed, 125000 remain, where the "remain" figure is
VACUUM's report of the table's current live row count, not a dead-tuple count, so it
reads 125,000, matching the live rows still in the table, rather than 0; 0 remain
would only be printed if the table were actually empty). Despite reclaiming that space, the table's
physical size barely moved: 78 MB before and 78 MB after (81,928,192 bytes before,
81,936,384 bytes after, a difference of exactly one 8 KB page, an unmeasurable change
at the table's scale, not literally the same size the rounded MB figures suggest).
VACUUM without FULL
marks space reusable for future inserts; it does not return it to the operating
system. The table now holds 125,000 live rows, one quarter of the 500,000 rows it was
originally sized for, inside that same 78 MB file, so every scan of that table,
including the dashboard's aggregate, was reading roughly four times the pages the live
data needed, not twice.
Now add the partition angle: if this table is partitioned by month and the query filters
by date, pruning correctly narrows the scan to one partition, say the current month's,
which is also the one absorbing most of the day's writes and deletes (a "hot" partition).
Pruning working correctly (touching only 1 of 12 partitions) doesn't mean that partition
is healthy; if it's carrying a disproportionate share of the table's churn, it can be
bloated exactly like the example above while its 11 siblings are fine. That's why "the
plan shows pruning is working" is not the same conclusion as "the query is fast", you
still have to check the one partition doing all the work.
Trade-offs and pitfalls
- Reaching for an index before checking
EXPLAIN ANALYZErisks fixing the wrong problem;
bloat and stale statistics both produce slow plans that look, at a glance, like a
missing-index problem. - A cache "fixes" the symptom without addressing what staleness stakeholders can actually
accept; a silently stale number on a business dashboard can be worse than a slow but
correct one, so that's a product conversation, not just a technical one. - Precomputing the aggregate shifts cost to the write path and introduces a staleness
window; decide the acceptable window with the business rather than assuming. - Validating against a single idle-system test run and calling it done misses whether the
fix holds under real concurrent load and ongoing bloat regrowth; a fix that looks great
in staging can still fail the p99 (99th-percentile) target in production a week later.
What is a materialized view, and how is it different from a regular (logical) view? Compare them on storage cost, query latency, data freshness, and maintenance overhead, and describe the refresh strategies you could use (on-demand, scheduled full refresh, incremental refresh) and which access patterns favor each.
Sample Answer
Direct answer
A regular (logical) view is a saved query, a name for a SELECT statement that the database re-runs from scratch against live data every time it is queried; it stores no data of its own. A materialized view stores the query's result as an actual table on disk as of the last refresh; reading it is a normal table read, fast and independent of how expensive the underlying query is, but the data is only as fresh as that last refresh.
How to think about it
| Logical view | Materialized view | |
|---|---|---|
| Storage cost | None beyond the stored query text | A full copy of the result set, plus any indexes added on top |
| Query latency | Equal to running the underlying query every time | Equal to a plain table read, and it can be indexed |
| Data freshness | Always current | Stale until the next refresh, a design choice, not a given |
| Maintenance overhead | None | Something, a job, a trigger, or application logic, must trigger refreshes, and a bad refresh strategy either wastes compute or serves stale data |
Refresh strategies. On-demand, refreshed manually or by an explicit application action, fits rarely-changing reference data or a "recompute my report" button. Scheduled full refresh recomputes the entire result on a schedule; simple and correct, but its cost scales with the full underlying query every time regardless of how little actually changed, a good fit for a nightly or hourly warehouse aggregation where near-real-time freshness is not required. Incremental refresh recomputes only the rows affected by recent changes; native Postgres materialized views do not support this out of the box, a plain REFRESH is always a full recompute, so it has to be built, either by accepting REFRESH ... CONCURRENTLY's non-blocking behavior on top of a still-full recompute, or with a hand-rolled incremental pattern such as a trigger-maintained summary table.
REFRESH MATERIALIZED VIEW CONCURRENTLY specifically still recomputes the whole view, but builds it into a shadow copy and swaps it in using the view's own unique index (which is why creating one is required), so readers keep seeing the old data with no lock and no downtime during the refresh. A plain REFRESH instead takes an exclusive lock and blocks readers for its duration. CONCURRENTLY is a concurrency and availability improvement, not a cost improvement, it does not make the refresh cheaper, only non-blocking.
Worked example
A materialized view built over the same 50,000-row orders table as its matching logical view, with a unique index for concurrent refresh:
CREATE VIEW v_customer_totals AS
SELECT customer_id, sum(amount) AS total_amount, count(*) AS n_orders
FROM orders GROUP BY customer_id;
CREATE MATERIALIZED VIEW mv_customer_totals AS
SELECT customer_id, sum(amount) AS total_amount, count(*) AS n_orders
FROM orders GROUP BY customer_id;
CREATE UNIQUE INDEX ON mv_customer_totals (customer_id);
Real, unedited EXPLAIN ANALYZE (Postgres's command for showing a query's actual execution plan and per-step timing) output for the same lookup against each:
-- against the view: recomputes the aggregate every time
GroupAggregate (actual rows=1 loops=1)
-> Seq Scan on orders (actual rows=54 loops=1)
Filter: (customer_id = 408)
Execution Time: 1.532 ms
-- against the materialized view: reads precomputed rows
Index Scan using mv_customer_totals_customer_id_idx (actual rows=1 loops=1)
Execution Time: 0.034 ms
Then a live write shows the freshness gap directly. After inserting one new order for that same customer:
-- the view, queried immediately: current
total_amount | n_orders
15911.04 | 55
-- the materialized view, queried immediately: stale
total_amount | n_orders
14912.04 | 54
Running REFRESH MATERIALIZED VIEW CONCURRENTLY mv_customer_totals; brings it back in sync, 15911.04 | 55, matching the view exactly, with no lock taken on readers during that refresh.
Trade-offs and pitfalls
Treating a materialized view as "just a faster view" and forgetting it can silently serve stale data to a report someone is making a decision from. Forgetting the unique index CONCURRENTLY requires: without it, that refresh mode fails outright, and a plain REFRESH locks readers for its duration instead. Refreshing far more often than the query actually needs burns the same compute the materialized view was meant to save. Not indexing the materialized view itself leaves it barely better than an unindexed pre-aggregated table someone built without much thought.
You manage a 500GB OLTP table that shows average fragmentation over 30 percent. How would you decide between reorganizing and rebuilding its indexes, including the thresholds you would use, whether you can do it online, the impact on locks, and how fillfactor should factor into the decision? Describe a maintenance approach that minimizes impact on users.
Sample Answer
Direct answer
Do not decide this purely from a fixed fragmentation percentage. The widely repeated rule of thumb (reorganize between 5% and 30% average fragmentation, rebuild above 30%) is a reasonable starting filter, but Microsoft's own current guidance for SQL Server explicitly warns against relying on fixed thresholds alone, and points out that a lot of the performance improvement people attribute to a rebuild actually comes from the full statistics refresh a rebuild does as a side effect, not from the physical defragmentation itself. For a 500 GB online transaction processing (OLTP) table under continuous load, the practical default is REORGANIZE (always a fully online, low-impact operation) and REBUILD is reserved for when page density (a page is the fixed-size block of storage, 8 KB by default, that a table or index is physically built from; page density measures how full each page actually is, a different and often more consequential number than fragmentation) is materially low, when the table needs a genuine full-scan statistics refresh, or when fragmentation keeps returning quickly after a reorganize, which is itself a signal about fillfactor, not about the maintenance method.
Structured elaboration
Two different numbers get conflated as "fragmentation"
SQL Server's sys.dm_db_index_physical_stats reports both avg_fragmentation_in_percent (logical fragmentation: how out-of-order the leaf pages are relative to the index's key order, which mainly hurts range and full scans) and avg_page_space_used_in_percent (page density: how full each page actually is, which affects every kind of read because a less-full page means more I/O and less usable buffer-pool cache (the in-memory cache of recently used pages that lets the database skip a disk read on repeat access) per byte of real data). A table can have low logical fragmentation and still perform poorly because of low page density, or vice versa; treating "fragmentation" as one number hides this.
REORGANIZE versus REBUILD
| REORGANIZE | REBUILD | |
|---|---|---|
| Locking | Always fully online; no long-term object-level lock; queries and writes continue throughout | Offline holds an object-level lock for the whole operation, blocking the table; online (WITH (ONLINE = ON), available in Standard Edition since SQL Server 2016 SP1) avoids that except for a brief lock at the very end |
| What it fixes | Leaf level only; physically reorders leaf pages (a B-tree index, the structure most indexes use, is organized as a tree of pages; the leaf level is its bottom layer, the pages that actually hold each indexed value and a pointer to the row it belongs to) to match logical key order and compacts pages to the index's configured fillfactor | All levels of the index; also compacts to the configured (or newly specified) fillfactor |
| Statistics | Does not update statistics at all | Updates statistics with a full scan, equivalent to UPDATE STATISTICS ... WITH FULLSCAN |
| Resource cost | Lower; incremental, and if interrupted its progress up to that point is kept, so it can be restarted rather than redone from scratch | Higher; needs roughly twice the index's disk space for the duration (old and new copy coexist until the rebuild completes) |
| Resumability | Naturally incremental | Can be started as a resumable operation, which can be paused and resumed, on supporting versions |
The statistics angle, and why it changes the decision
Microsoft's current guidance is explicit that customers "often incorrectly attribute" a post-rebuild performance improvement to reduced fragmentation, when the real cause was the full-scan statistics update that happened alongside it. The query optimizer's plan choices depend on statistics currency and sampling quality, not on physical page order; a rebuild refreshes both at once, which is why it can look like a fragmentation fix when it was really a statistics fix achieved at far higher cost. The stated recommendation: if rebuilding an index seems to help, try replacing it with a plain UPDATE STATISTICS ... WITH FULLSCAN next time; the resource cost of updating statistics is minor and the operation typically finishes in minutes, versus hours for a rebuild on a large table.
Where fillfactor fits in
Fillfactor controls how full a page is left when it is built (a fillfactor of 90 leaves 10% of each page empty). Both REORGANIZE and REBUILD compact pages back to the index's configured fillfactor. A lower fillfactor leaves headroom for future row insertions without immediately triggering a page split (the event that causes fragmentation in the first place on a table with a non-sequential key), at the ongoing cost of more pages, more I/O, and less usable buffer-pool cache per byte of real data, every single day, not just during maintenance. Current Microsoft guidance is not to set fillfactor away from 100 by default; do it only where there is actual evidence of a high page-split rate, most commonly an index whose leading column is a non-sequential value like a randomly generated identifier. For this scenario, if fragmentation keeps climbing back to 30% shortly after a reorganize, that recurrence is the evidence to look for before lowering fillfactor, not something a maintenance schedule alone can fix.
A maintenance approach that minimizes user impact on 500 GB
Default to REORGANIZE on a recurring cadence driven by measured fragmentation and page density, not a fixed calendar. It is always online, so it does not need a maintenance window. Reserve REBUILD (with ONLINE = ON) for cases where reorganize is not enough, and if the table is partitioned, rebuild or reorganize one partition at a time rather than the whole 500 GB at once, to bound both the resource footprint and the disk headroom needed for any given operation. Before running any REBUILD, confirm there is enough free disk space for roughly a second copy of the index; on a table this size that is a real, checkable constraint, not a detail to skip.
Worked example
PostgreSQL does not expose an avg_fragmentation_in_percent DMV (Dynamic Management View, SQL Server's term for a system view exposing live internal engine statistics), but its pgstattuple and pgstatindex extensions measure the same underlying ideas (dead space in the table, and leaf-page density in a B-tree index). The following was executed against a real PostgreSQL 16 instance to show what "the index still looks full of garbage until you actually rebuild it" looks like in practice, not just claimed:
CREATE EXTENSION pgstattuple;
CREATE TABLE frag_demo (id bigint PRIMARY KEY, val text) WITH (fillfactor = 90);
INSERT INTO frag_demo SELECT g, repeat('a', 100) FROM generate_series(1, 300000) g;
DELETE FROM frag_demo WHERE id % 3 = 0; -- delete a third of the rows
UPDATE frag_demo SET val = repeat('b', 100) WHERE id % 2 = 0; -- update half
SELECT * FROM pgstattuple('frag_demo');
SELECT * FROM pgstatindex('frag_demo_pkey');
Output (executed), before any cleanup:
dead_tuple_percent | free_percent
---------------------+--------------
46.21 | 2.38
avg_leaf_density | leaf_pages
-------------------+------------
96.36 | 820
The index's avg_leaf_density looks high here (96.36%) but that number is misleading: those leaf pages are still full of index entries pointing at now-dead heap rows. Running an ordinary VACUUM reclaims the dead heap space for reuse, but it also removes the corresponding dead entries from the index leaf pages without compacting them, which actually makes the reported density worse, not better:
VACUUM (VERBOSE) frag_demo;
SELECT * FROM pgstattuple('frag_demo');
SELECT * FROM pgstatindex('frag_demo_pkey');
Output (executed):
dead_tuple_percent | free_percent
---------------------+--------------
0.00 | 49.63
avg_leaf_density | leaf_pages
-------------------+------------
60.13 | 820
Only an actual rebuild (REINDEX, PostgreSQL's equivalent of ALTER INDEX ... REBUILD) repacks the pages:
REINDEX INDEX CONCURRENTLY frag_demo_pkey;
SELECT * FROM pgstatindex('frag_demo_pkey');
Output (executed):
avg_leaf_density | leaf_pages
-------------------+------------
90.00 | 547
before, after = 6_758_400, 4_513_792 # index size in bytes, before and after REINDEX
print(f"index size dropped {(1 - after/before)*100:.1f}%, from {before/1024/1024:.2f} MiB to {after/1024/1024:.2f} MiB")
print(f"leaf pages: 820 -> 547 (density is back to the table's own fillfactor, 90%)")
Output (executed):
index size dropped 33.2%, from 6.45 MiB to 4.30 MiB
leaf pages: 820 -> 547 (density is back to the table's own fillfactor, 90%)
REINDEX CONCURRENTLY (available since PostgreSQL 12) is PostgreSQL's non-blocking equivalent of an online rebuild: it builds a new index alongside the old one and swaps them, so it needs roughly double the index's space temporarily, mirroring SQL Server's own space requirement during an online rebuild, and it cannot be run inside an explicit transaction block. For a full table rewrite rather than just an index, the pg_repack extension does the same "build a shadow copy, then swap" trick for the whole table without holding a long exclusive lock, which is PostgreSQL's rough analog to a SQL Server online table rebuild.
For the SQL Server side of this scenario specifically, here is reference syntax for the ONLINE rebuild and default-preferred reorganize (documented, not executed here, since this environment has no SQL Server instance to run it against):
-- default lever: always online, low impact
ALTER INDEX PK_Orders ON dbo.Orders REORGANIZE;
-- reserved for when reorganize isn't enough, or a full stats refresh is wanted anyway
ALTER INDEX PK_Orders ON dbo.Orders
REBUILD WITH (ONLINE = ON, FILLFACTOR = 90, SORT_IN_TEMPDB = ON);
-- the diagnostic query behind the decision. page_count isn't filtered to a specific
-- vendor-documented cutoff here; skip whatever indexes are small enough on your table
-- that mixed-extent allocation and sampling noise make their reported numbers unreliable.
SELECT i.name, ips.avg_fragmentation_in_percent, ips.avg_page_space_used_in_percent, ips.page_count
FROM sys.dm_db_index_physical_stats(DB_ID(), OBJECT_ID('dbo.Orders'), NULL, NULL, 'SAMPLED') ips
JOIN sys.indexes i ON i.object_id = ips.object_id AND i.index_id = ips.index_id
ORDER BY ips.avg_fragmentation_in_percent DESC;
Trade-offs & pitfalls
- Don't schedule blanket rebuilds on a fixed calendar. Correlate maintenance with measured query performance (SQL Server's Query Store A/B comparison, or a before/after
pgstatindexreading as shown above) rather than assuming a rebuild helped just because it ran. - REBUILD's roughly 2x space requirement is a real operational risk on a 500 GB table, not a footnote; confirm headroom before running one, and prefer partition-level rebuilds over whole-table rebuilds if the table is partitioned.
- A reorganize can fail on a nearly-full data file or filegroup, because it can only allocate its temporary work pages within the same file, not elsewhere in the filegroup, even when the filegroup as a whole has free space.
- Lowering fillfactor "just in case" is a permanent, ongoing cost, not a one-time maintenance decision; only do it where the evidence (recurring fragmentation shortly after a reorganize, a non-sequential leading key with a high page-split rate) actually supports it.
- Fragmentation numbers on very small indexes are frequently not meaningful, and maintaining them rarely reduces the reported fragmentation regardless of how it looks, so it is not worth the resource cost of including them in a maintenance pass.
- Plain VACUUM never fixes index bloat (extra, wasted space left inside an index by updates and deletes, making it physically larger than the live data needs and slower to scan) by itself in PostgreSQL. It reclaims heap space for reuse and removes dead index entries, but as the numbers above show, it can leave the index itself less dense, not more; a genuinely bloated index needs a REINDEX, not just a VACUUM.
You need to add a column to a production table with hundreds of millions of rows, and you cannot take a long lock or cause a visible outage. Describe a safe approach: what technique would you use to make the change incrementally, how would a dual-write-and-backfill strategy work if you needed one, and how would you monitor and cap the impact on live traffic while it runs, including a way to back out if something goes wrong?
Sample Answer
Direct answer
Adding the column itself should be near-instant: a plain ADD COLUMN with a constant (or
NULL) default is a metadata-only change on modern PostgreSQL and doesn't rewrite the
table. The actual risk is in populating it: run that as an explicit incremental backfill
in small batches with pacing between them, have the application dual-write the new column
on every new or updated row going forward before the backfill starts, and monitor replication lag (how far behind the primary a replica's copy of the data has fallen) and lock wait as hard caps that pause the job automatically.
The plan
The ADD COLUMN step itself. On PostgreSQL 11 and later, ADD COLUMN with a
constant default, including NULL, is metadata-only and does not rewrite existing rows.
That's a genuine change from older versions, and a common misconception is that any ADD COLUMN with a default rewrites the whole table; that's only true for a volatile,
non-constant default, or certain constraint additions. This step takes a brief exclusive
lock, but for milliseconds, a fundamentally different risk than the population step.
If a full backfill is needed (computing a derived value per row, the harder case this
question is really about):
- Incremental technique: iterate in small batches by primary-key range, each batch its
own short transaction, with a brief pause between batches so replication and any read
replicas can keep up, and so row locks don't accumulate into one long-held transaction. - Dual-write: ship the application change that writes the new column on every new or
updated row first, before the batch backfill starts, so the backfill isn't chasing a
moving target. The batch job then only needs to cover rows written before that deploy. - Monitoring and capping impact: watch replication lag (don't let a replica fall far
enough behind that a failover would lose data, or that it starts serving badly stale
reads); watch lock-wait time and set alock_timeoutso a batch that's queued too long
aborts rather than backs up behind unrelated traffic; watch dead-tuple growth (a dead tuple is the old copy of a row that Postgres leaves behind after anUPDATE, since it writes a new row version instead of editing the old one in place); the backfill itself generates a dead row version for every update, a real bloat event, meaning the table fills up with dead tuples faster than they get cleaned out, at this row count that needs its own vacuum planning (VACUUMis the background process that reclaims the space those dead tuples hold so the table doesn't just keep growing); and cap the overall rate (target
rows/sec) rather than running batches back to back as fast as possible. - Backing out: since the column can be added nullable with nothing yet depending on it,
backing out mid-backfill just means stopping the job. The column can sit partially
populated with no correctness impact as long as nothing treats it as authoritative
until the backfill and validation are complete, and the dual-write path can be
feature-flagged off independently of the backfill's progress.
Worked example: backfill timing (pinned inputs)
total_rows = 400_000_000
batch_size_rows = 5_000
sleep_between_batches_ms = 50
exec_time_per_batch_ms = 20 # illustrative per-batch UPDATE execution time
num_batches = total_rows / batch_size_rows
time_per_batch_s = (sleep_between_batches_ms + exec_time_per_batch_ms) / 1000.0
total_time_s = num_batches * time_per_batch_s
print(f"num_batches = {num_batches:,.0f}")
print(f"time_per_batch = {time_per_batch_s*1000:.0f}ms")
print(f"total wall time = {total_time_s:,.0f}s = {total_time_s/3600:.1f} hours")
num_batches = 80,000
time_per_batch = 70ms
total wall time = 5,600s = 1.6 hours
Halving the batch size to 2,500 rows roughly doubles num_batches to 160,000 and, for a
similar per-batch overhead, roughly doubles the wall time to about 3.2 hours, a direct
trade between how gentle each batch is on the live system and how long the whole backfill
takes. That trade is worth sizing explicitly against how much time the migration is
actually allowed to take, not defaulted to "as small as possible."
Trade-offs and pitfalls
- Assuming
ADD COLUMNitself is the risky step; on modern PostgreSQL with a constant
default it usually isn't. The real risk in this scenario is almost always the
subsequent full-table update to populate a derived value; don't spend the caution
budget on the step that doesn't need it. - Smaller batches and longer pauses are safer for the shared system but make the backfill
take proportionally longer, size this trade-off deliberately, not by habit. - Shipping the backfill before the dual-write path is verified working means the backfill is chasing a target that's still drifting from concurrent, uninstrumented writes: rows the backfill already processed keep getting changed by callers the dual-write path never reached, so the column silently falls out of sync with its source again after the batch job has already moved past that row. This is the same kind of drift failure that hits any derived copy of data, a cache, a summary table, a replica, whenever its update logic misses a write instead of catching every one.
- Not planning for the backfill's own bloat: 400 million updates generate 400 million
dead tuples somewhere, a genuinely large vacuum workload competing with the same system
the whole plan is trying not to disrupt.
A high-throughput event-ingestion table needs a backpressure and throttling strategy so the database does not fall over when downstream consumers lag. How would you surface backpressure back to producers, what incremental throttling policy would you use, and how would you balance this against SLA requirements?
Sample Answer
Direct answer
Backpressure has to be visible to the producer, not silently absorbed by an ever-growing
queue or an ever-slower database, applied incrementally so throttling kicks in before
outright rejection and rejection before the system falls over, and calibrated against the
freshness SLA (service-level agreement) producers actually need, not just the database's
raw physical write ceiling.
Design
Surfacing backpressure to producers, in increasing strength: a signal in the response
that the system is under load and the producer should slow down voluntarily; an explicit
rate-limit response (an error the producer must respect, with a suggested retry delay);
or, for a synchronous write path, simply making the acknowledgment take longer, which
naturally throttles a single producer's rate but doesn't coordinate across many
independent producers.
Incremental throttling policy. A token bucket is the standard shape: tokens refill at
the sustained rate the database can absorb; each write consumes a token; a short burst
above the sustained rate is allowed up to the bucket's capacity, after which throttling
engages smoothly rather than as a hard cliff the instant sustained capacity is technically
exceeded for one second.
Balancing against SLA. The ingestion SLA (for example, "events are queryable within
60 seconds of being sent") sets how much lag is tolerable before throttling needs to get
more aggressive. A queue allowed to grow unbounded during a downstream slowdown can blow
that SLA for everyone even if no single write was ever rejected, so the trigger for
tightening throttling has to include queue depth or message age, not raw throughput (the volume of writes the system processes per second) alone.
Worked example: sizing the token bucket
Suppose the database's write path, including index maintenance, can sustainably absorb
8,000 rows/sec:
refill_rate=8,000 tokens/sec
Allowing a 1.5x burst above sustained capacity:
bucket_capacity=1.5×8,000=12,000 tokens
burst_seconds=refill_ratebucket_capacity=8,00012,000=1.5s
The bucket holds the equivalent of 1.5 seconds of sustained-rate traffic as burst
headroom: producers can spike well above 8,000/sec briefly, but a burst sustained longer
than that drains the bucket and throttling engages at the sustained refill rate.
Trade-offs and pitfalls
- An unbounded queue in front of the database "solves" backpressure from the database's
point of view, writes never get rejected, while silently blowing the freshness SLA; the
queue itself needs its own depth- or age-based backpressure trigger, not just the
database. - Throttling protects the shared database but pushes cost onto the producer, retries,
buffering, possible data loss if the producer can't buffer indefinitely; the contract
needs to specify what a throttled producer is expected to do, buffer, drop, or alert a
human, rather than leaving it implicit. - A burst allowance sized "generously to be safe" defeats its own purpose: too large an
allowance just delays the moment throttling engages until the underlying database is
already in trouble, instead of smoothing load before it gets there.
Unlock Full Question Bank
Get access to all 38 Database Performance Tuning and Scaling interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.