Scrivio Interview library
DebuggingIntermediate7 min read · updated 12 November 2026

A batch insert of 50,000 rows fails with a BatchUpdateException at row 30,000 because of a duplicate key. What state is the database in, and how would you design the job to handle such failures?

It depends on the transaction. If the whole batch ran in one transaction and the failure rolled it back, nothing from the 50,000 rows is persisted; in auto-commit mode, the outcome depends on the driver, and earlier rows may already be committed. BatchUpdateException.getUpdateCounts() shows which statements ran, and drivers differ in whether they continue after the failing row. We design the job in chunks with a transaction per chunk and recorded progress so it can restart, use INSERT ... ON CONFLICT DO NOTHING or a similar upsert when duplicates are expected, and log rejected rows to an error table instead of failing the whole job.

Why this question is asked

Batch jobs rarely fail on the first row. They fail on row 30,000, at 2 a.m., and the first question from everyone is what is in the table now, and can we just run it again. Answering that needs knowing what the driver and the transaction did, not guessing. Interviewers ask this debugging and design question because it separates people who have run real data loads from people who have only written them. In this answer, we will work out the database state in each case, read the exception correctly, and then design the job so that a duplicate key never ruins a night again.

1A Quick Recap of How a Batch Runs

In a JDBC batch, the driver collects parameter sets with addBatch() and sends them with executeBatch(). Spring's batchUpdate with a batch size splits 50,000 rows into chunks, say of 1,000, and calls executeBatch once per chunk. When a statement in a batch fails, the driver throws BatchUpdateException, a subclass of SQLException that also carries an array of update counts. Spring translates it into a DataAccessException, here a DuplicateKeyException, with the BatchUpdateException as its cause.

Two things decide the database state after that exception: whether the work was in a transaction, and what this particular driver does when one statement in a batch fails.

2What State Is the Database In?

If the job ran inside one @Transactional method, the exception propagates out, Spring rolls the transaction back, and none of the 50,000 rows is persisted, including the 29,999 that succeeded. That is clean: the table is exactly as before, and after fixing the cause we can rerun the whole job. In PostgreSQL, even inside the transaction nothing after the error could have succeeded anyway, because a failed statement puts the transaction in an aborted state where every further command is rejected until rollback.

If the job ran without a transaction, in auto-commit mode, the answer depends on the driver and its settings. Chunks executed before the failing one are committed. Within the failing chunk, some drivers stop at the first error, some continue with the remaining statements (MySQL Connector/J has a continueBatchOnError setting, true by default), and with batch rewriting a multi-row INSERT fails or succeeds as a whole. So rows 1 to about 29,000 may be committed, part of the failing chunk may be committed, and rows after it are missing. We have to look, not assume, and a blind rerun would hit the same duplicate keys plus the ones we created in the first run.

State after a duplicate key at row 30,000
How the job ranRows persistedSafe to rerun as is?
One transaction for all rowsnone, rolled backyes, after fixing the cause
Auto-commit, chunks of 1,000earlier chunks; part of the failing chunk depends on the driverno, duplicates again
Transaction per chunk, progress recordedchunks 1 to 29 exactlyyes, resume at chunk 30
Upsert (ON CONFLICT DO NOTHING)all valid rows; duplicate skippedyes, idempotent
Only the auto-commit job leaves a state we have to investigate by hand.

3Reading the BatchUpdateException

getUpdateCounts() returns an int per statement that the driver reports on. If the driver stopped at the failure, the array is shorter than the batch, and its length tells us how many statements succeeded before the failing one. If the driver continued, the array has an entry for every statement, with Statement.EXECUTE_FAILED, which is -3, for the ones that failed. With rewriting, entries may be SUCCESS_NO_INFO, -2, which tells us nothing about individual rows.

Java
} catch (DuplicateKeyException e) {
if (e.getCause() instanceof BatchUpdateException bue) {
int[] counts = bue.getUpdateCounts();
log.error("batch failed: {} counts reported, failed={}", counts.length,
Arrays.stream(counts).filter(c -> c == Statement.EXECUTE_FAILED).count());
// stop-at-first-error driver: counts.length == 999 -> the 1000th statement failed
// continue-on-error driver: counts.length == 1000, one entry is -3
SQLException next = bue.getNextException(); // pgjdbc puts the server's real error here
log.error("cause: {}", next != null ? next.getMessage() : bue.getMessage());
}
throw e;
}

Notice getNextException(). The PostgreSQL driver's BatchUpdateException message is often generic, along the lines of Batch entry 999 ... was aborted, and the actual server error, such as duplicate key value violates unique constraint item_sku_key with the offending key, is in the chained exception. Logging it saves a lot of guessing. Because these behaviours differ between drivers and versions, we should test our driver's behaviour once and write it down.

4Design 1: Chunks With a Transaction Each and Recorded Progress

For a job that must make progress, we commit per chunk and record which chunks are done, so a restart continues where it stopped instead of starting over.

Java
for (int c = progress.lastCompletedChunk(jobId) + 1; c < chunks.size(); c++) {
List<Row> chunk = chunks.get(c);
int chunkNo = c;
tx.executeWithoutResult(s -> {
jdbc.batchUpdate(INSERT_SQL, chunk, chunk.size(), SETTER);
progress.markDone(jobId, chunkNo); // same transaction as the data
});
}
Step throughA restartable, duplicate-tolerant load
  1. Read the next chunk of 1,000 rowsfrom the file or staging table
  2. Insert with ON CONFLICT DO NOTHINGduplicates are skipped, not errors
  3. Other rows rejected?constraint or format problems
    YesWrite them to the error tableNoContinue
  4. Commit the chunk and its progress markerone transaction
  5. More chunks?
    YesRead the next chunkNoReport counts: loaded, skipped, rejected

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

A failure loses at most one chunk, and a rerun is safe.

The key detail is that the progress record is written in the same transaction as the chunk's rows. Then the data and the progress marker always agree: either both are committed or neither is. Spring Batch implements exactly this pattern, with chunk-oriented steps, a job repository for restart state, and skip and retry policies, and is worth using for jobs that run regularly.

5Design 2: Make Duplicates Expected, Not Fatal

If duplicates are a normal part of the input, for example because files overlap or a previous run partly succeeded, the insert itself should handle them. In PostgreSQL, INSERT ... ON CONFLICT (sku) DO NOTHING skips rows that would violate the unique constraint, and ON CONFLICT ... DO UPDATE turns the insert into an upsert. MySQL has INSERT IGNORE, which also ignores other errors and should be used with care, and INSERT ... ON DUPLICATE KEY UPDATE; other databases offer MERGE, which PostgreSQL also supports since version 15.

This makes the job idempotent: running it twice gives the same result as running it once. That property is what makes reruns safe after any failure, not just duplicates. The update counts then tell us how many rows were actually inserted: 0 for a skipped row, which we can sum to report loaded versus skipped.

6Design 3: Log Rejected Rows to an Error Table

Finally, one bad row should not stop 49,999 good ones. For rows that fail for other reasons, such as a missing foreign key or a value out of range, we route them to an error table with the job id, the row's data, the error message and a timestamp. A simple approach is to validate rows in the application before the batch and divert bad ones; another is, when a chunk fails, to retry that chunk row by row in a new transaction to isolate the offenders.

At the end, the job reports three numbers: loaded, skipped as duplicates and rejected. An operator can fix the rejected rows and reload just those, and alerting can trigger when the rejected count crosses a threshold, so a systematic problem, such as a changed file format, is noticed the same morning.

7Follow-up questions

Can we rely on getUpdateCounts() to find the failing row?

Only with knowledge of the driver's behaviour. With a stop-at-first-error driver, the array length points to the failing statement; with a continue-on-error driver, the -3 entries mark the failures; with batch rewriting, a whole group fails together and the counts may be -2. That is why row-by-row retry of the failing chunk, or validation before inserting, is the reliable way to identify the bad row.

Why write the progress marker in the same transaction as the data?

If they were separate, a crash between committing the chunk and recording its progress would make a restart insert the chunk again, causing duplicates, or the reverse would skip data. In one transaction they commit or roll back together, so the marker always describes exactly what is in the table.

Is one big transaction ever the right choice?

Yes, when the load must be atomic, for example a reference table that must be either fully replaced or untouched. Then all-or-nothing is the requirement, and the cost of rerunning from the start is acceptable. For large or long-running loads, loading into a staging table and swapping or merging in one short final transaction gives atomicity without one huge transaction.

8Conclusion

In this answer, we saw that after a duplicate key at row 30,000, a single transaction leaves nothing persisted, while auto-commit leaves a driver-dependent partial state that needs investigation. getUpdateCounts() and getNextException() tell us what ran and why it failed, though drivers differ. We designed the job to be restartable with a transaction per chunk and progress recorded in the same transaction, made duplicates harmless with ON CONFLICT DO NOTHING or an upsert, and diverted bad rows to an error table so one row cannot fail the whole load.

What to say in the interviewAbout 100 seconds aloud

Open with

First I would establish how the job ran, because that decides the state. If the whole batch was in one transaction and the exception rolled it back, nothing is persisted, all fifty thousand rows are gone, and I can rerun after fixing the cause.

Then, if they want more

If it ran in auto-commit mode, earlier chunks are already committed, and what happened inside the failing chunk depends on the driver: some stop at the first error, MySQL by default continues, and with batch rewriting a multi-row insert fails as a whole.

So I would check the table rather than assume, and I would not just rerun it, because the committed rows would collide again. To see what ran, I look at BatchUpdateException's getUpdateCounts: a shorter array means the driver stopped there, and minus three entries mark failed statements.

On PostgreSQL I also log getNextException, which has the real server error with the duplicate key. Then I would redesign the job. Process it in chunks, each in its own transaction, and write a progress marker in the same transaction, so a restart resumes exactly at the failed chunk; Spring Batch does this well.

If duplicates are expected, use insert on conflict do nothing in PostgreSQL, or an upsert, which makes the job idempotent and reruns safe.

And route rows that fail for other reasons into an error table with the job id and error message, so one bad row does not stop the rest, and report loaded, skipped and rejected counts at the end.

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
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 "A batch insert of 50,000 rows fails with a BatchUpdateException at row 30,000 because of...": https://scrivio-interview-library.netlify.app/databases/jdbc/005837cf82/