Scrivio Interview library
ScenarioAdvanced7 min read · updated 12 November 2026

You must load 2 billion rows into a new PostgreSQL table during a migration window of 6 hours. Describe the plan.

Two billion rows in six hours is about 93,000 rows a second sustained, so the plan removes everything that slows inserts: create the table without secondary indexes, foreign keys and triggers, load with COPY in parallel streams split by key range, and build indexes afterwards with parallel workers and a large maintenance_work_mem. We consider an UNLOGGED table during the load, knowing that SET LOGGED then writes the whole table to WAL and reaches replicas, tune checkpoints and watch WAL volume and replica lag, then ANALYZE, verify counts and checksums, and rehearse the whole run on a copy to know the timing.

Why this question is asked

Large migrations live or die by arithmetic and rehearsal. A window of six hours sounds generous until we calculate the rate it demands and remember that indexes, constraints and verification also need time inside it. Interviewers ask this to see whether we understand what makes bulk loading expensive in PostgreSQL and whether we plan like an operator, with numbers, checkpoints and a way to verify. In this answer, we will do the arithmetic, prepare the table, load in parallel, decide about UNLOGGED, tune the server, build indexes and constraints, and verify.

1Start With the Arithmetic

Six hours is 21,600 seconds, so two billion rows means about 93,000 rows per second on average, for the whole window. But the load is not the only step: index builds, foreign key validation, ANALYZE and verification must also fit. A realistic budget gives the load itself about half the window, which means roughly 185,000 rows per second. A single INSERT stream will not get there; parallel COPY into a bare table can, on suitable hardware, but only a rehearsal tells us for sure.

Budget for a 6-hour window
PhasePlanned timeNotes
Parallel COPY into bare table3 h 00about 185,000 rows/s across streams
Primary key and secondary indexes1 h 30parallel builds, high maintenance_work_mem
Foreign keys (NOT VALID, then VALIDATE)0 h 20validation scans, lighter lock
VACUUM ANALYZE, verification0 h 40counts, checksums, statistics
Buffer0 h 30go or no-go checkpoint at hour 3.5
Numbers from a rehearsal replace these estimates.

Writing the budget down early also tells us where to stop and roll back: if the load is not finished at hour 3.5, we will not make the window, and the go or no-go decision is taken then, not at hour 5.9.

2Prepare a Bare Table

Every secondary index, foreign key and trigger adds work to every inserted row: an index entry to insert, a lookup in the parent table, a function call. For two billion rows that is billions of extra operations, done one row at a time. Building an index afterwards is far more efficient, because PostgreSQL sorts all the keys once and writes the index in one pass. So we create the table with its columns only, and add the primary key, other indexes and foreign keys after the load.

SQL
CREATE TABLE events_new (
id bigint NOT NULL, account_id bigint NOT NULL,
occurred_at timestamptz NOT NULL, payload jsonb
) WITH (autovacuum_enabled = false); -- no vacuum fighting the load; we vacuum at the end

Notice that we also turn off autovacuum on the new table during the load. A fresh table receiving only inserts does not need vacuum until it is finished, and we run VACUUM ANALYZE ourselves at the end.

3Load With COPY in Parallel Streams

COPY is PostgreSQL's bulk loading command and much faster than INSERT. One COPY uses one CPU core on the server, so we run several in parallel, each loading its own slice of the data, split by key range or by source file. The right number of streams depends on CPU and disk: we start at about the number of cores minus a few for the system, and the rehearsal shows where throughput stops rising.

Java
# 16 streams, each loading one key range exported from the source
for i in $(seq 0 15); do
psql -d app -c "\copy events_new FROM 'part_$i.csv' WITH (FORMAT csv)" &
done
wait
# progress: SELECT relid::regclass, tuples_processed FROM pg_stat_progress_copy;

pg_stat_progress_copy shows how many rows each running COPY has processed, so we can compare progress against the budget during the run. Splitting by key range also makes failures cheap: if stream 7 fails, we delete its range and rerun that slice instead of starting over.

4UNLOGGED and WAL: Speed Versus Safety

Every row loaded into a normal table is also written to the WAL, the write-ahead log used for crash recovery and replication, which roughly doubles the writing. An UNLOGGED table skips WAL, so the load is much faster. The catch is serious. An unlogged table is not crash-safe, it is truncated after a crash, and it is not sent to replicas. When we run ALTER TABLE events_new SET LOGGED at the end, PostgreSQL writes the whole table into the WAL in one go, which takes time, produces a huge WAL volume and makes replicas fall far behind while they receive it.

So UNLOGGED is a good choice when the database has no replicas that must stay current, or when the replicas can be rebuilt after the migration, and a poor one when a hot standby must stay close for failover. An alternative with similar savings is COPY into a table created or truncated in the same transaction with wal_level = minimal, which only works without streaming replicas. With replicas, we usually keep the table logged, accept the WAL, and size the window for it.

5Tune the Server for the Load

A few settings make a large difference during the window. max_wal_size set high, for example 64 GB, and a longer checkpoint_timeout prevent a checkpoint every few minutes, each of which forces dirty pages to disk and makes full-page images appear in WAL again. maintenance_work_mem of several gigabytes lets index builds sort in memory, and max_parallel_maintenance_workers lets each CREATE INDEX use several workers.

SQL
ALTER SYSTEM SET max_wal_size = '64GB';
ALTER SYSTEM SET checkpoint_timeout = '30min';
ALTER SYSTEM SET max_parallel_maintenance_workers = 8;
SELECT pg_reload_conf();
SET maintenance_work_mem = '8GB'; -- per session that builds an index
CREATE UNIQUE INDEX events_new_pkey ON events_new (id);
ALTER TABLE events_new ADD PRIMARY KEY USING INDEX events_new_pkey;
CREATE INDEX ON events_new (account_id, occurred_at);
ALTER TABLE events_new ADD FOREIGN KEY (account_id) REFERENCES accounts (id) NOT VALID;
ALTER TABLE events_new VALIDATE CONSTRAINT events_new_account_id_fkey;

Notice that several index builds can run in parallel sessions, each with its own maintenance_work_mem, if memory allows. Adding the foreign key as NOT VALID and validating it separately lets the check scan the table under a lighter lock. Throughout, we watch WAL generation and replica lag, and disk space for pg_wal, because a stalled archive or replica can retain WAL until the disk fills.

6Finish, Verify and Rehearse

At the end we run VACUUM ANALYZE so the planner has statistics and the visibility map is set; without statistics, the first queries against two billion rows can choose terrible plans. A VACUUM FREEZE now, if time allows, also avoids a huge anti-wraparound vacuum months later. Then we verify: row counts per key range against the source, and checksums, for example the sum of a hash of each row per range computed on both sides, which catches truncated or corrupted slices that a count alone would miss. Finally we restore autovacuum and the normal settings.

Most importantly, all of this is rehearsed on a full-size copy before the real night. The rehearsal gives real timings for each phase, the right number of streams and settings, and a tested script, so the go or no-go checkpoint is based on numbers we have seen, not hopes.

7Follow-up questions

What does COPY FREEZE do?

If the table was created or truncated in the same transaction as the COPY, COPY ... WITH (FREEZE) writes the rows already frozen and marked visible, which saves a later vacuum pass over the whole table. It only works under that condition, and it suits loads into new tables well.

How would you handle a failure halfway through?

Because each stream loads a separate key range, we find which ranges completed, delete any partial range and rerun only that slice. If the go or no-go time passes without enough progress, we stop, keep the old system running, and use what we learned to adjust the plan.

8Conclusion

In this answer, we saw how to plan loading two billion rows in six hours. We start from the arithmetic and a phase budget, create a bare table without secondary indexes, foreign keys and triggers, load with parallel COPY streams split by key range, decide carefully about UNLOGGED because SET LOGGED rewrites the table into WAL and affects replicas, tune checkpoints and maintenance_work_mem for the load and the index builds, and finish with ANALYZE, verification of counts and checksums, after a full rehearsal on a copy.

What to say in the interviewAbout 90 seconds aloud

Open with

I would start with the arithmetic: six hours is about 93,000 rows a second, and indexes, constraints and verification also need time, so the load itself must run at nearly twice that.

Then, if they want more

I would create the target table with columns only, no secondary indexes, foreign keys or triggers, and autovacuum off for that table. Then I load with COPY in parallel streams, maybe sixteen, each a separate key range or file, sized by rehearsal to the CPU and disks, and watch pg_stat_progress_copy against the budget.

I would consider an UNLOGGED table for the load to skip WAL, but SET LOGGED afterwards writes the whole table into WAL and floods the replicas, so with a standby that must stay current I keep it logged and size the window for the WAL.

During the window I raise max_wal_size and checkpoint_timeout so checkpoints are rare, and I watch WAL volume, pg_wal disk and replica lag. After the load I build the primary key and indexes with a large maintenance_work_mem and parallel maintenance workers, add foreign keys as NOT VALID and then validate them.

Finally VACUUM ANALYZE, freeze if time allows, and verify row counts and checksums per key range against the source. All of this is rehearsed on a full-size copy, with a go or no-go checkpoint at about hour three and a half.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "You must load 2 billion rows into a new PostgreSQL table during a migration window of 6...": https://scrivio-interview-library.netlify.app/databases/query-optimization/181edde56f/