Scrivio Interview library
ScenarioAdvanced7 min read · updated 12 November 2026

Nightly bulk loads of hundreds of millions of rows into PostgreSQL are taking longer each month and now overlap with business hours. What options would you evaluate?

I would evaluate five options, roughly from cheapest to largest change: replace INSERT batches with COPY through the PostgreSQL driver's CopyManager; load into a staging table without indexes and merge from there, or drop and rebuild indexes around the load; partition the target table so each load and its cleanup touch only new partitions; replace full reloads with incremental or change-data-capture loads; and ask whether this workload belongs in an analytical store instead of the OLTP database at all.

Why this question is asked

A nightly load that grows a little every month is a slow-motion incident: nothing breaks until the day the job overlaps business hours, and then customers feel the locks, I/O and replication lag. Interviewers ask this scenario at senior levels because there is no single trick; the answer is a sequence of options with different costs, from a code change to an architecture change. In this answer, we will see why the load slows down as data grows, then go through COPY, staging tables and index handling, partitioning, incremental loads, and moving the workload elsewhere, and finish with how to choose.

1Why the Load Gets Slower Every Month

Inserting a row into PostgreSQL costs more than writing the row. Every index on the table must be updated, and as an index grows beyond memory, each insert touches pages that must be read from disk. Every change is written to the write-ahead log (WAL), the journal PostgreSQL uses for crash recovery and replication, so a large load also means a large WAL volume to write and ship to replicas. If the job deletes old data before reloading, it leaves dead rows that autovacuum must clean, and a table that keeps growing makes all of that slower.

So load time grows faster than data volume. Before changing anything, we measure where the time goes: per-phase timings in the job, pg_stat_statements for the statements, wait events in pg_stat_activity during the run, WAL generated, and checkpoint frequency. The fix depends on whether the time is in the client, in index maintenance, in deletes, or in I/O.

2Option 1: Use COPY Instead of INSERT Batches

COPY is PostgreSQL's bulk-load command. Instead of executing a statement per row or per group of rows, the client streams rows in text, CSV or binary format, and the server parses them in a tight loop. It is commonly several times faster than even well-batched INSERTs. From Java, the PostgreSQL driver exposes it through CopyManager.

Java
try (Connection con = dataSource.getConnection()) {
CopyManager copy = con.unwrap(PGConnection.class).getCopyAPI();
try (Reader in = Files.newBufferedReader(Path.of("/data/sales-2026-11-04.csv"))) {
long rows = copy.copyIn(
"COPY sales_staging(sale_id, store_id, sold_at, amount) FROM STDIN WITH (FORMAT csv, HEADER true)",
in);
log.info("loaded {} rows", rows); // loaded 182000000 rows
}
}

Notice that COPY FROM STDIN streams data from the client, so the file does not need to be on the database server, and the application user does not need file-system privileges. We can also generate rows on the fly by writing them to a Writer connected to copyIn, rather than from a file. COPY stops at the first bad row in most versions, which is another reason to load into staging first; newer PostgreSQL versions add options to tolerate bad rows, so check your version.

3Option 2: Staging Tables and Index Handling

Loading straight into a heavily indexed, busy table is the slowest path. Instead, we COPY into a staging table with no indexes and no constraints, optionally created UNLOGGED so it skips the WAL, then validate the data with SQL and move it into the target with one INSERT ... SELECT, an INSERT ... ON CONFLICT, or MERGE (PostgreSQL 15 and later). Building indexes once over the whole data set is much cheaper than maintaining them row by row.

When the job replaces most of a table, a related trick is to drop secondary indexes before the load and rebuild them afterwards, or to build a new table and swap it in with a rename inside a short transaction. Rebuilding indexes on hundreds of millions of rows still takes time, so we raise maintenance_work_mem for the session and can build several indexes in parallel. The trade-off is that the table has no index during the load, which only works if nothing queries it then.

Step throughStaged nightly load
  1. COPY into an unlogged staging tableno indexes, no constraints
  2. Validate and clean in SQLbad rows to an error table
  3. Analyze the staging tableso the planner has statistics
  4. Merge into the targetINSERT ... SELECT or ON CONFLICT, or attach a partition
  5. Truncate the staging tableready for tomorrow

5 steps in order. Play them, or step through them one at a time.

The expensive per-row work happens on a table nobody else is using.

4Option 3: Partition the Target Table

Declarative partitioning splits one logical table into many physical tables by a key, typically a date. If sales are partitioned by day, tonight's load only touches the new day's partition: its indexes are small and fit in memory, and nothing else is affected. Even better, we can load and index a standalone table, then attach it as a partition with ALTER TABLE ... ATTACH PARTITION, which, with a matching check constraint created beforehand, is quick.

Partitioning also transforms cleanup. Deleting last year's 100 million rows with DELETE generates WAL for every row and leaves dead tuples for vacuum; detaching and dropping an old partition is nearly instant. The costs are design work, a partition key that queries should use for pruning, and primary keys and unique constraints that must include the partition key.

5Option 4: Load Incrementally Instead of in Full

Often the biggest win is not loading faster but loading less. If the nightly job reloads all orders from the source system although only 2 percent changed, we should load only the changes. Options include using an updated_at column with a high-water mark, having the source publish change events, or using change data capture (CDC), which reads the source database's log, for example with Debezium into Kafka, and applies each change shortly after it happens.

CDC also removes the nightly window altogether: data flows continuously in small pieces, which spreads the load over the day and keeps the target fresher. It requires more infrastructure and careful handling of ordering, deletes and schema changes, so it is a bigger project than COPY or partitioning, but it is the option that stops the problem from returning as data keeps growing.

6Option 5: Ask Whether It Belongs in the OLTP Database

Finally, we ask what the data is for. Hundreds of millions of rows loaded nightly are often used for reporting and analytics: aggregates, trends, dashboards. A PostgreSQL primary that serves customer transactions is tuned for many small reads and writes, and every heavy load competes with them for I/O, cache and replication bandwidth.

If the data is analytical, a columnar analytical store or data warehouse, or at least a separate PostgreSQL instance dedicated to reporting, may be the right home. Loads there do not affect customers, and queries over large ranges run much faster on columnar storage. The OLTP database keeps only what the application needs to serve requests. This is the largest change of all, so we usually start with options 1 to 3 to buy time and plan this one deliberately.

Options for the nightly load
OptionEffortTypical gainMain cost
COPY instead of INSERTsmall code changeseveral times faster loadingless row-level error handling
Staging table and mergemoderateless index and lock work on targetextra step and disk space
Drop and rebuild indexessmallfaster for full reloadstable unusable during load
Partition by dateschema changeloads and cleanup touch one partitiondesign work, key in constraints
Incremental or CDC loadsprojectload only what changednew infrastructure
Analytical storearchitecture changeno impact on OLTPnew platform to run
Start with the cheap options and plan the structural ones.

7Follow-up questions

Does COPY bypass constraints and triggers?

No. COPY into a table still checks constraints, updates indexes and fires row triggers, which is why COPY into an indexed target is faster than INSERT but still slower than COPY into a bare staging table. What COPY saves is per-statement overhead: parsing, planning and round trips.

What are the risks of an unlogged staging table?

Unlogged tables skip the WAL, so they are faster to write, but they are truncated after a crash and are not replicated to standbys. For a staging table that we can always reload from the source file, that is acceptable. The target table must stay logged.

How do you keep the load from hurting replicas?

Large loads produce a lot of WAL, and replicas can fall behind. We watch replication lag during the load, spread the load or throttle it if lag exceeds what readers can tolerate, and prefer approaches that generate less WAL, such as unlogged staging, partition attach and dropping partitions instead of deleting rows.

8Conclusion

In this answer, we saw why bulk loads slow down as tables and indexes grow, and went through the options in order of effort: COPY through CopyManager instead of INSERT batches, staging tables without indexes followed by a merge or index rebuild, partitioning so loads and cleanup touch only new partitions, incremental and change-data-capture loads that move only what changed, and finally moving analytical workloads to a store built for them. We measure first, apply the cheap options to buy time, and plan the structural ones.

What to say in the interviewAbout 100 seconds aloud

Open with

I would start by measuring where the time goes: client time, index maintenance, deletes, WAL and checkpoints, and replication lag, because the right fix depends on it. Then I would work through options from cheapest to biggest.

Then, if they want more

First, replace INSERT batches with COPY using the PostgreSQL driver's CopyManager, copyIn with FROM STDIN, which streams rows without per-statement overhead and is usually several times faster.

Second, load into a staging table with no indexes, possibly unlogged since we can always reload it, validate there, and merge into the target with insert select or on conflict; or for full reloads, drop and rebuild secondary indexes around the load or build a new table and swap it.

Third, partition the target by date, so tonight's load only touches a new partition with small indexes, ideally loaded separately and attached, and old data is removed by dropping partitions instead of huge deletes.

Fourth, question the full reload: if only a few percent of rows change, load incrementally with a high-water mark or use change data capture, for example Debezium, which spreads the work across the day and stops the problem from coming back.

And fifth, ask whether hundreds of millions of rows of what is probably analytical data belong in the OLTP database at all, or in a warehouse or a separate reporting instance. I would apply the first options quickly to get out of business hours and plan the last ones properly.

About this answer

Last updated
12 November 2026
Versions it names
PostgreSQL 15
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.
Official documentation
java.sql, package documentation
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 "Nightly bulk loads of hundreds of millions of rows into PostgreSQL are taking longer...": https://scrivio-interview-library.netlify.app/databases/jdbc/0135d57575/