Algorithms and Design for Real Data
The first version of the matching step compared every invoice with every shipment. On a 50-invoice sample it finished instantly. On a real month, 6,000 invoices against 200,000 shipment records, it crawled, and it would only get slower as the data grew. Real customer data is bigger and messier than any demo, and it punishes careless algorithms and fragile designs.
The rule
Index once, look up fast; assume every step can fail and repeat.
The algorithm. Comparing each of 6,000 invoices with each of 200,000 shipments is 6,000 × 200,000 = 1.2 billion comparisons. Instead, build a dictionary keyed on carrier and LR number once, then look each invoice up:
by_key = {(s.carrier, s.lr_number): s for s in shipments} # built once
for inv in invoices: # 6,000 look-ups
shipment = by_key.get((inv.carrier, inv.lr_number)) # fast on average
if shipment is None:
flag(inv, "no matching shipment")That is about 206,000 steps instead of 1.2 billion. The work now grows in step with the data instead of multiplying.
The design. The pipeline has stages: fetch mail → read the invoice → match → check rates → review queue. In real life the mail server times out, the invoice-reading service limits how many requests you may send, and carriers resend the same invoice. So:
- Queues between stages, so a slow stage makes work wait instead of losing it.
- Retries with growing waits for temporary failures.
- Idempotency. Each invoice is recorded under a key, carrier plus invoice number, and a key already seen is not processed again. Handling it twice has the same effect as handling it once.
- A dead-letter queue. After a few failed attempts, the item is parked with its error for a person to look at, instead of being retried forever.