Batch operations

Round trips are the cost. addBatch, chunk size, what a batch failure tells you, and the driver settings that are off by default.

9 min read🐘 Relational Databases in Depth

Inserting five thousand rows one statement at a time is five thousand round trips. The rows are trivial, the database is idle, and the job takes minutes — because almost none of the time is spent inserting anything.

Batching replaces the round trips, and it is the single largest win available in any code that writes many rows.

The measurement, and its honest caveat

java
try (PreparedStatement ps = c.prepareStatement("insert into event values (?, ?)")) {
    for (int i = 0; i < N; i++) {
        ps.setInt(1, i);
        ps.setString(2, "payload-" + i);
        ps.addBatch();
        if (i % 500 == 499) ps.executeBatch();   // flush in chunks
    }
    ps.executeBatch();                            // the remainder
}
plaintext
### 5000 inserts, one executeUpdate each :     48 ms
### 5000 inserts, addBatch in 500s       :     21 ms
### speedup                              : 2.3x
### rows now in the table                : 5000

Now the caveat, because 2.3× dramatically understates it. That ran against an in-memory H2 in the same process — there is no network in that measurement, and the network is what batching removes. Against a Postgres one millisecond away, five thousand individual inserts spend five seconds purely waiting, and the same batched loop finishes in a fraction of it. Reported speedups of 10× to 50× over a real connection are ordinary.

Which is the useful way to think about it: batching does not make the database faster. It stops you waiting. The gain is proportional to your round-trip time, so it is smallest on a laptop and largest in the environment you actually care about.

Flush in chunks, not at the end

addBatch() accumulates in the driver's memory. Batching all five thousand and calling executeBatch() once builds one enormous packet and holds every parameter set in the heap.

Chunks of 500 to 1000 is the usual advice, and the reason is not superstition: it bounds memory, it keeps a single failure from invalidating the whole job, and past a certain size the round-trip saving is already taken. Going from 1 to 500 is where the win is; going from 500 to 5000 buys almost nothing and costs memory.

Batching and transactions are separate decisions

They are easy to conflate and they do different things:

  • Batching controls how many round trips you make.
  • The transaction controls what is atomic.

With autocommit on, each executeBatch() commits — so a job that fails halfway leaves half the rows. Usually you want one transaction around the whole thing, or one per chunk with a way to resume:

java
c.setAutoCommit(false);
// ... batches ...
c.commit();

One transaction over a million rows is its own problem, though: it holds locks for the duration and generates a lot of undo or WAL. For a genuinely large import, a transaction per chunk with a recorded high-water mark beats both extremes.

When one statement fails

executeBatch() returns an int[] of update counts, and on failure throws BatchUpdateException — which carries the counts for the statements that did succeed, so you can tell how far it got.

The part that catches people: what the driver does with the rest is not guaranteed. Some stop at the failure; others continue and report the failed ones with Statement.EXECUTE_FAILED. If your recovery depends on knowing, test it against your actual driver rather than assuming, and remember getNextException() — the useful message in a batch failure is frequently further down the chain than the first one.

Rewriting, which is the other half on some drivers

addBatch sends many statements in one round trip. Some drivers can do better and send one statement with many value tuples:

sql
insert into event values (1,'a'), (2,'b'), (3,'c'), ...
  • PostgreSQL — reWriteBatchedInserts=true in the JDBC URL. It is off by default and is frequently a large additional win for inserts.
  • MySQL — rewriteBatchedStatements=true, same idea.

Both are connection-string settings, both apply only to inserts, and both are worth checking before concluding that batching "did not help much".

From JPA

Hibernate batches too, and it is off by default, which surprises people who assume saveAll is doing something clever:

properties
spring.jpa.properties.hibernate.jdbc.batch_size=50
spring.jpa.properties.hibernate.order_inserts=true
spring.jpa.properties.hibernate.order_updates=true

Two things stop it working even when configured, and both come straight from the JPA course:

  • GenerationType.IDENTITY disables insert batching entirely. Hibernate must know the id after each insert, so it cannot defer them. A sequence generator with an allocation size can.
  • The persistence context keeps every entity you touch. Inserting a hundred thousand rows through entities means a hundred thousand managed objects and their snapshots. flush() and clear() periodically — or do not use entities for a bulk import, which is usually the better answer.

Under the hood: what addBatch/executeBatch actually send, and two different ways to reduce round trips

addBatch() does not touch the network. It appends the current bound parameter values to a list the PreparedStatement keeps in the driver's memory, against the SQL text prepared once when the statement was created. Nothing goes out until executeBatch() — which is the whole reason chunking matters for memory, as the section above says.

What happens on executeBatch() is where "reduces round trips" gets more specific, and it happens in one of two genuinely different ways, and which one you get depends on the driver:

  • Batching execute messages into fewer round trips. The driver still asks the database to run the statement once per row, but it packs many "execute with these parameters" messages into far fewer TCP writes/reads than one-request-per-row would need, and reads the acknowledgements back as a group. This is what plain JDBC batching gives you on essentially every driver, with no special configuration: the database still does N logical executions, but your application does not pay N network round trips waiting for each one before sending the next.
  • Rewriting into fewer statements, not just fewer round trips. Some drivers can go further and rewrite a batch of single-row inserts into one genuinely different SQL statement with many value tuples — insert into event values (1,'a'), (2,'b'), (3,'c') — which is one statement for the database to parse and plan instead of N. This is the reWriteBatchedInserts/rewriteBatchedStatements behavior mentioned above; it is a driver-specific rewrite on top of ordinary batching, restricted to inserts, and it is why turning it on is often described as "the other half" of the win — it is a different mechanism from batching itself, not a bigger version of it.

Both reduce round trips. Only the second reduces the number of statements the database has to parse and plan. Plain JDBC batching (the first kind) is close to universal; the rewrite behavior is driver-specific, worth checking rather than assuming, and easy to overstate for a driver you have not verified it on.

Try it yourself

Count the round trips, individual vs. batched

A job inserts 2,000 rows, either one executeUpdate() per row, or addBatch() for every row with executeBatch() called every 500 rows (flushing whenever the count reaches a multiple of 500, plus once more at the end if anything is left over).

java
int rows = 2000;
int chunkSize = 500;
 
int individualRoundTrips = rows; // one executeUpdate() per row
 
int batchedRoundTrips = rows / chunkSize; // a flush every time the chunk fills exactly
if (rows % chunkSize != 0) batchedRoundTrips++; // plus one more for a leftover partial chunk
 
System.out.println("individual round trips: " + individualRoundTrips);
System.out.println("batched round trips: " + batchedRoundTrips);

If the chunk size were 700 instead of 500 for the same 2,000 rows, how many batched round trips would there be, and why does the remainder matter?

Three full chunks would overshoot — it's two full chunks plus one partial flush

2000 / 700 is 2 (integer division, two full chunks of 700 = 1400 rows), with a remainder of 600 rows still unflushed — so rows % chunkSize != 0 is true and one more round trip is needed for that leftover partial batch, giving 3 round trips total, not 2. This is exactly the if (i % 500 == 499) ps.executeBatch() plus the final unconditional ps.executeBatch() in the code example earlier in this lesson: the loop only flushes on exact multiples of the chunk size, so unless the row count divides evenly, the last chunk is smaller than the rest and needs its own explicit flush after the loop — forgetting that final call silently drops the leftover rows, since they were added to the batch but never executed.

Misconceptions

  • "Batching and reWriteBatchedInserts/rewriteBatchedStatements are the same optimisation, so turning one on gets you the other." They are separate mechanisms, as the section above lays out: plain batching reduces round trips while the database still runs one statement per row; the rewrite flag additionally collapses those into fewer statements. A driver without the rewrite flag (or with it off) still benefits from batching — just not by as much, and not for the reason the flag would add.
  • "executeBatch() guarantees the driver actually sent fewer network packets." It guarantees fewer round trips your code waits on — the driver decides how to pack the underlying network writes, and that packing is implementation detail, not a JDBC contract. What the spec commits to is the batch semantics (accumulate, then execute as a unit, with the int[]/exception behavior described above) — not a specific wire-level encoding.

Sources

  • Java SE documentation — java.sql.Statement#addBatch, #executeBatch, java.sql.BatchUpdateException.
  • PostgreSQL JDBC driver (pgjdbc) documentation — the reWriteBatchedInserts connection parameter.
  • PostgreSQL documentation — COPY.
  • Vlad Mihalcea, "The best way to do JDBC batch inserts" (JDBC/Hibernate batching writing).
Progress is saved on this device and to your account when signed in.