Real-time email ingestion
An event-driven pipeline on AWS Lambda and Step Functions that syncs Gmail in under a second, onboards new inboxes in parallel, and moved 854 GB of email data onto PostgreSQL and S3, account by account.
Summary
- I moved email ingestion from long-running workers to an event-driven pipeline on AWS Lambda. It handles about 100k Gmail push events a day, syncing new mail in 0.6 s at p50 and 1.0 s at p95, with over 99.9% of events processed successfully.
- I rebuilt inbox onboarding as an AWS Step Functions workflow that fans out across senders and emails in parallel, removing the 15-minute ceiling of a single function.
- I led the migration of 15.4M emails (854 GB) and 6.3M threads onto PostgreSQL, with message bodies in S3, through a verified, account-by-account cutover.
The problem
EmailZap is only useful if it sees your email as it arrives. Every new message, label change or deletion in Gmail has to be reflected within seconds, for thousands of inboxes at once, and a single heavy inbox must never slow down everyone else. Post-processing ran on a fixed pool of container workers, which had to be sized for peak load and scaled by hand.
An event-driven pipeline
Gmail publishes a notification to Pub/Sub whenever a mailbox changes. The webhook Lambda reads the mailbox’s change history from its last checkpoint, fetches new messages in batches of 50, writes metadata to PostgreSQL and bodies to S3, and advances the checkpoint. It then hands newly arrived mail to a second Lambda for classification. I moved post-processing from the container workers to this function for horizontal scaling, running both side by side behind a feature flag until the Lambda path was proven.
Key design decisions:
- One function for receive and process. Receiving and processing share one Lambda that invokes itself asynchronously. That means one cold start instead of two, one database connection pool and one provisioned-concurrency pool to tune.
- Async invoke over a queue. Lambda’s asynchronous invocation provides retries, up to six hours of throttle backoff and failure routing with full error context through Lambda Destinations, with no queue to operate. The classification function sends failures to a dead-letter queue that can be replayed.
- Label changes inline. A separate function for label updates would spend more time cold starting than doing the work, so they’re applied in the sync path.
- Provisioned and reserved concurrency. Provisioned concurrency keeps a warm floor for latency, and reserved concurrency sets a ceiling that protects the database and downstream rate limits.
One run per mailbox
A busy inbox can generate hundreds of notifications in minutes. Processing them in parallel would race on the same history and multiply the work. Instead, each notification is recorded, and a per-mailbox lock admits only one active run. When it finishes, the run picks up the newest pending notification, which covers everything before it. Large histories are processed in chunks, with the function re-invoking itself for the next one.
Correctness comes from the checkpoint. A notification at or below the stored history point is skipped, and the new checkpoint is written in the same transaction as the work it covers, so a retry after a crash never double-counts. When Gmail’s history window has expired, the checkpoint re-anchors to the mailbox’s latest state.
Onboarding on Step Functions
Connecting a new inbox means scanning its history, building a profile of the user and classifying thousands of senders and emails. As a single function, that work had to finish inside Lambda’s 15-minute limit. I redesigned it as an AWS Step Functions workflow:
- Split at real data boundaries: scan, then classify senders, then classify emails, with each stage passing data through the database, not the state machine.
- Parallel where it’s independent: scanning and profiling run together, and Map states fan out across sender and email chunks with bounded concurrency to respect model rate limits.
- First results early: the first cohort of senders and emails is processed ahead of the fan-out, so a new user sees a classified inbox before onboarding completes.
- Failure isolation: every task retries with exponential backoff, and each chunk has its own catch, so one failed chunk never fails the whole run.
- Warm start: classifier functions are pre-warmed at the start of each run.
Step Functions was estimated at about 1% of a run’s cost; model inference is the rest. In exchange, every onboarding is a visual, inspectable execution with no time ceiling, and p99 onboarding time came down by roughly 20%.
Migrating 854 GB onto PostgreSQL
Email data had grown to 15.4M emails (854 GB logical) and 6.3M threads in MongoDB Atlas. Email state is relational at heart (accounts, threads, labels, classifications), and keeping full bodies in the primary database made it expensive to scale. I led the migration to PostgreSQL, with bodies moved out of the database entirely.
- Metadata in PostgreSQL, bodies in S3. PostgreSQL holds metadata only. Bodies live in S3 as a cache-aside layer with Gmail as the source of truth: filled lazily on first read, encrypted with KMS, and expired after 30 days. Warm reads return at 85 ms p95.
- Per-account cutover. Each account family moves through preflight, backfill, stopping old mailbox watches, import, a read flip and activating new watches. Every step before the flip is recoverable, and integrity checks verify each transfer afterwards. Repeated dry runs produced identical row counts.
- Connection management. RDS Proxy pools connections across concurrent Lambda executions, configured to avoid session pinning.
Once every account had moved, the old cluster was disconnected and decommissioned.
What I learned
- Let the platform do the plumbing. Async invocation, Destinations and Step Functions retries replaced queues and retry code that would otherwise need maintaining.
- Serialise per key, parallelise across keys. One run per mailbox removed race conditions without limiting overall throughput.
- Make every step resumable. Checkpoints in the same transaction as the work, and cutovers that can be retried up to the flip, are what make a live migration safe.