Sub topic 9
Upserting Many Records in One Batch
This chapter assumes you can write a single INSERT ... ON CONFLICT statement and that customers has a unique constraint on (source_system, external_id). Here you will apply that statement to many records at once.
Why batch
Real syncs move thousands of records. Sending one statement per record costs a network round trip each time, and each statement commits separately. A batch sends many rows in one call, so the load runs faster and you control where transactions begin and end.
One statement, many rows
PostgreSQL accepts several rows in one VALUES list. The conflict rule applies to each row separately.
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', 'Alan Turing', '[email protected]')
ON CONFLICT (source_system, external_id)
DO UPDATE SET name = EXCLUDED.name, email = EXCLUDED.email
RETURNING id, external_id;Rows that are new get inserted. Rows that already exist get updated. RETURNING gives back one line per row that was inserted or updated, so you can map each external ID to its internal id.
Chunking from a script
Do not build one statement from a million rows. Large statements use a lot of memory, and a single bad row then fails the whole load. Split the input into chunks and write each chunk in its own transaction.
This Python example uses SQLite, which supports the same ON CONFLICT syntax (version 3.24 or later), so you can run it anywhere.
import sqlite3
def chunks(items, size):
for i in range(0, len(items), size):
yield items[i:i + size]
conn = sqlite3.connect(":memory:")
conn.execute(
"CREATE TABLE customers ("
"id INTEGER PRIMARY KEY, "
"external_id TEXT NOT NULL UNIQUE, "
"name TEXT NOT NULL)"
)
sql = (
"INSERT INTO customers (external_id, name) VALUES (?, ?) "
"ON CONFLICT(external_id) DO UPDATE SET name = excluded.name"
)
rows = [(f"C-{n}", f"Customer {n}") for n in range(1, 2501)]
def load(rows):
for chunk in chunks(rows, 1000):
with conn: # one transaction per chunk
conn.executemany(sql, chunk)
load(rows)
print(conn.execute("SELECT COUNT(*) FROM customers").fetchone()[0]) # 2500
load(rows)
print(conn.execute("SELECT COUNT(*) FROM customers").fetchone()[0]) # 2500The second run leaves the count at 2500. That is the idempotency from the earlier chapter, now applied to a batch.
Choosing a chunk size
- Chunks of 500 to 5,000 rows are a common starting point. Measure with your own data.
- Smaller chunks lose less work when one fails. Larger chunks make fewer round trips.
- PostgreSQL drivers limit the number of bound parameters in one statement. Four columns per row means a 1,000-row chunk uses 4,000 parameters.
Failure and reruns
Chunks that already committed stay committed. Only the failing chunk rolls back. Because the upsert is idempotent, you can rerun the entire load after fixing the problem. The committed chunks are matched and rewritten with the same values, and the failed chunk is inserted for the first time.
Exercise
A load of 10,000 rows runs in 10 chunks of 1,000 rows, each in its own transaction. Chunk 7 fails on a bad value. What state is the table in, and how do you recover safely?
Show answer
Chunks 1 to 6 are committed, and chunk 7 is rolled back. Chunks 8 to 10 were never run. Fix the bad value and rerun the whole load. The upsert is idempotent, so chunks 1 to 6 are matched on their external IDs and rewritten with the same values, with no duplicates. Chunks 7 to 10 are inserted normally.