How to Reduce Database Round Trips with Batching
Cut database round trips: batch inserts and updates in one statement, chunk large batches, and measure the round trips per request.
On this page
Introduction
A database round trip costs a network hop, a parse, a plan, and a wait, and a loop that issues one query per row pays all of that per row. Inserting a thousand rows one statement at a time is a thousand round trips, each far more expensive than the tiny amount of work it does. Batching the same rows into one statement turns a thousand trips into one, and the cost drops by the round trip count rather than the row count.
This tutorial finds the per-row loops, batches them into single statements, chunks very large batches so each statement stays efficient, and measures the round trips per request. The examples use SQL with PostgreSQL and a Node.js client, but the batching logic applies to any database.
Find the per-row round trips
The signature is a loop that issues a query inside it, one call per element. Look for awaits inside a for loop, a forEach that returns a promise, or an ORM that lazily loads per row. Count the database calls per request and check whether the count grows with the number of rows, which is the same signature as the N+1 pattern applied to writes.
Once you find them, the batching opportunity is often large. A loop inserting child rows, updating a status per row, or reading a detail per parent all become one statement each. The fix is not a faster query but fewer queries, and the gain scales with the number of rows, so it is largest exactly where the load is highest.
// one round trip per row: a thousand inserts are a thousand trips
for (const row of rows) {
await db.query('INSERT INTO events (id, type) VALUES ($1, $2)', [row.id, row.type]);
}
// one round trip for all rows
const ids = rows.map((r) => r.id);
const types = rows.map((r) => r.type);
await db.query(
'INSERT INTO events (id, type) SELECT * FROM unnest($1::bigint[], $2::text[])',
[ids, types],
);
Batch into a single statement
The batch mechanism depends on the database. PostgreSQL can insert from an array with unnest, or from a values list, so one statement writes many rows. A prepared statement with an array parameter is a clean way to pass a batch. For updates, a single statement with a values list joined to the target table updates many rows at once. For reads, a single query with an IN over the keys fetches all the details.
Choose the mechanism that keeps the SQL readable and the parameters typed. unnest with array parameters is compact and avoids building a large SQL string with many placeholders. A values list is portable but grows the statement text. Whatever the mechanism, keep it parameterized so the batch does not introduce SQL injection through concatenated values.
-- batch update in one statement: join the batch to the target table
UPDATE accounts a
SET balance = b.balance
FROM (VALUES (1, 100), (2, 250), (3, 0)) AS b(id, balance)
WHERE a.id = b.id;
-- batch read: all details for a set of parent keys in one query
SELECT child_id, detail FROM details WHERE parent_id = ANY($1::bigint[]);
Chunk very large batches
A single statement with a hundred thousand rows can be slow to plan, can exceed a parameter limit, and holds its locks for the whole duration, blocking concurrent writes. Chunk the batch into pieces that keep each statement efficient. A few thousand rows per statement is often a good balance; measure the plan time and the lock duration to choose.
Run the chunks within a transaction if the whole batch must be atomic, or one transaction per chunk if a partial failure is acceptable and you can resume. Chunking also lets you report progress and throttle, so a very large load does not flood the database or the network. The round trip count becomes the number of chunks, which is small and predictable, rather than the number of rows.
function chunk(arr, size) {
const out = [];
for (let i = 0; i < arr.length; i += size) out.push(arr.slice(i, i + size));
return out;
}
for (const part of chunk(rows, 2000)) { // bounded chunks, a few round trips
await insertBatch(part);
}
Combine with connection and statement reuse
Batching reduces the number of statements, and connection reuse reduces the setup per statement. Together they cut both the count and the cost of each round trip. Use a pooled connection so each batch does not pay a handshake, and, where the driver supports it, a prepared statement so the parse and plan are reused across the repeated batch shape.
For a very large load, a bulk-copy mechanism can be faster than a batched insert, because it streams the data to the server in one direction with less per-row overhead. Use it when the volume justifies the extra complexity, and keep the batched insert for the common case where a few thousand rows need to be written quickly without a separate copy pipeline.
Measure round trips per request
Instrument the data layer to count statements per request, then assert the count is small and does not grow with the number of rows. A count that doubles when the rows double means the loop is still issuing per-row queries. Track it as a metric so a regression that reintroduces a loop is caught.
# count statements for a request with 10 rows and with 1000 rows: should be constant
DB_LOG=1 node server.js &
curl -s -X POST -d @10-rows.json http://localhost:3000/import >/dev/null
curl -s -X POST -d @1000-rows.json http://localhost:3000/import >/dev/null
grep -c 'INSERT INTO events' server.log # expect a small constant, e.g. 1 or a few chunks
Test batching and atomicity
Test that importing N rows issues a constant number of statements rather than N. Test that the rows are all present and correct after the batch, which catches a batch that silently drops rows. Test that a failure in a chunk rolls back as intended if the batch must be atomic. Test that a large batch is chunked and each chunk completes.
psql -d app -c "SELECT count(*) FROM events;" # equals the number of imported rows
# assert no duplicate row when the same batch is retried (idempotent insert)
Common pitfalls
A loop issuing one query per row, a batch so large it is slow to plan or exceeds a parameter limit, concatenating values into SQL instead of parameterizing, no connection reuse so each batch pays a handshake, and never measuring the statement count so a loop re-enters are the recurring mistakes. Batching into one statement with unnest or values, chunking large batches, parameterizing, connection reuse, and a statement-count metric address them.
Conclusion
A round trip is expensive, and a per-row loop pays it per row. Find the loops, batch into a single statement with unnest or a values list, chunk very large batches, and reuse connections and prepared statements. Self-check by asserting the statement count is constant as rows grow. Then the cost of a bulk operation drops to the number of batches, not the number of rows.
Sources: PostgreSQL: Multi-row VALUES and unnest, PostgreSQL: Copy for bulk load, Node.js: pg and batch inserts.
FAQ
- Is one big statement always better?
- No. A very large statement can be slow to plan, exceed a parameter limit, and hold locks longer. Batch into chunks of a size that keeps each statement efficient, then run a few chunks rather than one giant one.
- Does a transaction reduce round trips?
- It reduces commit round trips, not statement round trips. A transaction wraps several statements in one commit, but each statement is still a round trip. You still need to batch the statements themselves to cut the per-row trips.
Report a problem with this articleOpens a pre-filled issue on GitHub.