How we cut our nightly batch from 4 hours to 19 minutes

Every night at 01:00 UTC, Ledgerline reconciles the previous day's card transactions against bank statements for about 9,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 71% of wall-clock time went to small round trips: one query per transaction to look up candidate matches.

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 71% of wall-clock time went to small round trips: one query per transaction to look up candidate matches.

What we changed

  1. We replaced per-transaction lookups with one bulk query per customer that pulls every candidate statement line into memory.
  2. We split customers into 64 shards and ran the shards in parallel on a worker pool.
  3. We moved the final write to a single COPY into a staging table, followed by one merge.

The fastest query is the one you only run once.

Results

MetricBeforeAfter
Wall-clock time4 h 12 min19 min
Database queries per run38 million27,000
Peak memory per worker1.1 GB2.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 15%, 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 90 minutes. We expect to ship that change in the first quarter of 2027.