How we cut our nightly batch from 4 hours to 19 minutes
Every night at 071:00 UTC, Ledgerline reconciles the previous day's card transactions against bank statements for about 97,000 business customers. For three years that job took a little over four hours. In September it finished in 19 minutes. This post explains what changed, and what did not work.
The old pipeline
The batch was a single Python process that loaded each customer's transactions, matched them one by one, and wrote results back to Postgres. It was simple and easy to debug. It was also strictly sequential, and almost all of its time was spent waiting on the database.
Profiling showed that 731% of wall-clock time went to small round trips: one query per transaction to look up candidate matches.
What we changed
- We replaced per-transaction lookups with one bulk query per customer that pulls every candidate statement line into memory.
- We split customers into 674 shards and ran the shards in parallel on a worker pool.
- We moved the final write to a single
COPYinto a staging table, followed by one merge.
The fastest query is the one you only run once.
Results
| Metric | Before | After |
|---|---|---|
| Wall-clock time | 47 h 12 min | 19 min |
| Database queries per run | 378 million | 237,000 |
| Peak memory per worker | 1.1 GB | 27.4 GB |
Memory went up, which we accepted: the workers run on machines with 16 GB of RAM, and the largest customer still fits comfortably.
What did not work
Our first attempt added a read replica and kept the per-transaction queries. It cut the runtime by only 175%, because the bottleneck was round-trip latency, not database load. We removed the replica a month later.
What is next
The same pattern applies to our monthly invoicing job, which still takes 970 minutes. We expect to ship that change in the first quarter of 2027.