Scrivio Interview library
ScenarioAdvanced7 min read · updated 12 November 2026

A data import service built with Spring Data saveAll() takes 6 hours for 20 million rows. The business needs it in under 30 minutes. How would you approach it?

We measure first: how many statements and round trips each row costs, how ids are generated, and how the time splits between the application and the database. Then we fix the JPA path with sequence ids, JDBC batching, ordered inserts and flush and clear in chunks; and because 20 million rows in 30 minutes means about 11,000 rows per second, we most likely move the bulk load to JdbcTemplate batches or PostgreSQL COPY into a staging table, merge with set-based SQL, defer secondary indexes where safe, and parallelise by partition while watching locks and database capacity.

Why this question is asked

A 12x speed-up target is the kind of problem where guessing wastes weeks. Six hours for 20 million rows is about 925 rows per second, which usually means each row pays several round trips, not that the database is slow. Interviewers ask this scenario to see whether we measure before changing code, whether we know the cost of each layer, and whether we are willing to leave JPA where it does not fit. In this answer, we will measure where the time goes, fix the obvious per-row costs in the JPA path, move to a bulk path, restructure the load with a staging table, and parallelise safely.

1Measuring Before Changing Anything

First we work out the budget. 30 minutes is 1,800 seconds, so 20,000,000 / 1,800 = about 11,100 rows per second. Today we do 20,000,000 / 21,600 = about 925 rows per second. That ratio tells us we need structural change, not tuning.

Then we look at what one row costs. We turn on Hibernate statistics or a JDBC proxy such as datasource-proxy for a sample of 10,000 rows and count statements and batches. We also compare time spent inside JDBC calls with total time, using a profiler or simple timers, and check the database side with pg_stat_statements for the slowest and most frequent statements.

Java
// Sample of 10,000 rows with saveAll()
JDBC statements executed: 30,000 // 3 per row
JDBC batches executed: 0
time in JDBC: 9.6 s of 10.8 s total
-- pg_stat_statements top entries
select ... from customer where external_id = $1 calls 10,000 -- lookup before each save
select nextval('customer_seq') calls 10,000 -- no pooled optimizer
insert into customer ... calls 10,000 -- not batched
Where the six hours go
Cost per rowCauseFix
select before insertfindByExternalId() per rowone lookup per chunk, or upsert in SQL
nextval round tripsequence allocationSize = 1pooled optimizer, allocationSize 50
unbatched insertno batch_size, IDENTITY or mixed orderbatch_size + order_inserts
slow flushesmillions of managed entitiesflush and clear every batch

Notice what the numbers say. Three statements per row and no batches means the time is almost all network round trips. The select per row comes from the import code itself: before saveAll(), it calls findByExternalId() for every row to decide whether to insert or update. The nextval call per row means allocationSize is 1. This is typical, and each item has a clear fix.

2Fixing the JPA Path

If the load must go through entities, for example because rows need domain validation, we remove the per-row costs. We replace the per-row lookup with one query per chunk that loads the existing keys (where external_id in (...)), and use em.persist() for the new rows. We switch to a sequence with allocationSize 50, set hibernate.jdbc.batch_size=50 and order_inserts=true, and call flush() and clear() every 50 entities so the persistence context stays small. We commit in chunks of a few thousand rows so a failure does not undo hours of work.

These changes typically bring a JPA import to several thousand rows per second. That is a big improvement, but for 11,000 rows per second with headroom it is rarely enough on its own, because each row still becomes an entity object, a persistence context entry and a statement.

3Switching to the Bulk Path

For a pure load, the fastest route skips the ORM. JdbcTemplate.batchUpdate sends batched inserts with almost no per-row overhead, and PostgreSQL's COPY command streams rows in the database's own bulk format, typically reaching tens of thousands to hundreds of thousands of rows per second depending on row size and indexes.

Java
// PostgreSQL COPY through the JDBC driver
try (Connection c = dataSource.getConnection();
Reader csv = Files.newBufferedReader(Path.of("customers-part-07.csv"))) {
CopyManager copy = c.unwrap(PGConnection.class).getCopyAPI();
long rows = copy.copyIn(
"COPY staging_customer (external_id, name, email) FROM STDIN WITH (FORMAT csv)", csv);
System.out.println(rows); // 2500000
}

For MySQL, the equivalents are LOAD DATA INFILE where allowed, or batched inserts with rewriteBatchedStatements=true. In both databases the principle is the same: send rows in bulk, not one statement at a time.

4Loading Into a Staging Table and Merging With SQL

Bulk-loading straight into the live table has two problems. Bad rows fail the whole COPY, and every secondary index and foreign key is checked row by row while other users are working. So we load into a staging table first: an unlogged table with no indexes or constraints, which accepts rows as fast as the disk allows. Then a set-based SQL statement validates and merges into the real table in one pass, which the database can execute far more efficiently than millions of single-row statements.

SQL
CREATE UNLOGGED TABLE staging_customer (external_id text, name text, email text);
-- COPY the files into staging_customer (parallel, see below)
INSERT INTO customer (id, external_id, name, email)
SELECT nextval('customer_seq'), s.external_id, s.name, lower(s.email)
FROM staging_customer s
WHERE s.email LIKE '%@%'
ON CONFLICT (external_id) DO UPDATE SET name = EXCLUDED.name, email = EXCLUDED.email;
-- INSERT 0 19998412
SELECT count(*) FROM staging_customer WHERE email NOT LIKE '%@%'; -- 1588 rejected rows to report
Step throughThe restructured load
  1. Split input into partitionsfor example 8 files of 2.5 million rows
  2. COPY each partition in parallelinto an unlogged staging table
  3. Validate in SQLcount and report rejected rows
  4. Merge with INSERT ... ON CONFLICTset-based, in key ranges if large
  5. Rebuild deferred indexesonly if the table was offline
  6. Drop or truncate staging

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

If the target table is empty or offline during the load, we can go further: drop or defer secondary indexes and recreate them after the merge, because building an index once is much cheaper than maintaining it 20 million times. On a live table we keep the indexes, and if the merge itself is too large, we run it in ranges of external_id so each transaction stays manageable.

5Parallelising Without Overloading the Database

With a fast bulk path, parallelism gives the last multiple. We split the input by a natural partition, such as file, region or a hash of the key, so that no two workers write the same rows; that avoids lock conflicts and deadlocks. Then we run several workers, for example 4 to 8, each with its own connection.

But more workers are not always faster. Each one competes for disk, WAL writing and CPU on the database, and the database also serves live traffic. So we increase the worker count step by step while watching database CPU, I/O wait, replication lag and lock waits, and stop when throughput stops rising. We also agree with the DBA on a load window, because a 30 minute bulk load can still slow down other users.

6Follow-up questions

Why not just add more application instances?

If each row still costs three round trips, more instances multiply the load on the database without removing the waste. Parallelism helps after the per-row cost is fixed, and the database's capacity, not the number of application pods, sets the limit.

How do you keep the import correct if it fails halfway?

With a staging table, failure before the merge leaves the live table untouched; we truncate staging and start again. If the merge runs in key ranges, we record the last finished range and resume from there. The ON CONFLICT clause makes rerunning a range safe.

Would Spring Batch help?

Spring Batch gives chunking, restartability and partitioned steps, which fit this job well, and its JdbcBatchItemWriter uses JDBC batches. It does not make the writes faster by itself; the gains still come from batching, the bulk path and partitioning.

7Conclusion

In this answer, we turned a 6 hour import into a plan for under 30 minutes. We measured first and found three round trips per row from a lookup before each save, unpooled sequence calls and unbatched inserts. We fixed the JPA path with one lookup per chunk, persist(), pooled sequence ids, batching, ordering and flush and clear, then moved the bulk of the work to COPY into a staging table, merged with set-based SQL, deferred indexes where safe, and parallelised by partition while watching database capacity.

What to say in the interviewAbout 80 seconds aloud

Open with

I would start by measuring, because six hours for 20 million rows is about 900 rows a second and the target is about 11,000, which needs structural change.

Then, if they want more

I would sample ten thousand rows with Hibernate statistics or datasource-proxy and pg_stat_statements. Typically that shows three statements per row: a select because the code looks up each row before saving it, a nextval because allocationSize is 1, and an unbatched insert. So the time is round trips, not the database.

First I fix the JPA path: one lookup per chunk instead of per row, persist for new rows, a pooled sequence with allocationSize 50, hibernate.jdbc.batch_size and order_inserts, and flush and clear every batch, with chunked commits. That gets a few thousand rows a second.

For a bulk load that is not enough, so I would use PostgreSQL COPY, or JdbcTemplate batches, into an unlogged staging table without indexes, then validate and merge into the real table with set-based SQL using INSERT ON CONFLICT, in key ranges if needed. If the table is offline, I defer secondary indexes and rebuild them after.

Finally I parallelise by input partition so workers never touch the same rows, and increase the worker count while watching database CPU, I/O, locks and replication lag.

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 "A data import service built with Spring Data saveAll() takes 6 hours for 20 million...": https://scrivio-interview-library.netlify.app/databases/jpa-performance/7c8cb7e48a/