We built an LLM expense scanner as a two-call pipeline: a cheap gpt-4o-mini pass reads each email's subject and body, then a gpt-4o Vision pass reads the attachment image directly and classifies it. Twenty concurrent workers fed from a single IMAP fetch processed 574 emails in 1.6 minutes, about 6 emails per second, at $0.004 per email with an attachment.

Those numbers come from our own logged production runs, not a benchmark harness. The system has run on a 5-minute timer since February 2026, and a later 1,800-email backfill showed what happens to unit cost when you change one design decision. Both stories are below, with the real numbers.

What does the expense scanner actually do, end to end?

The scanner reads a shared business inbox without marking anything as read, skips any email it has already seen by Message-ID, runs new emails through a two-step LLM workflow, stores the structured result in PostgreSQL, and routes detected receipts and supplier invoices to the bookkeeping destination. A Flask dashboard shows every decision and lets a human retry any email.

The pipeline has five stages, and only two of them involve a model:

every 5 minutes (systemd timer):
  ids      = imap.search(folder)                 # newest N only
  for each id:
      raw  = imap.fetch(id, BODY.PEEK[])         # never sets \Seen
      mid  = message_id(raw) or hash(date+from+subject)
      if db.seen(mid): skip
      img  = first_attachment(raw) or render(email_html -> png)
      r1   = mini_model(subject, body)           # is this an expense?
      r2   = vision_model(img)                   # classify + extract fields
      db.store(mid, r1, r2, tokens, cost_usd)
      if r2.is_expense: route(r2.type, raw)

Every workflow execution logs its duration, token count, and dollar cost on one line. That single log line is what made every number in this post possible. Without per-call cost telemetry you are guessing at unit economics, and guessing is how LLM pipelines quietly get expensive.

Why did we drop OCR and go from three LLM calls to two?

We dropped OCR because a Vision model reading the receipt image directly does extraction and classification in one call, while the OCR path needed a text-extraction stage plus two text-only LLM calls. The rebuild cut the workflow from three model calls to two and removed three dependencies. The catch: our cost model put each attachment email 64% more expensive.

Version 2 of the workflow ran pytesseract and a PDF text extractor, then fed the text to gpt-4o-mini for analysis and again for classification. Version 3 sends the base64 image straight to gpt-4o with a strict JSON schema. Our own cost model put the text path at $0.0025 per attachment email and the Vision path at $0.0041.

We chose the more expensive path deliberately. OCR is the stage that degrades on phone-photographed receipts, rotated scans, and mixed Swedish/English invoices, and in a bookkeeping pipeline every extraction failure becomes a manual task. Paying an extra $0.0016 per receipt to remove the most fragile stage is an easy trade when a human correction costs minutes.

Both calls use OpenAI's Structured Outputs with a strict JSON schema, not the older JSON mode. Vendor, amount, currency, invoice number, date, expense type, and confidence come back as typed fields that go straight into the database. We sized max_tokens per node (400 for the detection step, 2,000 for Vision) because a truncated structured response is a silent failure, a lesson we have written up separately in what 97 failed LLM JSON calls with finish_reason='length' actually looked like.

How did we get to 574 emails in 1.6 minutes?

We separated I/O from inference. One thread fetches every message over a single IMAP connection first, then a ThreadPoolExecutor with 20 workers runs the LLM workflow concurrently, each worker holding its own database session. At about 6 emails per second and two calls per email, that is roughly 720 requests per minute, far below the rate limit.

The sequential prototype this replaced was measured in emails per minute, not per second. The bottleneck was never compute. It was waiting on two network round trips to the model per email, one email at a time.

Three constraints shaped the concurrency design:

  • IMAP connections are not safe to share across threads. Fetching everything up front on one connection avoided both connection-per-worker overhead and the mailbox-server connection limits you hit when 20 workers each log in.
  • Database sessions are per worker. A shared SQLAlchemy session across threads produces the kind of intermittent corruption that only shows up under load.
  • Shared counters are locked. Totals for cost, expenses found, and errors are updated under a lock so the end-of-run summary is actually correct.

We considered 50 workers and ruled it out. At that level, two calls per email puts a full-inbox scan in the territory of 3,000 requests per minute against a tier limit of 5,000, which leaves no headroom for retries with exponential backoff. Twenty workers was the point where throughput stopped being the problem.

Why do IMAP PEEK and Message-ID dedup matter more than the model?

Because the scanner shares a mailbox with humans and runs 288 times a day. Fetching with BODY.PEEK leaves the read flag untouched, so people still see their unread mail. Deduplicating on Message-ID makes every run idempotent: a crash, a restart, or an overlapping backfill can never double-file a receipt or double-charge a model call.

In the IMAP specification (RFC 3501), a plain BODY[] fetch implicitly sets the \Seen flag, while BODY.PEEK[] does not. A scanner that uses the plain form silently marks every invoice in a shared inbox as read, which is how bookkeeping emails get missed by the humans who also rely on that inbox.

Message-ID is the dedup key, but it is not guaranteed. RFC 5322 says every message SHOULD carry one, not MUST. In our 1,800-email backfill, 6 emails arrived without one. For those we generate a deterministic key from a hash of date, sender, and subject, so the same email still maps to the same key on the next run.

The dedup layer is also what made the backfill cheap to restart. Of the 1,800 emails it checked, 324 had already been processed by the timer and were skipped before any model call, at zero cost.

What did the 1,800-email backfill cost, and why was it higher than $0.004?

The backfill processed 1,476 new emails through 1,506 workflow runs for $30.78 total: a median of $0.014 per run, a p95 of $0.042, and a worst case of $0.115. That is roughly 3.5 times the original $0.004, and the cause was one later design change: rendering every attachment-less email to an image and sending it through Vision.

That change was made for a good reason. Many SaaS and card-payment receipts arrive as HTML email bodies with no attachment. The scanner detected them correctly but had nothing to file, so we added an HTML-to-PDF-to-PNG render at 150 DPI and filed the image as the receipt. We covered why plain-text extraction was not enough in when SaaS receipts arrive as HTML emails and break your expense automation. In the backfill, 1,429 emails took that render path.

The side effect: the Vision step was gated on "has an image," and now every email had one. The cheap gpt-4o-mini gate still ran, but it no longer decided anything. The numbers make the cost of that visible:

  • 88 of 1,506 runs (about 6%) were actual expenses. The other 94% of Vision spend confirmed that newsletters, notifications, and health-check emails were not receipts.
  • 12 runs skipped Vision and cost about $0.0002 each, roughly 70 times cheaper than the median run.
  • Median latency was 4.6 seconds per email, with a p95 of 9.5 seconds, consistent with two network calls where the second carries an image.

The fix is to gate the render and the Vision call on the first step's verdict, not on whether an image exists. The general lesson is the one we keep relearning across LLM pipelines: the cheap model is only a cost control if it is allowed to say no.

Two rendering gotchas are worth knowing. First, HTML emails reference inline images with cid: URLs that point to other MIME parts, and an HTML renderer treats them as unknown URL schemes: the backfill logged 696 such errors. The receipt text still rendered and the model still read it, but logos were missing from the filed PNG.

Second, and more important: a renderer with network access fetches remote images, and marketing emails are full of tracking pixels. Rendering an email can register as an "open" with the sender. The backfill logged 193 failed or timed-out remote image fetches, and the successful ones were never logged at all. A receipt renderer should block remote fetches by default.

What happens after an expense is detected?

The scanner routes each expense by type: receipts and supplier invoices go to different destinations because bookkeeping treats them differently. That destination changed once in production, from a direct accounting-system API upload to SMTP forwarding plus filing into a mailbox folder, and the classification layer did not need to change at all.

At launch, the scanner uploaded files to a Swedish accounting platform's API, with receipts and supplier invoices sent to separate inboxes and OAuth tokens refreshed automatically. About seven weeks later the bookkeeping workflow moved, and we replaced the upload with an email forward to the accountant and an expense platform, plus an IMAP copy into a Receipts folder.

That migration was cheap because the LLM output was a typed classification, not a destination. If we had baked "upload to system X" into the prompt or the schema, the migration would have meant re-validating the model's behavior. Keeping the model responsible for what a document is, and plain code responsible for where it goes, is a separation we now apply to every document pipeline.

Did it actually catch the receipts?

For most transactions, yes, and the gaps taught us more than the hits. A manual reconciliation of 74 bank transactions from April to July 2026 ended with receipts filed for 59. Seven had only a booking confirmation with no price shown. The remaining eight had no emailed receipt at all: in-store card payments, taxi rides, and an unmatched refund.

That reconciliation reset how we think about the ceiling on systems like this. The scanner's recall is bounded by the inbox it watches, not by the model. Ride-hailing "pending" charges, rail bookings, and hotel confirmations often arrive without a final amount, and several of the 59 receipts had to be pulled from vendor billing consoles or a second mailbox. No prompt fixes a receipt that was never emailed to the address being scanned.

The practical outcome is a different division of labor. The scanner handles the high-volume digital receipts automatically, and the human effort concentrates on the short list of card transactions with no matching email, which is exactly the list a bank reconciliation produces.

How does it run day to day?

It runs as a oneshot systemd service on a 5-minute timer, with persistence so missed runs catch up after a reboot. Each run fetches at most the 50 newest emails, and on a typical day most runs process zero or one new email. The concurrent path exists for backfills; the timer path stays sequential on purpose.

We kept the scheduled path simple because concurrency buys nothing when there is one email to process, and every worker pool is another thing to debug at 2 a.m. The 20-worker executor earns its keep when someone connects a new mailbox or replays months of history, and that is the only time it runs.

The Flask dashboard is the operational surface: a list of every processed email with its classification, confidence, extracted fields, and cost, a retry button for any failed or misclassified email, a health check that flags a stalled scanner, and a four-week chart of uploads. Most weeks, nobody opens it. That is the point.

What is the reusable pattern for LLM document intake in 2026?

An LLM expense scanner that holds up in production is mostly not an LLM problem. The pattern is: non-destructive, idempotent ingestion; a cheap model that is genuinely allowed to gate the expensive one; Vision instead of OCR for messy documents; concurrency only where volume justifies it; and per-call cost telemetry from day one.

The headline numbers, 574 emails in 1.6 minutes at $0.004 each, came from getting those boring parts right. The backfill numbers, a median of $0.014 once every email went through Vision, came from one reasonable feature quietly bypassing the gate. Both are worth knowing before you build one, and the second is the one that shows up on the invoice.