Scalable Event Notification Email Platform

Medium · System Design · Software Engineer · Onsite

Prompt

Architect a multi-tenant event management and notification platform capable of supporting at least 1,000,000 simultaneously active events while delivering lifecycle and ad-hoc emails to every registered attendee of each event. Supported communications must cover registration confirmations, scheduled pre-event reminders, urgent schedule-change or cancellation alerts, post-event wrap-ups, and organizer-initiated announcements (sent immediately or scheduled for a future time).

Your design should take an event trigger all the way to inbox delivery through external Email Service Providers (ESPs), backed by explicit capacity arithmetic, storage schemas, queue topology, rate controls, compliance safeguards, and cost reasoning. Conclude by tracing one concrete production incident—such as severe ESP rate-limiting/downtime or a full cloud-region outage—showing how the platform protects urgent traffic while degrading and recovering cleanly.

Scope & Expectations

  • APIs, schemas, and capacity sizing: Define idempotent write APIs for event lifecycle changes, attendee sign-ups, and immediate or future-dated sends; justify relational vs. NoSQL storage choices, sharding keys, indexes, and data-retention windows; and calculate write QPS, per-event fan-out, peak email throughput, and monthly cost (contrasting managed ESPs with self-hosted mail transfer agents).
  • Scheduling, fan-out pipeline, and quota enforcement: Detail the distributed scheduler, broker/queue topology, and worker pools that convert both clock-based reminders and state-change events into batched ESP calls while avoiding top-of-the-hour thundering herds, autoscaling safely, propagating backpressure, and enforcing limits per tenant, per ESP contract, and per destination mailbox domain.
  • Delivery guarantees, resilience, and multi-region recovery: Explain how writes avoid lost triggers (e.g., transactional outbox), compare at-least-once vs. duplicate-free delivery semantics, cover backoff retries and dead-letter queue replay, analyze multi-region disaster-recovery consistency trade-offs, and walk step by step through your chosen failure scenario.
  • Observability, anti-abuse, and privacy compliance: Specify latency and delivery SLOs, end-to-end tracing, bounce and spam-complaint webhook handling, scoped suppression and one-click unsubscribe enforcement, confirmed opt-in rules, and GDPR / CAN-SPAM compliance.

Step-by-step walkthrough

  1. Clarify requirements and scope

    Storing 1,000,000 events in a database is straightforward. What makes this problem genuinely hard is bursty fan-out meeting a rigid external ceiling: thousands of Saturday-night concerts want to send reminders at the exact same clock minute, or a severe storm cancels hundreds of venues at once, while external Email Service Providers (ESPs) (delivery platforms such as Amazon SES or SendGrid that hand mail to Gmail and Outlook) enforce strict per-second quotas and punish erratic spikes by throttling or downgrading sender reputation.

    Our architecture therefore centers on turning jagged, time-clustered event triggers into a smooth, priority-ordered, duplicate-free stream.

    Functional requirements

    • Organizers (tenants) create, update, and cancel events; participants register and unregister.
    • Automated lifecycle emails: registration confirmation, scheduled reminders (T-7d, T-24h, T-2h before start), urgent schedule-change and cancellation notices, and a T+1d post-event follow-up.
    • Ad-hoc organizer sends: trigger an immediate announcement or schedule one for a future timestamp.
    • Per-send delivery tracking (planned, sent, delivered, bounced, suppressed, expired).
    • One-click unsubscribe, scoped suppression lists, and automated bounce/spam-complaint handling.

    Non-functional requirements

    • Scale: at least 1,000,000 concurrent active events (from creation until post-event follow-up).
    • Priority-tiered freshness (trigger time to ESP acceptance):
      • P0 (cancellations, schedule changes, confirmations): p99 < 5 minutes.
      • P1 (scheduled reminders): within ±15 minutes of nominal time (±10 min deliberate spread + <= 5 min queueing).
      • P2 (post-event follow-ups, promotional blasts): within 6 hours.
    • Durability & low duplicates: zero silent loss after API 2xx; duplicate deliveries < 1 in 10,000 recipients.
    • API availability: 99.95% monthly; strict adherence to tenant, ESP, and mailbox-domain rate limits; full CAN-SPAM and GDPR compliance.

    Clarifying assumptions

    • Active event lifecycle averages ~30 days; participant counts are heavy-tailed: median 30, mean 200, max 100,000 (a stadium concert).
    • Multi-tenant platform shared by thousands of independent event organizers, requiring per-tenant fairness and anti-spam isolation.
    • Two external ESPs (ESP-A primary, ESP-B secondary) kept warm simultaneously so either can absorb failover traffic.
    • Confirmations, reminders, and change/cancellation alerts are transactional (tied to a ticket the user holds); promotional follow-ups and newsletters are marketing (requiring explicit opt-in and one-click opt-out).
  2. Back-of-the-envelope sizing

    Let us derive write QPS, fan-out spikes, network bandwidth, and storage from first principles:

    1. Baseline volume
       Active events:                   1,000,000 (30-day average lifecycle)
       Active registrations:            1,000,000 * 200 mean attendees = 200,000,000
       New events/day:                  1,000,000 / 30 = ~33,300/day
       New registrations/day:           200,000,000 / 30 = ~6,700,000/day (~77 writes/s avg)
       Hot stadium on-sale peak (50x):  77 * 50 = ~4,000 registration writes/s
       Emails per registration:         ~5 (confirm + 3 reminders + follow-up + 6% change/cancel)
       Daily / monthly email volume:    6.7M * 5 = ~33.5M emails/day (~390/s avg, ~1.0B/month)
    
    2. The Saturday-evening thundering herd
       Weekly events:                   33,300 * 7 = ~233,000
       Saturday share (20%, mean 400):  ~47,000 events * 400 = ~19,000,000 Saturday attendees
       50% start at 7:00 or 7:30 pm across 4 US time zones (8 half-hour slots):
                                        (19M * 0.5) / 8 = ~1,200,000 attendees in ONE slot!
       If fired in 1 minute (60 s):     1,200,000 / 60 s    = 20,000 emails/s (blows ESP quota!)
       Spread across 20 min (1,200 s):  1,200,000 / 1,200 s = 1,000 emails/s  (smooth & safe)
    
    3. Peak pipeline sizing
       Spread Saturday reminders (P1):                        1,000 emails/s
       Storm cancellations (P0: 300k seats drained in 5 min): 300,000 / 300 s = 1,000 emails/s
       Other Saturday peak traffic (3x daily avg):            ~1,200 emails/s
       Combined peak demand:                                  ~3,200 emails/s
       Target sustained design capacity:                      5,000 emails/s (~1.6x headroom)
       Contracted ESP quotas:           ESP-A (4,000/s) + ESP-B (2,000/s) = 6,000 emails/s
    
    4. Worker concurrency & database write rates at 5,000 emails/s
       Send queue bandwidth:            5,000/s * ~1 KB (template vars only) = 5 MB/s
       ESP webhook ingress (~3/email):  15,000 callbacks/s * ~500 B          = 7.5 MB/s
       In-flight ESP HTTP calls (Little's Law = rate * latency):
         Single-email calls (200 ms):   5,000/s * 0.20 s = 1,000 concurrent calls
         50-email batch calls (250 ms): 100/s   * 0.25 s = 25 concurrent batch calls
       Delivery state writes (~4 updates/email: claim, sent, delivered, open/bounce):
         Average: 33.5M/day * 4 = ~134M writes/day; Peak: 5,000/s * 4 = 20,000 writes/s
    
    5. Storage footprint
       Events:                          ~12M/year * 2 KB    = ~24 GB/year
       Registrations:                   200M active * 300 B = 60 GB active (~730 GB/year)
       Pending scheduled triggers:      1M events * 4       = 4M rows (< 1 GB)
       Delivery records (90-day TTL):   33.5M/day * 400 B * 90 = ~1.2 TB
       Suppression list (in-RAM cache): 30M hashes * 100 B  = ~3 GB
    

    Three architectural laws jump out of this math:

    1. Schedule per event (4M rows), never per recipient (800M rows): rescheduling an event then updates 4 rows in one transaction instead of rewriting 100,000 timers.
    2. Jitter + priority queues are mandatory: draining all 200M active participants at 5,000/s would take 200M / 5,000 ≈ 11.1 hours, so urgent P0 cancellations must never sit behind P1 reminders or P2 promotions.
    3. Separate transactional metadata from high-write delivery logs: events fit in 60 GB of sharded PostgreSQL, while 20,000/s delivery status updates belong in a horizontally scalable key-value store.
  3. API contract and write idempotency

    Every mutating endpoint requires an Idempotency-Key header (a unique client-generated string stored alongside the response for 24 hours so network retries return the original response instead of duplicating writes). For resource creation, we compute IDs deterministically with UUIDv5 (a standard SHA-1 name-based UUID where hashing tenant_id + ":" + idempotency_key always produces the exact same UUID), and event edits use optimistic concurrency (If-Match) to prevent lost updates:

    POST   /v1/events                                   Header: Idempotency-Key: <key>
           { "tenant_id": 84, "title": "Harbor Jazz Night", "starts_at": "2026-12-05T19:00:00-05:00",
             "time_zone": "America/New_York", "capacity": 14000,
             "reminders": ["P7D", "P1D", "PT2H"], "follow_up": "P1D" }
           -> 201 { "event_id": "evt_408...", "version": 1 }
    
    PATCH  /v1/events/{event_id}                        Headers: If-Match: 1, Idempotency-Key: <key>
           { "starts_at": "2026-12-05T20:00:00-05:00", "notify_participants": true }
           -> 200 { "version": 2 }   |   412 Precondition Failed (version mismatch)
    
    POST   /v1/events/{event_id}:cancel                 Header: Idempotency-Key: <key>
           { "reason": "severe coastal squall", "notify_participants": true }
           -> 200 { "version": 3, "status": "CANCELLED" }
    
    POST   /v1/events/{event_id}/registrations          Header: Idempotency-Key: <key>
           { "email": "maya@example.com", "name": "Maya", "locale": "en-US", "marketing_consent": false }
           -> 201 { "registration_id": 90014 }   (200 existing row if email already registered)
    
    DELETE /v1/events/{event_id}/registrations/{registration_id}
    
    POST   /v1/events/{event_id}/sends                  Header: Idempotency-Key: <key>
           { "template_id": "gate-change", "send_at": null }
           -> 202 { "send_id": "s772...", "estimated_recipients": 14000, "priority": "P0" }
           -> 429 Too Many Requests (tenant daily quota exceeded; includes Retry-After)
    
    GET    /v1/sends/{send_id}
           -> 200 { "status": "RUNNING", "planned": 14000, "sent": 9500,
                    "delivered": 9380, "bounced": 30, "suppressed": 90, "expired": 0 }
    
    GET|POST /u/{signed_token}                          Human unsubscribe page + RFC 8058 1-click POST
    POST     /internal/esp/{provider}/webhook           HMAC-signed delivery, bounce & complaint events
    

    Notice that priority (P0/P1/P2) is assigned by the server from the template's verified category (gate-change -> P0, newsletter -> P2); letting organizers pick priority would cause everyone to mark marketing blasts P0.

  4. Schemas, sharding, and storage engines

    We match each table to the storage engine that fits its access pattern:

    Workload Engine Why
    Events, registrations, triggers, outbox PostgreSQL (32 logical shards by hash(event_id) on 4 clusters) Single-shard ACID transactions keep an event, its reminder schedule, and its outbox event strictly in sync (~60 GB active).
    Sends & chunk progress PostgreSQL (1 primary + standby) Tiny write rate (~10 chunks/s at peak); supports rich admission queries by priority, tenant, and deadline.
    Per-recipient delivery state DynamoDB Global Tables (or Cassandra) Absorbs 20,000 point writes/s with built-in 90-day TTL and active-active cross-region replication; zero joins needed.
    Suppressions (bounces & opt-outs) DynamoDB Global Tables + local RAM cache Checked on every email; 30M hashed addresses (~3 GB) fit in memory on sender nodes or Redis.

    1. Sharded Events DB schema (PostgreSQL)

    CREATE TABLE events (
      event_id          UUID PRIMARY KEY,
      tenant_id         BIGINT NOT NULL,
      status            TEXT NOT NULL,          -- SCHEDULED | CANCELLED | COMPLETED
      starts_at         TIMESTAMPTZ NOT NULL,
      time_zone         TEXT NOT NULL,
      version           INT NOT NULL,
      title             TEXT,
      venue             JSONB,
      participant_count INT NOT NULL DEFAULT 0, -- refreshed asynchronously (avoids hot row lock!)
      updated_at        TIMESTAMPTZ NOT NULL
    );
    
    CREATE TABLE registrations (
      event_id          UUID NOT NULL,
      registration_id   BIGINT NOT NULL,
      email_norm        TEXT NOT NULL,          -- lower-cased, trimmed
      name              TEXT,
      locale            TEXT,
      status            TEXT NOT NULL,          -- ACTIVE | CANCELLED
      marketing_consent BOOLEAN NOT NULL,
      consent_meta      JSONB,                  -- timestamp + form version for GDPR proof
      created_at        TIMESTAMPTZ NOT NULL,
      PRIMARY KEY (event_id, registration_id),  -- clusters all attendees of 1 event contiguously!
      UNIQUE (event_id, email_norm)
    );
    
    CREATE TABLE scheduled_triggers (
      trigger_id     UUID PRIMARY KEY,
      event_id       UUID NOT NULL,
      kind           TEXT NOT NULL,             -- REMINDER_7D | REMINDER_24H | REMINDER_2H | FOLLOW_UP | ADHOC
      fire_at        TIMESTAMPTZ NOT NULL,      -- nominal time + deterministic [-10m, +10m) spread
      deadline       TIMESTAMPTZ NOT NULL,      -- drop as EXPIRED if still unsent past this timestamp
      event_version  INT NOT NULL,
      status         TEXT NOT NULL              -- PENDING | FIRED | CANCELLED
    );
    CREATE INDEX due_triggers_idx ON scheduled_triggers (fire_at) WHERE status = 'PENDING';
    
    CREATE TABLE outbox (
      id         BIGSERIAL PRIMARY KEY,
      topic      TEXT NOT NULL,
      key        TEXT NOT NULL,
      payload    JSONB NOT NULL,
      created_at TIMESTAMPTZ NOT NULL
    );
    
    • Avoiding hot-row lock contention on stadium on-sales: if every registration ran UPDATE events SET participant_count = participant_count + 1, 4,000 concurrent buyers for one concert would queue on one row lock. Instead, participant_count is refreshed every few seconds in the background (and if hard seat caps are enforced here, capacity is split across 16 sub-counter rows per large event).
    • Cross-shard user lookups: a secondary lookup table registrations_by_email (sharded by SHA-256(email_norm) and populated asynchronously from outbox) powers "My Tickets" and GDPR erasure without scatter-gather queries across all 32 shards.

    2. Send Control DB (sends, send_chunks) and Key-Value store (deliveries, suppressions)

    sends (PostgreSQL)
      send_id PK (UUIDv5), tenant_id, event_id, template_id, priority (P0|P1|P2),
      category (TRANSACTIONAL|MARKETING), deadline, status, counters...
    
    send_chunks (PostgreSQL)
      (send_id, chunk_no) PK, after_reg_id, last_reg_id, size (<= 500),
      status (READY | RELEASED | DONE | EXPIRED), released_at
    
    deliveries (DynamoDB, 90-day TTL)
      PK message_key = UUIDv5(send_id, registration_id)
      send_id, tenant_id, email_hash, provider, provider_msg_id,
      state (SENDING | SENT | DELIVERED | BOUNCED | COMPLAINED | SUPPRESSED | SKIPPED | EXPIRED | FAILED | UNKNOWN),
      attempt, lease_until, updated_at
      GSI (email_hash, updated_at) for customer support & GDPR erasure
    
    suppressions (DynamoDB Global Table + RAM cache, retained indefinitely as hashes)
      PK email_hash = SHA-256(email_norm)
      scopes: e.g. {"ALL": "HARD_BOUNCE"} or {"tenant:42:MARKETING": "UNSUBSCRIBE"}
    

    Retention: idempotency_keys 24 h; outbox 7 d; Kafka topics 3–7 d; deliveries 90 d (aggregated daily metrics kept 2 yr); registrations PII anonymized 2 yr post-event (or within 30 days on GDPR request); suppressions kept permanently as irreversible SHA-256 hashes.

  5. Service and queue topology

    We split fan-out into two bounded stages (Event Trigger -> 500-row Chunks -> Individual Recipient Messages) gated by an Admission Controller that keeps downstream Kafka queues short (~30 seconds of work) so urgent P0 cancellations never wait behind millions of already-expanded P1 reminders:

     Organizers / Checkout
              | HTTPS (with Idempotency-Key)
              v
     [ Stateless API Service ]
              | 1 ACID tx: event + triggers + outbox
              v
     [ Events DB (32 PG shards) ] ---CDC Relay---> [ Kafka: event-changes ]
              |                                               |
       poll due triggers                                      v
              v                                    [ Trigger Service ] (cancel/reschedule -> P0 send)
     [ Scheduler Workers ] ---+                               |
                              v                               v
                     [ Send Control DB: sends + send_chunks (status = READY) ]
                              ^                               |
           [ Planner ] -------+ (cuts 500-ID ranges)          v
                                                   [ Admission Controller (1 active leader) ]
                                                     (checks send.* lag <= 30 s; P0 > P1 > P2;
                                                      tenant round-robin; drops past-deadline chunks)
                                                              |
                                                              v
                                                   [ Kafka: chunk-tasks ]
                                                              |
                                                              v
                                                   [ Expander Workers ] (read 500 rows from PG replica)
                                                              |
                                                              v
                   [ Kafka: send.p0 | send.p1 | send.p2 ] + [ send.retry.1m | .10m | .1h ] + [ send.dlq ]
                                                              |
                                                              v
                   [ Sender Workers ] <---> [ Redis Rate Limiter (ESP + Tenant + Domain buckets) ]
                     (claim lease in DynamoDB, check suppression cache, render HTML, call ESP)
                                           /                     \
                                          v                       v
                                     [ ESP-A ]                 [ ESP-B ]
                                          \                       /  signed webhooks
                                           v                     v
                   [ Webhook Ingester ] -> [ Kafka: esp-feedback ] -> [ Feedback Processor ]
                                                                      (updates deliveries & suppressions)
    

    Mini-trace of a 14,000-person T-2h reminder (evt_408, Harbor Jazz Night):

    1. Scheduler claims the due trigger row, creates an idempotent sends row (P1), and marks the trigger FIRED.
    2. Planner scans (event_id, registration_id) on a read replica and inserts 28 READY rows of 500 attendees in send_chunks.
    3. Admission Controller sees spare room under the 30-second Kafka lag cap and releases chunks round-robin across tenants to chunk-tasks.
    4. Expander fetches the 500 attendee rows, filters out cancelled registrations and suppressed addresses, and emits ~1 KB messages to send.p1.
    5. Sender claims message_key in deliveries, pulls rate-limit tokens from Redis, renders the localized template, and sends a 50-recipient batch to ESP-A.
    6. ESP-A posts delivery/bounce webhooks back to Webhook Ingester -> esp-feedback -> Feedback Processor.
  6. Fan-out pipeline, delivery guarantees, and DLQ

    Keyset pagination for fast, stable fan-out

    Reading a 100,000-person stadium event with OFFSET 95000 LIMIT 500 forces PostgreSQL to walk and discard 95,000 rows on every query. Instead, the Planner walks the clustered primary key (event_id, registration_id) using keyset pagination (WHERE event_id = $1 AND registration_id > $last_seen ORDER BY registration_id LIMIT 10000), scanning 100,000 8-byte IDs (~800 KB) in ~10 index-only queries and slicing chunk boundaries [after_reg_id, last_reg_id] of 500 IDs each.

    Sender deduplication and lease logic

    Every stage uses deterministic IDs (send_id = UUIDv5(trigger_id, event_version), message_key = UUIDv5(send_id, registration_id)), converging on one atomic conditional write (claim) in deliveries:

    LEASE_SECONDS = 60
    
    
    def handle_recipient_message(
        msg, current_time, deliveries, suppressions, event_cache, limiter, esp, retry_queue
    ):
        """Process one recipient email safely under at-least-once Kafka delivery."""
        # 1. Never send a reminder after its usefulness window has passed
        if current_time > msg.deadline:
            deliveries.mark_if_unsent(msg.message_key, "EXPIRED")
            return
    
        # 2. Drop stale reminders if the event was cancelled or rescheduled while queued
        event = event_cache.get(msg.event_id)
        if event.status == "CANCELLED" and msg.template_kind == "REMINDER":
            deliveries.mark_if_unsent(msg.message_key, "SKIPPED")
            return
    
        # 3. Check in-memory / DynamoDB suppression list (hard bounce, spam complaint, opt-out)
        if suppressions.is_blocked(msg.email_hash, msg.category, msg.tenant_id):
            deliveries.mark_if_unsent(msg.message_key, "SUPPRESSED")
            return
    
        # 4. Atomic conditional write: succeeds only if missing, retryable, or expired SENDING lease
        if not deliveries.claim(msg.message_key, lease_seconds=LEASE_SECONDS):
            return  # Already SENT, or another worker currently holds an active lease
    
        # 5. Acquire rate-limit token for an available ESP and recipient mailbox domain
        provider = limiter.acquire(msg.priority, msg.recipient_domain)
        if provider is None:
            deliveries.release_lease(msg.message_key)
            retry_queue.publish(msg, delay="1m", attempt=msg.attempt)
            return
    
        # 6. Render template at send time and call ESP (or group up to 50 into an ESP batch call)
        rendered_email = esp.render(msg, event)
        result = esp.send(provider, rendered_email, reference_id=msg.message_key)
    
        if result.ok:
            deliveries.mark_sent(msg.message_key, provider, result.provider_message_id)
        elif result.retryable:  # HTTP 429, 5xx, or network timeout
            deliveries.release_lease(msg.message_key)
            retry_queue.publish(msg, delay=retry_queue.backoff_for(msg.attempt + 1), attempt=msg.attempt + 1)
        else:  # Permanent error (syntax-invalid address, rejected payload)
            deliveries.mark_failed(msg.message_key)
    

    Delivery semantics: why inbox "exactly-once" is impossible, and how we handle the gap

    • Inside our pipeline, delivery is at-least-once (Kafka offsets commit after handle_recipient_message finishes) paired with idempotent deduplication on message_key.
    • Across the network boundary to an ESP that lacks idempotency keys, one narrow ambiguity exists: the ESP accepts the email (200 OK), and our sender container crashes 2 ms later before mark_sent reaches DynamoDB. After the 60-second lease expires, nobody knows whether the email went out.
    • Explicit category policy: for P0 and P1 transactional mail, we resend on expired lease (receiving two storm-cancellation emails is vastly safer than driving to a cancelled concert). For P2 marketing mail, we transition an expired SENDING lease to UNKNOWN and do not resend, protecting sender spam-complaint reputation.

    Non-blocking retries, Dead-Letter Queue (DLQ), and ESP feedback

    • Transient failures move to fixed-delay Kafka topics (send.retry.1m -> .10m -> .1h with ±20% jitter) so main partitions never stall waiting on a sleeping thread.
    • Past msg.deadline, P1/P2 messages mark EXPIRED, whereas P0 messages that still fail (plus poison messages like broken templates) route to send.dlq — a Dead-Letter Queue (a quarantine topic that pages an engineer, who fixes the bug and replays messages safely because message_key prevents re-sending already-sent items).
    • Bounces & complaints: hard bounces (non-existent mailbox) immediately suppress ALL scopes permanently; 3 soft bounces (full inbox) across distinct sends in 15 days suppress for 30 days; spam complaints suppress all MARKETING mail and increment the tenant's abuse counter.
  7. Distributed scheduling and spike smoothing

    • Co-located time triggers: scheduled_triggers lives on the same PostgreSQL shard as events. Creating an event inserts its 4 trigger rows in the same transaction; PATCHing starts_at updates their fire_at, deadline, and event_version atomically so reminders can never drift out of sync with the event clock. Two scheduler workers per shard poll WHERE status = 'PENDING' AND fire_at <= now() ORDER BY fire_at LIMIT 200 FOR UPDATE SKIP LOCKED every second (64 tiny indexed queries/s across 32 shards).
    • Event-driven triggers via transactional outbox: cancelling or rescheduling an event writes an outbox row in the same transaction; a CDC relay streams it to event-changes, where Trigger Service creates a P0 send (UUIDv5(event_id, version, kind)) and marks any in-progress reminder sends CANCELLED.

    Five layers that eliminate thundering herds:

    1. Deterministic 20-minute trigger spread: instead of firing every 7:00 pm Saturday concert's T-2h reminder at 17:00:00, we hash event_id into a fixed offset in [-10 min, +10 min), cutting the 1.2M-email Saturday spike from 20,000/s down to 1,000/s:
    import hashlib
    from datetime import datetime, timedelta
    
    SPREAD_WINDOW = timedelta(minutes=20)
    
    
    def spread_fire_at(event_id: str, nominal_time: datetime) -> datetime:
        """Assign each event a repeatable offset in [-10 min, +10 min) around nominal_time."""
        digest_hex = hashlib.sha256(str(event_id).encode("utf-8")).hexdigest()
        offset_seconds = int(digest_hex, 16) % int(SPREAD_WINDOW.total_seconds())
        return nominal_time - (SPREAD_WINDOW / 2) + timedelta(seconds=offset_seconds)
    
    1. Chunk-level admission control: a single 100,000-person stadium reminder still fires at one second, so the Admission Controller meters chunks into Kafka only as fast as senders drain them (~30 s backlog cap).
    2. Hard usefulness deadlines: a T-2h reminder carries deadline = starts_at - 30 min; under extreme disaster load, late reminders expire cleanly in the DB instead of embarrassing us after doors open.
    3. Proactive schedule forecasting: summing participant_count on scheduled_triggers due in the next 30 minutes predicts exact upcoming email load, pre-scaling Expander and Sender pods ahead of spikes.
    4. Ad-hoc P2 jitter: organizer marketing blasts scheduled for :00 top-of-the-hour receive the same ±10-minute spread.
  8. Quotas, autoscaling, and upstream backpressure

    Senders enforce limits at three levels through a centralized Redis token bucket limiter (a counter refilled at a steady rate per second, leased by workers in blocks of 50 tokens so 5,000 emails/s needs only ~100 Redis calls/s):

    1. Tenant quotas & fairness: daily send caps per organizer (new organizers start low and warm up via clean bounce/complaint metrics), plus round-robin chunk admission across tenants within each priority so one stadium blast cannot starve 50-person community meetups.
    2. ESP contract adherence & AIMD: ESP-A (4,000/s) and ESP-B (2,000/s) normally split traffic 70/30 so both keep warm IP reputations, allocated strictly P0 -> P1 -> P2 (with a 5% floor for P2). If an ESP returns HTTP 429 throttling, we apply AIMD (Additive Increase, Multiplicative Decrease): immediately halve that ESP's rate (down to a 10% floor), then edge back up by +5% of contract rate every 30 throttle-free seconds.
    3. Recipient mailbox-domain buckets: Gmail, Outlook, and Yahoo each have dedicated token buckets; if Yahoo temporarily defers connections, Yahoo-bound messages hop to send.retry.1m without slowing Gmail delivery.

    End-to-end backpressure and admission loop

    ESP throttles (429) --> Redis grants fewer tokens --> Senders drain send.* slower
    --> send.* consumer lag approaches 150,000 (~30 s) --> Admission Controller pauses chunk release
    --> READY chunks wait cheaply in PostgreSQL ordered by P0 > P1 > P2 (stale P1/P2 expire cleanly)
    
    MAX_SEND_BACKLOG = 150_000  # ~30 seconds of runway at 5,000 emails/s
    PRIORITIES = ["P0", "P1", "P2"]
    
    
    def admit_chunks_once(ready_by_priority, current_backlog, current_time, publish_chunk, expire_chunk):
        """Release READY chunks in strict priority order and round-robin across tenants."""
        available_room = MAX_SEND_BACKLOG - current_backlog
        for priority in PRIORITIES:
            tenant_queues = ready_by_priority[priority]
            while tenant_queues and available_room > 0:
                tenant_chunks = tenant_queues.pop(0)
                if not tenant_chunks:
                    continue
                chunk = tenant_chunks.pop(0)
                if current_time > chunk.deadline:
                    expire_chunk(chunk)
                else:
                    publish_chunk(chunk)
                    available_room -= chunk.size
                # Put tenant at the back of the line so other tenants get equal turns
                if tenant_chunks:
                    tenant_queues.append(tenant_chunks)
            # Do not release lower-priority work while higher-priority chunks still wait
            if tenant_queues:
                return
    

    Autoscaling rule: Expanders autoscale horizontally on chunk-tasks lag, whereas Senders are sized by ESP_token_rate * ESP_call_latency — never scale Senders blindly on Kafka lag when ESP quota is saturated, or extra pods simply hammer the ESP with 429 errors!

  9. Reliability, multi-region DR, and failure walk-through

    • Transactional outbox: writing events and outbox in one PostgreSQL transaction eliminates dual-write bugs where an event cancels in the database without queuing cancellation emails.
    • Multi-region disaster recovery:
      • Events & Send Control DBs (Active in Region A / Warm Standby in Region B): single-writer avoids 60 ms cross-ocean locks on seat-registration uniqueness, giving an RPO (Recovery Point Objective — max data loss window on sudden regional death) of < 5 seconds via async replication and an RTO (Recovery Time Objective — time to promote Region B and switch DNS) of ~15–30 minutes.
      • Deliveries & Suppressions (Active-Active DynamoDB Global Tables): unsubscribes and message_key dedup records replicate continuously in ~1 second so Region B immediately honors opt-outs and skips already-sent emails when re-running RUNNING sends after failover (accepting a tiny handful of duplicates for emails sent in the final ~1 second before Region A vanished rather than dropping cancellations).

    Concrete failure walk-through: ESP-A throttles and then crashes during Saturday peak

    Assume Saturday 5:00 pm load is 2,200 emails/s (700/s P0 storm cancellations, 1,200/s P1 reminders, 300/s P2 follow-ups) against ESP-A (4,000/s) + ESP-B (2,000/s):

    Time Failure event Automated system response User-visible outcome
    17:03 ESP-A degrades, returning 429 on 40% of calls (true capacity drops to ~800/s). AIMD halves ESP-A tokens (4,000 -> 2,000 -> 1,000 -> 500/s) within ~10 s and stabilizes near ~800/s; throttled items route to send.retry.1m with jitter; allocator shifts ~1,400/s to ESP-B (2,000/s cap). Combined capacity (~2,800/s) still exceeds 2,200/s demand; retried emails land 1–2 min later; all P0/P1/P2 SLOs hold.
    17:10 ESP-A goes completely down (5xx / timeouts > 50% across 200 calls in 10 s). Per-ESP circuit breaker (an automatic cut-off switch preventing wasted timeouts against a dead dependency) trips OPEN; 100% of traffic routes to ESP-B (2,000/s total ceiling). P0 gets full 700/s and P1 gets full 1,200/s on time! P2 gets the 5% floor (100/s), accumulating 200/s safely as READY chunks in PostgreSQL.
    17:10–17:40 Outage lasts 30 minutes. Alert pages on open breaker; P0 and P1 burn zero error budget; ~360,000 P2 follow-ups wait in send_chunks (well within their 6-hour SLO). Zero missed cancellations or late reminders.
    17:40 ESP-A recovers. Breaker enters HALF-OPEN, probing 1% traffic for 30 s, then linearly ramps ESP-A from 10% to 100% over 10 minutes so recovery does not re-crash ESP-A. Once ramped (~3,800/s spare capacity), the 360k P2 backlog drains cleanly in ~2 minutes.
  10. Observability, abuse prevention, compliance, and cost

    • Observability: track P0 (< 5 min) and P1 (±15 min) freshness SLOs, duplicate rate (< 0.01%), oldest PENDING trigger age (> 2 min pages), READY chunk age by priority, per-ESP 429/5xx/breaker state, and DLQ inflow. Propagate trace_id from API/trigger through chunks (sampling per-recipient spans at 1% + 100% of errors) and pass message_key to ESPs so webhooks link back to traces.
    • Abuse prevention & compliance:
      • Organizers can only message verified ticket registrants; external marketing lists require double opt-in (clicking a confirmation link first). Auto-pause any tenant whose bounce rate exceeds 5% or complaint rate exceeds 0.3% (Gmail's bulk-sender spam threshold).
      • Authenticate all outbound domains with SPF, DKIM, and DMARC (DNS allow-lists and cryptographic header signatures proving to mailbox providers that our servers are authorized and messages were not forged), plus RFC 8058 one-click List-Unsubscribe headers honored in ~1 second across both regions.
      • CAN-SPAM & GDPR: include physical postal addresses on marketing mail, never let marketing opt-outs block critical ticket cancellation alerts (while hard bounces block ALL), store registration consent proofs, and fulfill GDPR erasure within 30 days by wiping PII in registrations and deliveries while retaining only the irreversible SHA-256 email hash in suppressions so erased users are never emailed again.
    • Rough monthly cost & managed vs. self-hosted trade-off (~1B emails/month):
      • ESP fees: 1,000,000,000 / 1,000 * $0.10 (typical cloud ESP list rate such as Amazon SES) = ~$100,000/month.
      • Infrastructure: ~40 stateless API/worker pods, 4 sharded PostgreSQL clusters + control DB, 6-broker Kafka (~13 MB/s peak), Redis, and DynamoDB (~134M writes/day, ~1.2 TB storage) = ~$25,000–$40,000/month.
      • Managed ESP vs. self-hosted MTAs (Postfix/KumoMTA): self-hosting cuts per-email fees dramatically, but requires dedicated IP warm-up, ISP feedback-loop agreements, blocklist remediation, and a 24/7 deliverability team — one reputation mistake sends ticket cancellations to spam. Keeping two managed ESPs is the right choice at 1B/month, revisiting dedicated self-hosted MTAs around ~10B emails/month.
  11. Summary of trade-offs

    • Per-event scheduled triggers (4M rows) vs. per-recipient timers (800M rows): makes event reschedules fast single-shard transactions, at the minor cost that an attendee buying a ticket seconds after chunk planning misses that single reminder (they just got a confirmation anyway).
    • Admission controller + 30-second queues vs. deep FIFO Kafka topics: keeps priority reordering, tenant fairness, and deadline expiration agile in PostgreSQL at the cost of one leader-elected controller component.
    • At-least-once + UUIDv5 message_key leases vs. distributed two-phase commit: keeps throughput high and retries safe, resolving the rare post-ESP crash window by category (P0/P1 resend, P2 silence).
    • Sharded PostgreSQL + DynamoDB split vs. single database: pairs ACID outbox/schedule guarantees on 60 GB of event state with effortless 20,000 writes/s and 90-day TTL expiration on 1.2 TB of delivery logs.
    • Active/standby event shards + active-active suppressions/dedup: preserves fast single-region seat uniqueness while guaranteeing opt-outs and duplicate protection survive regional failover.

Intuition & how it works

Think of an event email platform like airport air-traffic control paired with metered highway on-ramps. Storing 1,000,000 scheduled flights is easy; the hard part is that thousands of Saturday concerts all want to launch reminders at 5:00 pm sharp, a sudden storm can trigger urgent cancellation notices that must take off immediately, and external Email Service Providers (ESPs) (platforms like Amazon SES or SendGrid that deliver to Gmail and Yahoo) only give us two runways capped at 6,000 emails per second.

Beginners usually make two fatal mistakes here: they create one timer per attendee as soon as someone registers (generating 800 million timers that must all be rewritten whenever a concert moves by an hour), and they dump all due emails into a single first-in-first-out (FIFO) queue. At 5:00:00 pm on Saturday, 1.2 million reminders flood that queue at 20,000 emails/second — triggering HTTP 429 throttling from the ESPs while trapping urgent storm-cancellation notices behind hours of low-priority traffic.

Walk through how our design handles a 2,000-seat Harbor Jazz Night concert (evt_408, starting Saturday at 7:00 pm):

  1. Event-level scheduling with deterministic jitter: creating evt_408 commits the event and just 4 per-event trigger rows in one PostgreSQL transaction, shifting its T-2h reminder by SHA-256(evt_408) to 4:53:40 pm so thousands of 7:00 pm concerts spread evenly across a 20-minute window instead of colliding at 5:00:00 pm.
  2. Two-stage chunking and priority admission: at 4:53:40 pm, the planner slices the 2,000 attendee IDs into four 500-person READY chunks in the Send Control DB; an Admission Controller releases chunks into Kafka only while downstream send queues hold < 30 seconds of work, letting P0 cancellations jump straight ahead of P1 reminders and P2 follow-ups.
  3. Idempotent lease and rate-limited send: for each attendee, a sender computes message_key = UUIDv5(send_id, registration_id), checks the in-memory suppression cache, claims a 60-second lease in DynamoDB so retries never double-send, takes a Redis rate-limit token, and sends a 50-email batch to a healthy ESP.
  4. Feedback loop: signed ESP webhooks stream back to update DELIVERED counters or immediately add hard bounces and spam complaints to the global suppression cache.

Key trade-offs

  • Per-event triggers (4M rows) vs. per-recipient timers (800M rows). Storing 4 triggers per event in the same PostgreSQL shard lets an organizer move a concert's start time and update its entire reminder schedule in one millisecond transaction. Per-recipient timers would track individual emails earlier, but rescheduling a 100,000-seat stadium would require rewriting 400,000 rows; the tiny trade-off of event-level triggers is that someone registering right after chunks are cut misses that one reminder (having just received a ticket confirmation).
  • Admission controller + short Kafka queues vs. deep per-priority queues. Releasing 500-recipient chunks only while Kafka holds <= 30 seconds of work (~150,000 messages) keeps the real backlog in PostgreSQL, where we can enforce strict P0 > P1 > P2 priority, round-robin fairness across tenants, and automatic deadline expiration (EXPIRED) before rendering HTML. Pushing millions of expanded emails straight into Kafka makes tenant fairness and pre-send cancellation much harder, at the modest cost of running one leader-elected admission controller.
  • At-least-once delivery with UUIDv5 leases vs. true inbox exactly-once. Because an ESP is an external HTTP call, no distributed system can completely eliminate the tiny window where the ESP accepts an email (200 OK) and our worker crashes before recording SENT. Deterministic UUIDv5 (name-hashed UUID) keys eliminate duplicates everywhere else, and we resolve that narrow crash window explicitly by business impact: resend P0/P1 transactional notices after the 60-second lease expires, but mark P2 marketing UNKNOWN without resending to avoid spam complaints.
  • Sharded PostgreSQL + DynamoDB split vs. a single database technology. Event metadata, seat uniqueness, triggers, and the transactional outbox (a table committed alongside business writes so Kafka events are never lost or emitted for rolled-back transactions) need relational ACID transactions on ~60 GB of active data. Per-email delivery records need ~20,000 writes/second, 90-day TTL auto-deletion, and multi-region replication across ~1.2 TB with zero joins — a textbook fit for DynamoDB or Cassandra.
  • Active/warm-standby event DBs vs. active-active global event writes. Keeping one active write region for events avoids 60+ ms cross-ocean consensus latency when checking concert seat capacity, accepting a < 5-second RPO (Recovery Point Objective — max seconds of recent writes lost on sudden region failure) and 15–30 minute RTO (Recovery Time Objective — failover time). Meanwhile, deliveries and suppressions use active-active global tables so opt-outs and duplicate protection survive regional disasters intact.
  • Managed ESPs vs. self-hosted mail servers (MTAs). At ~1 billion emails/month, managed ESP fees (~$100k/month at $0.10 per 1,000) outweigh our own compute and databases (~$25k–$40k/month), but self-hosting requires IP warm-up, ISP feedback loops, and a dedicated deliverability on-call team where one blocklist mistake puts cancellation alerts in spam.

Common mistakes

  • Expanding all recipients synchronously inside the API call or at event-creation time, which makes API latency proportional to stadium size and turns every schedule edit into hundreds of thousands of queue updates.
  • Firing every T-24h and T-2h reminder on the exact second, creating a 20x Saturday-evening thundering herd that triggers ESP 429 throttling instead of spreading events across a deterministic ±10-minute hash window.
  • Putting cancellations, reminders, and marketing blasts in one FIFO queue, allowing a 100,000-recipient promotional newsletter or reminder wave to delay urgent weather cancellations past event start time.
  • Autoscaling sender workers on Kafka queue lag when the ESP quota is the bottleneck, which only multiplies 429 Too Many Requests errors and damages sender reputation instead of applying backpressure upstream.
  • Generating random uuid4() IDs on each send attempt, making it impossible to deduplicate retries, worker crashes, or Dead-Letter Queue (DLQ) redrives.
  • Dual-writing to PostgreSQL and Kafka without a transactional outbox, leaving cancelled events silently unannounced if the API server crashes between the DB commit and Kafka publish.
  • Treating unsubscribe rules identically across categories, either illegally ignoring marketing opt-outs or mistakenly blocking critical ticket-cancellation notices for an attendee who only unsubscribed from promotional newsletters.

Follow-up questions

  • Suppose a venue delays gate opening by one hour and 70,000 ticket holders must be notified within 2 minutes—can this pipeline hit that target? Yes when both ESPs are healthy: a schedule-change template maps server-side to P0, so the planner slices 140 chunks of 500 IDs in milliseconds and the Admission Controller preempts all P1/P2 work to release them immediately. At our 6,000 emails/second combined ESP quota (4,000/s + 2,000/s), transmitting 70,000 emails takes ~12 seconds once expanded, easily finishing inside 2 minutes. That said, inbox delivery and user reading time are outside SMTP's control, so time-critical day-of-show changes should also fan out to mobile push and SMS from the same event-changes topic.
  • If one attendee signs up for 25 separate sessions at a weekend festival, how do you avoid flooding their inbox with 75 individual reminder emails? Currently each event's triggers fire independently, so we add a per-recipient frequency cap and digest buffer in the sender pipeline: a Redis counter keyed by (email_hash, date) tracks daily reminders sent, and once a recipient exceeds 3 reminders in an hour, subsequent P1 reminders are diverted into a 15-minute digest-buffer store keyed by email_hash. A digest worker then compiles all buffered session reminders for that person into a single summary email, trading a few minutes of extra latency and per-recipient state for a much cleaner inbox experience (while keeping P0 cancellations immediate and unbatched).
  • What continuous technical evidence would you show a privacy regulator to prove that one-click unsubscribes take effect across all regions? Every RFC 8058 one-click unsubscribe writes an immutable timestamped audit record and updates the active-active suppressions Global Table across regions within ~1 second, while every sender checks suppressions before claiming a delivery lease and logs state = 'SUPPRESSED' whenever blocked. We run an automated daily compliance job that joins unsubscribe_events against deliveries on (email_hash, scope) looking for any SENT timestamp occurring more than 5 seconds after the user's unsubscribed_at timestamp. Expecting zero rows (and paging on-call immediately if even one violation appears) gives auditors continuous cryptographic and log-backed proof rather than verbal assurances.

Follow-up questions

Similar questions

More StubHub interview questions

All 9 StubHub questions →