Sub topic 9
Upserting Many Records in One Batch
This chapter assumes you can write a single INSERT ... ON CONFLICT DO UPDATE statement keyed on a unique (source_system, external_id) constraint. It also assumes you know what a transaction is. Here you will move from one record per statement to loading thousands of records efficiently and safely.
Why batch at all
A sync job rarely receives one customer. It receives a file or an API page with hundreds or millions of them. The simplest approach is a loop that sends one upsert per record. That works, but each statement costs a network round trip, a parse step, and, if autocommit is on, a separate commit with its own disk flush. For 100,000 rows, the round trips often dominate the total time.
Batching reduces that overhead by sending many records per round trip and committing once per group. It also changes how failures behave, so you need to decide how big a batch is and what happens when one fails.
Three ways to send a batch
| Approach | How it works | Strength | Limit |
|---|---|---|---|
| Driver `executemany` | Runs the same statement once per row, sometimes pipelined | Simplest code | Often still one round trip per row, depending on the driver |
| Multi-row `VALUES` | One statement lists many `(...)` tuples | One round trip for the whole chunk | Placeholder count grows with row count |
| Array parameters with `unnest` | Each column is passed as one array | Fixed number of parameters at any size | PostgreSQL-specific, so you must cast types |
Multi-row VALUES
Every upsert you have seen so far can take more than one tuple:
INSERT INTO customers (source_system, external_id, name, email)
VALUES
('crm', 'C-1001', 'Ada Lovelace', '[email protected]'),
('crm', 'C-1002', 'Grace Hopper', '[email protected]'),
('crm', 'C-1003', 'Edsger Dijkstra', NULL)
ON CONFLICT (source_system, external_id)
DO UPDATE SET name = EXCLUDED.name, email = EXCLUDED.email;EXCLUDED refers to the incoming row for each conflict, so one DO UPDATE clause covers every tuple. Each tuple is matched on its own. Some rows can be inserted and others updated in the same statement.
Array parameters with unnest
With multi-row VALUES, a driver needs one placeholder per value. A 1,000-row batch of four columns needs 4,000 placeholders. PostgreSQL's wire protocol allows at most 65,535 bind parameters per statement, and SQLite has its own limit that depends on version and build. Large batches can hit these limits.
Passing each column as an array avoids the problem. The statement always has three parameters here, however many rows you send:
INSERT INTO customers (source_system, external_id, name, email)
SELECT 'crm', t.external_id, t.name, t.email
FROM unnest($1::text[], $2::text[], $3::text[])
AS t(external_id, name, email)
ON CONFLICT (source_system, external_id)
DO UPDATE SET name = EXCLUDED.name, email = EXCLUDED.email;$1 is the array of external IDs, $2 the array of names, and $3 the array of emails. unnest with several arrays walks them in parallel, so position n in each array forms row n. The arrays must have the same length, and a missing email is a NULL element in its array. The explicit casts, such as ::text[], let PostgreSQL choose the right types when the driver sends untyped values.
Choosing a batch size
Bigger batches mean fewer round trips, but the gains flatten out. A very large batch has costs of its own:
- It holds locks on every row it touches until commit, which can block other writers.
- If it fails, the database rolls back all of it and you redo the work.
- It uses more memory on the client and the server.
A chunk of a few hundred to a few thousand rows is a reasonable starting point. Measure with your own row width and network latency, then pick a size and keep it configurable.
One transaction per chunk
The usual pattern is to split the input into chunks and run each chunk in its own transaction. A failure then rolls back only the chunk in progress. Chunks already committed stay in place.
This design is only safe because the load is idempotent. If a job fails after chunk 7, you can rerun it from the start. Chunks 1 to 7 are upserted again with the same values and nothing duplicates. The rerun also fixes the failed chunk. Without the unique constraint, this recovery would create duplicates.
If the whole load must succeed or fail as one unit, use a single transaction instead. The cost is the long-held locks and the full rollback described above.
A complete runnable example
This script chunks 1,200 records, upserts each chunk in its own transaction, and runs the whole load twice. It uses SQLite so it runs anywhere with SQLite 3.24 or later, but the structure is the same for PostgreSQL.
import sqlite3
from itertools import islice
def chunks(items, size):
it = iter(items)
while batch := list(islice(it, size)):
yield batch
SQL = (
"INSERT INTO customers (source_system, external_id, name) "
"VALUES ('crm', ?, ?) "
"ON CONFLICT (source_system, external_id) "
"DO UPDATE SET name = excluded.name"
)
def load(conn, records, chunk_size=500):
for batch in chunks(records, chunk_size):
with conn: # one transaction per chunk: commit, or roll back on error
conn.executemany(SQL, batch)
conn = sqlite3.connect(":memory:")
conn.execute(
"CREATE TABLE customers ("
"id INTEGER PRIMARY KEY, "
"source_system TEXT NOT NULL, "
"external_id TEXT NOT NULL, "
"name TEXT NOT NULL, "
"UNIQUE (source_system, external_id))"
)
records = [(f"C-{1000 + i}", f"Customer {i}") for i in range(1200)]
load(conn, records)
print(conn.execute("SELECT COUNT(*) FROM customers").fetchone()[0]) # 1200
load(conn, records) # rerun: updates every row, inserts none
print(conn.execute("SELECT COUNT(*) FROM customers").fetchone()[0]) # 1200The with conn: block commits when it exits normally and rolls back if an exception escapes it. The second call to load leaves the count at 1200, which is the idempotency check from the earlier chapter applied to a batch.
Telling inserts from updates
A batch statement reports one row count, and it does not split that count into inserts and updates. If you need the split for logging, ask the statement to return it. In PostgreSQL, RETURNING can include a flag:
INSERT INTO customers (source_system, external_id, name)
VALUES ('crm', 'C-1001', 'Ada Lovelace'),
('crm', 'C-2000', 'New Person')
ON CONFLICT (source_system, external_id)
DO UPDATE SET name = EXCLUDED.name
RETURNING id, external_id, (xmax = 0) AS inserted;xmax is a system column. It is zero on a freshly inserted row version and non-zero on a row that the conflict path updated. This behavior is an implementation detail of PostgreSQL, not a documented guarantee, so use it for reporting only and never for business logic.
RETURNING is also how you map each external ID back to its internal id, for example before inserting child rows that reference the customer.
Rows that are skipped still count differently
A DO UPDATE with a WHERE clause, such as the stale-data guard from a later chapter, skips rows that fail the condition. Skipped rows are not counted as affected and do not appear in RETURNING. If you compare "rows sent" with "rows affected", the difference is the number of skipped rows. Do not treat it as an error without checking why.
Two things that break batches
Duplicate keys inside one batch
If two tuples in the same statement carry the same (source_system, external_id), PostgreSQL rejects the statement with an error like "ON CONFLICT DO UPDATE command cannot affect row a second time". A statement may not modify the same row twice. Using executemany with one statement per row avoids this error, but the last row silently wins. Deciding which duplicate should win is a separate topic covered in its own chapter, so for now treat this error as a sign that your input has duplicates.
Unnormalized IDs
'C-1001' and 'c-1001 ' are different strings and so produce two rows. Normalize external IDs before they enter the batch, not inside the database after the fact.
Ordering and lock contention
If two loaders upsert overlapping keys in different orders, each can hold a row lock that the other needs, and PostgreSQL will abort one with a deadlock error. Sorting each batch by (source_system, external_id) before sending it makes every writer take locks in the same order, which prevents this. Sorting costs little and is worth doing for any job that may run alongside another writer.
Practical checklist
- Keep the unique constraint. Batching speeds up the statement but does not replace the constraint that makes the match reliable.
- Normalize IDs before building the batch.
- Chunk the input, with one transaction per chunk.
- Send each chunk as multi-row
VALUESor as arrays throughunnest. - Sort each chunk by the key.
- Make the chunk size configurable.
- Log rows sent, rows affected, and rows skipped.
Exercise
A loader sends 5,000 customers per statement as multi-row VALUES with four columns each. It fails on a PostgreSQL server with a "too many parameters" style error. Name two changes that would fix it without changing the table design, and say what you would also change to avoid long-held locks.
Show answer
Reduce the chunk size so rows times columns stays below 65,535 bind parameters (for example, 1,000 rows of 4 columns is 4,000 parameters). Or switch to array parameters with unnest, which uses one parameter per column regardless of row count. To avoid long-held locks, commit once per chunk instead of one transaction for the whole load, and sort each chunk by (sourcesystem, externalid) so concurrent writers take locks in the same order.