Database Performance Tuning and Scaling Questions
System-level performance work beyond a single query: configuration and resource tuning, capacity planning, handling large data volumes, and scaling read and write throughput. Covers identifying bottlenecks, growth management, the vertical-versus-horizontal scaling decision, materialized views for expensive queries, and maintenance work such as vacuuming, index rebuilds, bulk loads, and safe schema changes on large tables. Tests whether a candidate can keep a database healthy as load grows.
You need to bulk-load 100 million rows into PostgreSQL with minimal downtime and minimal WAL bloat. Walk through your plan: how would you validate the data first, choose between COPY and row-by-row INSERT, decide whether to disable and rebuild indexes, consider partitioning or UNLOGGED tables, and tune settings like maintenance_work_mem and parallelism? What risks would you flag, and how would you confirm the load succeeded?
Sample Answer
Direct answer
Validate the data against a disposable staging table before it ever touches the real one, load with COPY rather than row-by-row INSERT (a real, measured ~15x reduction in write-ahead log, or WAL, volume for the same rows in the test below), defer any non-primary-key indexes until after the load and only build the primary key up front if something else genuinely depends on uniqueness during the load itself, and size maintenance_work_mem and parallel workers for the index build rather than leaving them at their small interactive-session defaults. On the same test, building the primary key after the load instead of maintaining it during the load cut total WAL roughly in half. If the table can tolerate being reloaded from source on a crash, loading into an UNLOGGED table and converting it to logged only after the load is confirmed successful avoids writing that WAL at all during the risky part of the operation. WAL matters here in concrete terms: it is the log every change must be durably written to before Postgres calls a transaction committed, so a smaller WAL volume means less disk I/O and disk space consumed during the load, and less lag pushed onto any physical replica that has to replay every byte of it.
Structured elaboration
Validate first, against a disposable copy
Load the source data into a plain (or UNLOGGED) staging table first, or validate the source file directly with a script, before it ever reaches the destination table: check for null values in required columns, duplicate values in what will become the primary key, and that foreign-key targets actually exist. Finding a bad batch here means dropping and reloading a disposable staging table, not untangling a partially-loaded 100-million-row production table.
COPY versus row-by-row INSERT
COPY uses a dedicated bulk-loading protocol: rows stream to the server in one continuous operation instead of one parsed, planned, and separately logged statement per row. The measured section below shows this is not a marginal difference.
Index handling
For a one-time load of this size, drop or defer every index that is not required to be enforced during the load itself, run the COPY, then build indexes afterward. If the table must stay readable and writable by other sessions while the index builds, use CREATE INDEX CONCURRENTLY, which costs more and does not guarantee success on the first attempt (an interrupted concurrent build can leave an invalid index that has to be dropped and retried), in exchange for not blocking concurrent queries.
Partitioning and UNLOGGED tables
If this 100 million rows are a brand-new table rather than an append to an existing one, consider building it as a set of partitions and loading each partition with its own COPY, which allows parallel load streams and per-partition index builds. Sizing and routing a partitioning scheme is its own decision with its own trade-offs beyond this load; the relevant point here is only that partitioning is a lever for splitting one enormous load into several smaller, independently loadable and independently indexable pieces.
UNLOGGED tables skip the write-ahead log entirely, which is why the measurement below shows zero WAL bytes for the same load. The cost is that an UNLOGGED table's contents do not survive a crash or unclean restart and are not sent to physical replicas. The safe use of this for a one-time load: load into an UNLOGGED table, validate the result, then run ALTER TABLE ... SET LOGGED, which writes the table's contents to WAL exactly once as part of establishing durability. That is one bulk write instead of the incremental per-row WAL the original load would otherwise have generated, and it only pays that cost once the load is already confirmed good.
Tuning maintenance_work_mem and parallelism
maintenance_work_mem governs the memory available to operations like CREATE INDEX and VACUUM (distinct from work_mem, which governs ordinary query sorts and joins). Raise it for the duration of the load and index-build session rather than raising the cluster-wide default, since a generous value is safe specifically because you control how many maintenance operations are running concurrently during a dedicated load window; the same value left as a global default could let many ordinary sessions each claim that much memory at once. max_parallel_maintenance_workers lets a single CREATE INDEX use multiple parallel workers to build faster.
Risks to flag
WAL volume from a 100-million-row load, even via COPY, is real and can pressure disk space on the WAL volume or increase lag to any replicas, unless the table is loaded UNLOGGED. A single very large transaction can outrun the checkpointer (the background process that periodically flushes all recently modified in-memory pages to disk as a checkpoint, so older WAL can eventually be recycled), causing a burst of checkpoint I/O once it does catch up; checkpoint_timeout and max_wal_size (settings that control how often a checkpoint happens) can be raised temporarily for the load window. If this is an append to an existing live table rather than a new one, ordinary lock contention with concurrent readers and writers applies. Constraint violations discovered only at the very end of a long load are expensive; this is exactly what staging-table validation avoids.
Confirming the load succeeded
Compare the loaded row count against the source. Check for duplicate or null values in what should be unique or required columns. If any index was built CONCURRENTLY, check pg_index.indisvalid, since an interrupted concurrent build can silently leave an invalid index behind rather than failing loudly. Run ANALYZE on the table once loaded, since a table that just went from zero to 100 million rows with stale (or entirely absent) statistics can get badly wrong query plans until the planner has fresh numbers to work from.
Worked example
Everything below was executed against a real PostgreSQL 16 instance. pg_current_wal_lsn() and pg_wal_lsn_diff() give the exact number of WAL bytes a statement generated, a real, deterministic, storage-level measurement, not a timing claim.
First, COPY into a table where the primary key index is already built and maintained live during the load, versus COPY into an unindexed table with the primary key added afterward, both loading the same 2,000,000 generated rows:
CREATE TABLE bulk_indexed (id bigint PRIMARY KEY, val text);
CREATE TABLE bulk_noindex (id bigint, val text);
SELECT pg_current_wal_lsn() AS lsn_start \gset
\copy bulk_indexed FROM '/tmp/data.csv' WITH (FORMAT csv)
SELECT pg_wal_lsn_diff(pg_current_wal_lsn(), :'lsn_start');
SELECT pg_current_wal_lsn() AS lsn_start \gset
\copy bulk_noindex FROM '/tmp/data.csv' WITH (FORMAT csv)
SELECT pg_wal_lsn_diff(pg_current_wal_lsn(), :'lsn_start'); -- copy only
SELECT pg_current_wal_lsn() AS lsn_mid \gset
ALTER TABLE bulk_noindex ADD PRIMARY KEY (id);
SELECT pg_wal_lsn_diff(pg_current_wal_lsn(), :'lsn_mid'); -- index build only, isolated from a fresh LSN snapshot taken right after the copy
Output (executed, WAL bytes for 2,000,000 rows):
COPY into a table with the PK already built: 187,815,768 bytes
COPY into an unindexed table: 55,237,144 bytes
ADD PRIMARY KEY run once, after the load (isolated): 40,846,816 bytes
maintained_during_load = 187_815_768
deferred_total = 55_237_144 + 40_846_816
reduction = (1 - deferred_total / maintained_during_load) * 100
per_row_maintained = maintained_during_load / 2_000_000
per_row_deferred = deferred_total / 2_000_000
target_rows = 100_000_000
print(f"deferring the index cut total WAL by {reduction:.1f}%")
print(f"extrapolated to {target_rows:,} rows: "
f"{per_row_maintained*target_rows/1e9:.2f} GB (index maintained during load) vs "
f"{per_row_deferred*target_rows/1e9:.2f} GB (index built after)")
Output (executed):
deferring the index cut total WAL by 48.8%
extrapolated to 100,000,000 rows: 9.39 GB (index maintained during load) vs 4.80 GB (index built after)
Next, COPY versus row-by-row INSERT for the same 200,000 rows (the INSERT version is 200,000 separate autocommitted statements, the common shape of a naive "just loop and insert" script):
SELECT pg_current_wal_lsn() AS lsn_start \gset
\copy bulk_copy_200k FROM '/tmp/data_200k.csv' WITH (FORMAT csv)
SELECT pg_wal_lsn_diff(pg_current_wal_lsn(), :'lsn_start');
-- 200,000 individual statements, e.g. generated from application code, no explicit
-- transaction wrapping them, so each one commits on its own:
-- INSERT INTO bulk_rowbyrow (id, val) VALUES (1, 'v1');
-- INSERT INTO bulk_rowbyrow (id, val) VALUES (2, 'v2');
-- ... (200,000 lines)
SELECT pg_current_wal_lsn() AS lsn_start \gset
\i rowbyrow_inserts.sql
SELECT pg_wal_lsn_diff(pg_current_wal_lsn(), :'lsn_start');
Output (executed, WAL bytes for the same 200,000 rows):
COPY: 5,305,992 bytes
row-by-row INSERT: 80,843,112 bytes
copy_bytes, insert_bytes = 5_305_992, 80_843_112
print(f"row-by-row INSERT generated {insert_bytes/copy_bytes:.2f}x more WAL than COPY for the identical rows")
target_rows = 100_000_000
per_row_copy = copy_bytes / 200_000
per_row_insert = insert_bytes / 200_000
print(f"extrapolated to {target_rows:,} rows: "
f"{per_row_copy*target_rows/1e9:.2f} GB (COPY) vs {per_row_insert*target_rows/1e9:.2f} GB (row-by-row INSERT)")
Output (executed):
row-by-row INSERT generated 15.24x more WAL than COPY for the identical rows
extrapolated to 100,000,000 rows: 2.65 GB (COPY) vs 40.42 GB (row-by-row INSERT)
COPY into an UNLOGGED table, same 2,000,000 rows:
CREATE UNLOGGED TABLE bulk_unlogged (id bigint, val text);
SELECT pg_current_wal_lsn() AS lsn_start \gset
\copy bulk_unlogged FROM '/tmp/data.csv' WITH (FORMAT csv)
SELECT pg_wal_lsn_diff(pg_current_wal_lsn(), :'lsn_start');
Output (executed):
0
Finally, scoping maintenance_work_mem to just the index-build transaction with SET LOCAL, and confirming it actually reverts afterward:
BEGIN;
SET LOCAL maintenance_work_mem = '512MB';
SET LOCAL max_parallel_maintenance_workers = 4;
SHOW maintenance_work_mem;
CREATE INDEX bulk_indexed_val_idx ON bulk_indexed (val);
COMMIT;
SHOW maintenance_work_mem;
SELECT indisvalid FROM pg_index WHERE indexrelid = 'bulk_indexed_val_idx'::regclass;
Output (executed):
maintenance_work_mem
-----------------------
512MB -- inside the transaction, during the index build
maintenance_work_mem
-----------------------
64MB -- back to the session default immediately after COMMIT
indisvalid
------------
t
SET LOCAL only takes effect inside an explicit transaction block; run outside one, it is silently scoped to nothing and PostgreSQL warns rather than applies it, which is itself worth knowing before relying on it in a script that is not already wrapped in BEGIN/COMMIT.
Trade-offs & pitfalls
CREATE INDEX CONCURRENTLYis not free insurance. It costs more than a plain build and can fail partway through, leaving an invalid index that has to be dropped and rebuilt; use it only when the table genuinely must stay live during the index build, and always checkpg_index.indisvalidafterward.UNLOGGEDis not a default choice. It is the right lever specifically when the load can be redone from source on failure; for a load that cannot be cheaply repeated, the durability it gives up is not worth the WAL savings.- A single 100-million-row transaction is itself a risk, independent of WAL volume: it can outrun the checkpointer and, if it needs to be rolled back for any reason, undoing it is expensive. Loading in batches (still via
COPY, just multipleCOPYcalls) bounds the blast radius of a failure partway through. - Skipping the post-load
ANALYZEis a common, quiet mistake. A table with no statistics at all can get a catastrophically bad first query plan, which then looks like a mysterious performance problem entirely unrelated to the load that actually caused it. - The same instinct (minimize logging, avoid maintaining indexes row by row) applies on other engines, under different names. SQL Server bulk operations can run minimally logged under the
BULK_LOGGEDorSIMPLErecovery models (settings that control how much detail SQL Server's own transaction log keeps) combined with theTABLOCKhint (a table-level lock taken in exchange for permitting that faster, minimally-logged path), trading point-in-time recovery granularity (the ability to restore the database to an arbitrary moment using the log) for less log volume, similarly to whatUNLOGGEDtrades away here. Where PostgreSQL's lever for splitting a huge load is partitioned tables loaded independently, SQL Server's closest analog for a near-instant bulk swap isALTER TABLE ... SWITCH PARTITION, which moves an already-prepared partition into the live table as a metadata-only operation rather than a data-copying one. The underlying principle carries across engines even though the specific mechanism and syntax do not.
Your OLTP database is seeing p99 write latency spikes traced to bursts of fsyncs. What mitigations would you consider at the OS, filesystem, database-engine, and application layers to reduce that tail latency without giving up durability, and what are the trade-offs of each?
Sample Answer
Direct answer
fsync is the system call that forces the write-ahead log (WAL, the durability log every
committed transaction must be flushed to before the commit is acknowledged) to durable
storage, so every mitigation here is really trading durability risk for latency, not a
free performance win. The highest-leverage, lowest-risk lever is grouping many commits
behind fewer fsync calls (group commit) before reaching for anything that weakens the
durability guarantee itself.
Mitigations, layer by layer
OS and filesystem layer. Avoid a filesystem or mount configuration that adds its own
extra journal or flush overhead on top of the database's own fsync (double-journaling).
Confirm the storage device honors fsync correctly: a virtualized or cloud disk with a
write cache that isn't battery- or power-loss-protected can return from a flush call
before data is actually durable, which is a correctness risk wearing a performance-win
disguise, not a real mitigation.
Database-engine layer (verified against a live PostgreSQL 16 instance's actual
parameter names and current defaults):
commit_delay(default0) andcommit_siblings(default5): lets the WAL writer
wait a short configurable delay before flushing, if at leastcommit_siblingsother
transactions are also waiting to commit, so onefsynccovers several commits instead
of one each. This is literally group-commit tuning, and it only helps when there's
actually something to group with.synchronous_commit(defaulton): can be relaxed tooff(the client is told the
transaction committed before its WAL record is confirmed flushed) or tolocal/
remote_writein a replicated setup. This directly trades durability, a crash inside
the risk window can lose the last fraction of a second of commits, for removing the
fsyncwait from the commit's critical path entirely. It's a named, explicit trade, not
free performance, and should be scoped to data that's been deliberately decided doesn't
need commit-level durability.wal_writer_delay(default200ms) andwal_writer_flush_after(default1MB):
control how eagerly a background process flushes WAL even without an explicit commit
waiting, smoothing out bursts before they reach the commit path at all.full_page_writes(defaulton): protects against a torn page (a page whose write a crash interrupted partway through, leaving it part old data and part new data on disk) by writing a full page image to WAL the first time a page is modified after a checkpoint (the
periodic point where all recently modified in-memory pages are flushed to disk).
Disabling it reduces WAL volume, and thereforefsync-able bytes, but reopens a real
corruption risk on crash unless the storage layer independently guarantees atomic page
writes; generally not worth disabling on typical cloud block storage (a virtual disk volume attached to the database server over the network, like AWS EBS or its equivalent on other clouds).
Application layer. Batch logically related writes into fewer, larger transactions
instead of many small autocommitted ones, fewer commits means fewer fsync calls by
definition. For workloads that can tolerate it, route non-critical writes (telemetry that
can be reconstructed, isn't itself a source of truth) to an asynchronous queue instead of
a synchronous commit on the hot path, reserving the fsync-bound path for writes that
genuinely need the guarantee.
Worked example: what group commit buys you
Without grouping, every commit pays its own fsync serially. With an illustrative
single-fsync latency of 4.0 ms:
TPSmax=Lms1000=4.01000=250 commits/sec
With group commit able to batch up to 50 transactions arriving within a 2.0 ms window
behind one fsync:
TPSgrouped=twindowbatch_size=0.002s50=25,000 commits/sec
This is an idealized upper bound: it assumes 50 concurrent committers genuinely arrive
within every 2 ms window. Group commit only helps when there's real concurrent commit
traffic to group; a single serial client committing one transaction at a time sees no
benefit from it at all, since there's never anyone else to batch with.
Trade-offs and pitfalls
- Reaching for
synchronous_commit = offfirst because it's the largest number on paper;
it should be the last lever, reserved for data explicitly decided not to need
commit-durability, not a blanket performance setting applied everywhere. - Mistaking a virtualized disk that returns from
fsyncquickly for a fast, durable disk;
verify the storage layer's actual durability guarantee, not just its latency. - Group commit helps throughput under concurrent load but can slightly increase the
latency of any individual commit under low concurrency, it may wait up to
commit_delayfor siblings that never show up, so validate it against your actual
traffic's concurrency profile rather than assuming it's a free win in every situation. - Disabling
full_page_writeswithout confirming the storage layer's atomic-write
guarantees trades a rare torn-page corruption risk for WAL savings that group commit or
WAL compression could usually get more safely.
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 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.
You are building a monitoring dashboard for a production database. What are the 8 to 10 metrics you would include, covering resource utilization, replication, query performance, and capacity? Why does each one matter, and what alert thresholds would you set for them?
Sample Answer
Direct answer
A production database monitoring dashboard needs metrics from four categories, resource utilization, replication, query performance, and capacity, because a healthy reading in one category can hide a real problem in another. Nine metrics cover the ground well: CPU utilization, buffer cache hit ratio, disk input/output operations per second (IOPS) utilization, disk space used, active connections against the configured maximum, replication lag, replica connectivity state, the 95th and 99th percentile (p95 and p99) query latency, and lock wait time or blocked query count.
How to think about it
| Metric | Category | Why it matters | Example threshold |
|---|---|---|---|
| CPU utilization | Resource | Sustained high CPU means queries are compute-bound and burst headroom is gone | WARN 70%, PAGE 90% sustained 5 min |
| Buffer cache hit ratio | Resource | A low hit ratio means the working set no longer fits in memory, so page latency suffers even before IOPS are maxed | WARN below 95% sustained |
| Disk IOPS utilization | Resource, capacity | Approaching provisioned input/output operations per second (IOPS) triggers throttling on cloud storage tiers with a hard cap | WARN 70%, PAGE 90% |
| Disk space used | Capacity | A full disk does not just slow writes, it can take the database down entirely, since the write-ahead log cannot be written | WARN 75%, PAGE 90% |
| Active connections vs max | Resource, capacity | Approaching the connection cap causes new connections to be rejected outright, a hard failure, not a slowdown | WARN 70%, PAGE 90% |
| Replication lag (bytes or time) | Replication | A lagging replica risks stale reads if it serves traffic, and a promotion target too far behind loses data on failover (the moment a replica is promoted to become the new primary after the original fails) | WARN above your recovery point objective's tolerance, PAGE at the point a failover would lose unacceptable data |
| Replica connectivity state | Replication | A fully disconnected replica is not "a bit behind," it is providing no protection at all, and lag stops updating once disconnected, which can look falsely fine on a dashboard showing only the last known value | Binary up/down alert, independent of the lag number |
| p95 and p99 query latency | Query performance | Averages hide the tail that actually causes user-visible timeouts; the 95th and 99th percentile are the latency values slower than 95% and 99% of requests | Tied to your service's own latency target for that endpoint |
| Lock wait time or blocked queries | Query performance | Distinguishes "the database is slow" from "queries are fine individually but queueing behind a lock," a different fix entirely | PAGE if sustained more than a minute or two |
This list holds whether the instance is standalone or serving a mixed workload of online transaction processing (OLTP, many small read and write transactions) and online analytical processing (OLAP, fewer, larger queries that scan and aggregate data); a mixed workload just means watching the query-performance metrics separately per workload type, since an analytical query's normal duration and a transactional query's normal duration are entirely different baselines, and one threshold cannot serve both honestly.
Worked example
Real output pulled from a running instance, illustrating what these look like in practice:
-- buffer cache hit ratio
cache_hit_pct | blks_hit | blks_read
99.95 | 1562989 | 718
-- per-table scan pattern (a missing-index signal when seq_scan dominates)
relname | seq_scan | idx_scan
order_items_denorm | 1 | 1
orders | 5 | 0
And the replication query returning correctly empty on an instance with no replica attached:
SELECT application_name, state,
pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn) AS replay_lag_bytes
FROM pg_stat_replication;
-- (0 rows)
Zero rows here is the correct, real answer for this specific instance, not a broken query, a genuine replication setup returns the lag columns shown in a read-replica health check instead.
Trade-offs and pitfalls
Alerting on every metric at the same severity causes alert fatigue, and real pages get ignored along with the noise. Thresholds copied from someone else's blog post instead of your own baseline will page every day if your normal steady state already runs at that level. Missing the replica connectivity state specifically, because a lag graph can look fine while actually frozen at its last reading. Monitoring only resource metrics or only query-performance metrics, never both, hides real incidents either way: high CPU with no p99 alarm can be an entirely healthy scheduled batch job, and a p99 spike with normal CPU is often a lock or an external dependency, not the database's own fault at all. Connections being rejected outright rather than degrading gracefully once the cap is hit is exactly why that threshold should warn well before 100%, not at it.
Unlock Full Question Bank
Get access to all 11 Database Performance Tuning and Scaling interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.