Quick revision
The short answer
We run the import as an asynchronous job: the upload goes to object storage, a worker streams it through a CSV parser row by row, validates each row, writes bad rows with their line numbers and reasons to an error file, and loads good rows in large batches, ideally with PostgreSQL COPY into a staging table, followed by a SQL merge into the real tables. The job records its progress so it can resume after a crash, and upserts make a rerun safe.
What to remember
In this answer, we designed an import that keeps memory flat by streaming a 5 GB file through a CSV parser, validates each row and writes bad rows with line numbers and reasons to an error file, and loads good rows with COPY into a staging table before merging into the target tables with upserts. The job records its progress so it resumes after a crash, the checksum and upserts make reruns safe, and partners see progress, counts and a downloadable error report.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We run the import as an asynchronous job: the upload goes to object storage, a worker streams it through a CSV parser row by row, validates each row, writes bad rows with their line numbers and reasons to an error file, and loads good rows in large batches, ideally with PostgreSQL COPY into a staging table, followed by a SQL merge into the real tables. The job records its progress so it can resume after a crash, and upserts make a rerun safe.
Why this question is asked
Thirty million rows is past the point where any shortcut works. Load the file into memory and the pod dies; insert row by row and the import takes a day; fail on the first bad row and the partner resends the file ten times. Interviewers ask this design question because a good answer combines streaming I/O, database bulk loading, validation and operability into one coherent pipeline. In this answer, we will set the goals and numbers, design the overall flow, look at streaming and validation, compare batch inserts with COPY into a staging table, make the job resumable and idempotent, and finish with how partners see progress and errors.
1The Goals and the Numbers
A 5 GB file with 30 million rows averages about 170 bytes per row. We want three properties. Memory must stay flat whatever the file size, so we stream. Throughput should load the file in minutes rather than hours: at 1,000 single-row inserts per second it would take over 8 hours, while COPY commonly loads hundreds of thousands of rows per second into an unindexed table, so a few minutes of loading plus the merge. And a bad row should cost one line in an error report, not the whole import.
We also decide on a policy for errors: for example, accept the file if fewer than 1% of rows are invalid and reject it as a whole above that, because a file with 40% bad rows is probably the wrong file or the wrong format version.
2The Overall Flow
The HTTP request only receives the upload and stores it; everything else happens in a job, so no request waits for 30 million rows.
- Upload to object storagereturns 202 with an import id
- Worker streams the file through a CSV parserone record at a time
- Is the row valid?Yesadd to the COPY batch for stagingNowrite line number and reason to the error file
- Commit each chunk and record the offsetevery 50,000 rows
- Error rate under 1%?Yesmerge staging into target tablesNomark the import rejected
- Publish the resultcounts, error file link, duration
6 steps in order. Play them, or step through them one at a time.
3Streaming and Validating Row by Row
The worker opens the stored file as a stream, decodes it with the partner's agreed charset, and hands it to a streaming CSV parser such as Commons CSV, Jackson CSV or univocity-parsers. Each record is mapped to a small row object and validated, either with Bean Validation annotations or explicit checks for things the annotations cannot express, such as a currency code that must exist.
Notice that a bad row never stops the loop. The error file is itself a CSV with the line number, the business key and a readable reason, which is what lets a partner fix the source data quickly instead of guessing.
4Loading Fast: Batches, COPY and a Staging Table
The simplest fast option is JDBC batching: add rows to a PreparedStatement and execute every few thousand rows, with reWriteBatchedInserts=true on the PostgreSQL driver so it sends multi-row inserts. That is often good enough for millions of rows.
For 30 million rows, COPY is the better tool. It is PostgreSQL's bulk load protocol and avoids most per-statement overhead. Rather than copying into the real table, we copy into a staging table without indexes or foreign keys, which makes the load fast and keeps the target tables untouched until we decide the file is acceptable. PgJDBC exposes COPY through CopyManager and PGCopyOutputStream.
The merge is plain SQL, so the database does the heavy work set-wise, and ON CONFLICT makes it an upsert: running it twice gives the same result. Doing it in ranges of, say, 500,000 lines keeps each transaction short, avoiding long locks and huge write-ahead log bursts.
5Making the Import Resumable and Idempotent
A 20-minute job will eventually be interrupted by a deployment or a crash. Each import has a row in an imports table with its file key, a checksum of the file, the status and the last committed line number, updated in the same transaction as each staging chunk. On restart, the worker re-opens the file, skips records up to that line (parsing is fast, the database work is what we avoid), and continues. Because the merge is an upsert on the business key, repeating part of it is harmless, and the checksum lets us refuse the same file uploaded twice by mistake, or treat it as a no-op.
Spring Batch provides this structure ready-made if we prefer it: a chunk-oriented step with a FlatFileItemReader or a custom reader, a skip policy for invalid rows with a skip limit, a writer that batches inserts, and a JobRepository that stores the read count so a failed job restarts where it stopped.
6Progress and Error Reporting for Partners
Partners need to know what happened without asking support. The job updates its progress, rows read, rows accepted, rows rejected, and the percentage of bytes read from the file, which works even before we know the total row count. An endpoint or partner portal page shows it, and at the end the partner gets a summary with the counts and a link to the error file. We also keep metrics per partner, rows per second, error rate and duration, so that a partner whose error rate suddenly jumps from 0.1% to 15% is noticed, which usually means they changed their export.
7Follow-up questions
Why a staging table instead of COPY straight into the target?
Staging lets us load quickly without indexes, constraints or triggers, decide whether the file as a whole is acceptable, and merge with upsert logic that COPY itself cannot express. The target tables see only clean, deduplicated data in short transactions.
How many rows per batch or chunk?
Usually thousands to tens of thousands. Larger chunks reduce round trips but make each commit and each retry larger. Something like 50,000 rows for COPY chunks and 1,000 to 5,000 for JDBC batches is a sensible starting point, tuned with a load test.
Can we parallelise the import?
Parsing a single CSV stream is sequential, but loading can be split: one thread parses and several write chunks to staging, or the merge runs over line ranges in parallel. Measure first; often the database, not the parser, is the limit.
8Conclusion
In this answer, we designed an import that keeps memory flat by streaming a 5 GB file through a CSV parser, validates each row and writes bad rows with line numbers and reasons to an error file, and loads good rows with COPY into a staging table before merging into the target tables with upserts. The job records its progress so it resumes after a crash, the checksum and upserts make reruns safe, and partners see progress, counts and a downloadable error report.
Open with
I would never process this in the request. The upload goes to object storage and the API returns an import id, and a worker, or a Spring Batch job, does the rest.
Then, if they want more
The worker streams the file with the agreed charset into a streaming CSV parser like Commons CSV or univocity, one record at a time, so memory stays flat.
Each row is mapped and validated, with Bean Validation or explicit checks, and invalid rows do not stop the import; they go to an error file with the line number, the business key and a readable reason. I would also set a threshold, say more than one percent bad rows rejects the whole file.
For loading, row-by-row inserts would take hours, so I would use PostgreSQL COPY through PgJDBC's CopyManager into an unindexed staging table, in chunks of tens of thousands of rows, and then merge into the real tables with INSERT ... ON CONFLICT in ranges to keep transactions short. JDBC batch inserts with reWriteBatchedInserts are the simpler fallback.
To make it resumable, each chunk commits together with the last processed line number in an imports table, so after a crash the job skips ahead; the upsert and a file checksum make reruns safe. Finally partners see progress and a summary with counts and the error file, and we keep per-partner metrics on error rates.
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.
- Official documentation
- The Java Language Specification, Java SE 21, Java SE 21 API 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 "Partners upload CSV files of up to 5 GB with 30 million rows to import into PostgreSQL....": https://scrivio-interview-library.netlify.app/java/io-and-nio/f97fa6161a/