samodra

2 min read

Replacing Gmail polling with email forwarding

For a while, my expense tracker looked for new receipts by checking Gmail once an hour. A scheduled job asked Gmail whether there was anything new, picked up whatever had arrived, and recorded it.

It worked. It also felt inefficient, because the app kept going back to ask “any new email?”, and most of the time the answer was no.

Before: the app asks

every hour:
  app  ->  Gmail   "any new receipts?"
  app  <-  Gmail   emails (or nothing)
  app  ->  record transactions

Polling has a built-in delay. A receipt that arrives right after a check waits for the next one, so a transaction can show up an hour late.

After: the email is pushed

I brainstormed the problem with an LLM, and the result was to reverse the direction of the flow. Now Gmail forwards each receipt to my backend through Cloudflare Email Routing, and the app only has to wait for the email to arrive.

A five-step diagram: the app generates a receipt address and registers it to a wallet, Gmail auto-forwards matching receipts to that address, Cloudflare receives the email and sends its content to the backend, the backend parses the receipt and stores the transaction, and the wallet is updated and a Telegram notification is sent

The flow, step by step:

  1. Generate an address and register it. The app creates a receipt email address and registers it to a wallet.
  2. Set up Gmail auto-forward. A Gmail filter matches receipt emails (by sender, for example) and forwards them to that address.
  3. Email to Cloudflare. The forwarded receipt arrives at Cloudflare, which sends the email content on to the backend.
  4. Parse and store. The backend parses the receipt, extracts the transaction and stores it in the database.
  5. Wallet updated and notified. The wallet is updated, and a notification goes out to Telegram.

Everything after the email lands happens in one pass. There is no cron job in the middle, so recording a transaction is much closer to real time.

The trade-off

This is not free. The setup is more involved, because each wallet needs its own forwarding address, and the forwarding has to be registered one by one (steps 1 and 2 above). With polling, one job looked at one mailbox. With forwarding, a wallet’s receipts only reach the backend after its address and Gmail filter are in place.

For an app that records transactions and sends notifications, I think the faster response is worth the extra setup. If I had many more wallets, I would want to make that registration step less manual.