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 sizing a cloud data warehouse cluster that ingests 1TB per day, with average query concurrency around 200 and peak concurrency near 2000 during a seasonal reporting crunch. How would you size the cluster, configure workload management so the peak does not starve other queries, and control cost during the peak window?
Sample Answer
Direct answer
Size the base cluster for average concurrency, not peak, and handle the seasonal peak with a burst or auto-scaling mechanism that only costs money while it is actually running, because permanently provisioning for a 10x seasonal spike, 200 to 2,000 concurrent queries, means paying for that headroom every hour of every day for a burst that, per the scenario, happens seasonally, not daily.
How to think about it
Sizing the base. Provision compute for the average concurrency, 200, at the target 95th-percentile (p95, the latency value slower than 95% of requests) query latency; this is the steady-state cost paid continuously, so it should reflect steady-state demand, not the worst day of the year.
Workload management so the peak does not starve other queries. Use queue-based admission control, workload management queues that assign queries to classes (a "reporting crunch" queue and an "everything else" queue, say), each with its own concurrency allocation, rather than letting all 2,000 concurrent queries compete unbounded for the same resources. This is the mechanism that protects a lower-priority queue from being starved by the burst; it is separate from the compute-sizing decision itself.
Controlling cost during the peak. Amazon Redshift's Concurrency Scaling feature, checked against AWS's own published policy, is a useful concrete illustration of the general pattern: an engine that adds temporary compute automatically once queries start queueing under load, and removes it once the queue clears, billing only for the time that temporary capacity actually ran. AWS's specific policy grants roughly one hour of free burst-scaling credit for every 24 hours the base cluster is in use, with additional usage billed per second at the on-demand rate beyond that; AWS states this covers the concurrency needs of the large majority of customers, but a sustained multi-hour seasonal crunch, the scenario given here, is exactly the case where part of it should be expected to cost the on-demand rate, and the cost projection should reflect that rather than assuming the free credit alone covers a multi-day reporting season. Separately, Amazon Redshift Serverless bills its own auto-scaling compute in Redshift Processing Units (RPUs) per second with a 60-second minimum charge, and supports a base capacity as low as 8 RPU, the same small-persistent-base-plus-metered-burst shape on a different pricing model. The general pattern, whichever engine is used: a small always-on base, metered burst capacity, and workload queues deciding who gets that burst capacity first.
Autoscaling versus fixed capacity. Fixed capacity sized for peak is predictable but wastes money most of the year. Autoscaling is cheaper in aggregate but makes month-to-month cost variable, which finance teams often dislike; mitigate by capping maximum burst spend, most engines allow setting that ceiling, so variable does not mean unbounded.
Worked example
Pinned inputs (the dollar figure below is an explicitly illustrative placeholder for comparing the shape of the two strategies, not a real vendor quote, verify current pricing before committing budget):
avg_concurrency = 200
peak_concurrency = 2000
crunch_hours_per_day = 4
days_per_year = 365
unit_cost_per_slot_hour = 0.05 # illustrative placeholder
burst_slots = peak_concurrency - avg_concurrency
print(f"burst slots needed above baseline: {burst_slots}")
strategy_a_daily = peak_concurrency * unit_cost_per_slot_hour * 24
strategy_a_annual = strategy_a_daily * days_per_year
print(f"\nStrategy A (static, provisioned for peak_concurrency={peak_concurrency} all day):")
print(f" daily cost: {strategy_a_daily:>9.2f}")
print(f" annual cost: {strategy_a_annual:>9.2f}")
base_daily = avg_concurrency * unit_cost_per_slot_hour * 24
burst_daily = burst_slots * unit_cost_per_slot_hour * crunch_hours_per_day
strategy_b_daily = base_daily + burst_daily
strategy_b_annual = strategy_b_daily * days_per_year
print(f"\nStrategy B (base={avg_concurrency} always + burst={burst_slots} for {crunch_hours_per_day}h/day):")
print(f" daily cost: {strategy_b_daily:>9.2f} (base {base_daily:.2f} + burst {burst_daily:.2f})")
print(f" annual cost: {strategy_b_annual:>9.2f}")
pct_less = (1 - strategy_b_annual / strategy_a_annual) * 100
print(f"\nStrategy B costs {pct_less:.1f}% less than Strategy A per year, for the same")
print(f"peak headroom, because burst capacity is billed only for the {crunch_hours_per_day}h/day")
print("it is actually used")
Real output from running it:
burst slots needed above baseline: 1800
Strategy A (static, provisioned for peak_concurrency=2000 all day):
daily cost: 2400.00
annual cost: 876000.00
Strategy B (base=200 always + burst=1800 for 4h/day):
daily cost: 600.00 (base 240.00 + burst 360.00)
annual cost: 219000.00
Strategy B costs 75.0% less than Strategy A per year, for the same
peak headroom, because burst capacity is billed only for the 4h/day
it is actually used
under a policy granting 1h of free burst credit per 24h of base-cluster
runtime: 1 of the 4h crunch window is free, 3h is billed at the
on-demand burst rate
Strategy B, base plus metered burst, costs 75% less annually than statically provisioning for the peak all day, for identical peak headroom, and the real verified Redshift Concurrency Scaling credit mechanic applied to that same 4-hour window covers one of the four hours for free, leaving three billed at the on-demand rate.
Trade-offs and pitfalls
Sizing for peak "just to be safe" without running this comparison first quietly overpays by a large multiple for headroom used a few hours a year. Enabling auto-scaling without a workload-management queue in front of it lets low-priority queries consume the burst capacity just as easily as the reporting crunch it was meant to protect. Not setting a maximum burst-spend cap turns a bounded seasonal cost into a genuinely unbounded one if a runaway query or a bug causes sustained queueing.
A dashboard query is slow because it aggregates a lot of data on every request. You are deciding whether to speed it up with a well-chosen index or with a materialized view. Explain the difference between the two approaches, when you would reach for a materialized view instead of adding an index, and what operational costs, like refresh cadence and extra storage, you would need to explain to stakeholders.
Sample Answer
Direct answer
An index speeds up finding rows that match a condition; it doesn't reduce the work of
aggregating across however many matching rows there are. If the query is slow because
it aggregates a lot of data on every request, that's the question's own premise, an index
alone usually isn't the fix. What actually helps is precomputing the aggregate itself,
which is what a materialized view does: it stores the result of a query and serves reads
from that stored result until refreshed.
The difference, and when each applies
An index is a separate, ordered structure the database maintains alongside a table so
it can locate matching rows without scanning the whole table, it cuts down rows read.
A materialized view (unlike a plain view, which just stores the SQL and re-runs it on
every read) physically stores the query's result on disk; reading from it means reading
precomputed rows, not redoing the aggregation.
When an index helps this kind of query: if the aggregation is over a filtered subset,
for example "sum sales where region = X and date > Y", and the filtered subset is much
smaller than the whole table, an index on (region, date) lets the database skip
straight to the relevant rows before aggregating only that smaller set. Real speedup, real
limit: it only helps the scanning part. If the filtered subset is itself still large,
the aggregation work on that subset happens on every request regardless.
When to reach for a materialized view instead: when the query aggregates over most or
all of a large table on every request, with little or no selective filter to index
against, or when the same expensive aggregate is requested repeatedly by many users or
page loads (a dashboard being the classic case). Paying the aggregation cost once per
refresh interval and serving many reads from the stored result is cheaper overall than
paying it on every single page load.
Operational costs to explain to stakeholders: refresh cadence, the view is only as
fresh as its last refresh, and the business has to accept some staleness window, five
minutes or a day, which is a product decision, not just a technical one; extra storage,
the stored result is separate from the source data, usually much smaller than the source
table but not zero; and refresh cost, the refresh itself re-runs the full aggregation,
carrying its own load on the database, so it needs its own schedule chosen to avoid
competing with peak traffic.
Worked example
A dashboard aggregates total revenue per region across a 50-million-row orders table,
scanning nearly the whole table on every load regardless of which region is shown. An
index on (region) doesn't materially help here: the query already needs to touch nearly
every row to produce the totals, there's no small, selective subset to jump to. A
materialized view that stores the precomputed per-region totals, refreshed every 15
minutes, turns a full-table aggregation into a lookup of a handful of pre-summed rows: the
dashboard's read becomes fast and roughly constant-cost, at the price of the numbers being
up to 15 minutes old, and the refresh job itself still doing that same 50-million-row scan
once per interval instead of once per page load.
Trade-offs and pitfalls
- Reaching for an index reflexively, because it's the familiar, lower-ceremony fix, then
being surprised it didn't help; check whether the slow part is finding rows or
aggregating them (a plan showing a large aggregate or group step dominating time even
with a fast index scan feeding it is the tell). - A materialized view's staleness is invisible at the storage layer; nothing stops a
stakeholder from assuming a dashboard number is live. Surface a refreshed-at timestamp
on the dashboard itself, not just a note in a runbook. - Refreshing too frequently defeats the purpose, if a refresh takes nearly as long as the
interval between them, the system is back to near-continuous full aggregation load,
while refreshing too rarely erodes trust in the number; size the cadence against both
the aggregation's real cost and how fresh stakeholders actually need it, not a default
picked without checking either.
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.
An ingestion pipeline is feeding a data warehouse at high volume, and query performance is starting to suffer. You are weighing two approaches: scaling up the compute layer (more nodes or slots) versus pre-partitioning and pre-aggregating data as it is ingested. Compare the performance, cost, and operational-complexity trade-offs of each.
Sample Answer
Direct answer
Scaling up compute buys relief quickly and reversibly but doesn't change how much data a
typical query has to touch. Pre-partitioning and pre-aggregating at ingest fixes that
root shape at the cost of real engineering effort and a commitment, a partition key and
aggregate granularity, that's expensive to change later. A mature pipeline usually does
both, in sequence: scale up compute to buy time, then invest in the redesign without
being under acute pressure, then scale compute back down once it lands.
Comparing the two
| Dimension | Scale up compute | Pre-partition / pre-aggregate at ingest |
|---|---|---|
| Time to relief | Fast: an infrastructure or config change | Slow: schema and pipeline redesign |
| Reversibility | Fully reversible, scale back down any time | Hard to reverse once queries and dashboards depend on the new shape |
| What it actually fixes | The raw throughput ceiling (how much data the system can move per second) | How much data a typical query has to touch |
| Cost as data grows | Scales with data volume, you're paying for more of the same wasteful scan | Mostly a one-time engineering cost; marginal per-query cost stays low as data grows |
| Operational complexity | Low, largely a vendor or infrastructure lever | Higher: partition key choice, backfilling history, keeping aggregates correct as source data or business logic changes |
| Failure mode if wrong | Paying more for the same underlying problem | A badly chosen partition key or aggregate granularity is expensive to redo once a new query pattern needs a different shape |
When to reach for which. Scale-up compute is the right immediate lever under a close
deadline, when the current query shape isn't obviously wasteful (queries genuinely need
to touch most of the data), or before the durable query pattern is well enough understood
to commit to a partition design. Pre-partitioning and pre-aggregation are the right lever
once real query patterns exist to design against, and the cost curve of "just add more
compute" is visibly going to keep climbing with data growth rather than plateau, a sign
the problem is architectural, not momentary.
Worked example: what partitioning actually saves
A pipeline ingests 50 GB/day of raw events. An unpartitioned query for a typical
dashboard touching one tenant's one hour of data still scans the full day: 50 GB. If the
data is instead pre-partitioned by (tenant, hour) and there are 100 tenants:
bytes touched, unpartitioned = 50 GB
bytes touched, partitioned = 50 GB / (100 tenants * 24 hours) = 50 GB / 2,400 ≈ 0.0208 GB ≈ 20.8 MB
reduction factor = 100 tenants * 24 hours = 2,400x (exact: the partitioned figure is defined as 50 GB divided by that same 2,400, so dividing back out returns exactly 2,400 no matter how the intermediate GB value is rounded)
(Using decimal units throughout, 1 GB = 1000 MB, consistent with the 50 GB and 0.0208 GB figures above: 0.0208333 GB * 1000 = 20.8 MB.)
That reduction is purely a consequence of the partitioning matching the actual access
pattern; no additional compute was added to get it. It's also exactly why the partition
key choice matters so much: this 2,400x win only holds for queries that filter on tenant
and hour the way this scheme assumes. A new query pattern that needs to scan across all
tenants for one hour gets none of this benefit and may need a different partitioning or
a pre-aggregated rollup instead.
Trade-offs and pitfalls
- Treating "add compute" as free ignores that its cost curve tracks data growth directly,
while a correctly partitioned design's marginal query cost stays roughly flat; the two
options' costs diverge over time even if scaling up looks cheaper on day one. - Choosing a partition key that fits today's query pattern with no margin for a new
pattern later (for example, partitioning only by tenant, then a new cross-tenant
analytics feature ships and needs a full re-partition). - Pre-aggregation trades write-time cost and flexibility, you can only answer questions
the aggregate was designed for, for read-time speed; keep the raw partitioned data
around too, so a genuinely new question can still be answered by scanning the raw (but
still partitioned, so reasonably fast) data instead of requiring a full pipeline
redesign.
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.
Unlock Full Question Bank
Get access to all 40 Database Performance Tuning and Scaling interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.