Multi-Tenant Scheduled Broadcast Messaging Service

Medium · System Design · Software Engineer · Technical Screen

Prompt

Design a multi-tenant outbound campaign service that enables organizations to schedule broadcast messages to their opted-in audiences.

Each tenant organization manages its own roster of subscribed contacts. Through your service, a tenant can register a message slated for dispatch at a future timestamp (for instance, organization org_77 scheduling a launch announcement for 2026-12-10T16:00:00Z across its 1.5M active contacts), query campaigns scheduled within a specified time interval, and rely on the platform to eventually deliver the message to every eligible contact in that organization's audience.

Scope & Expectations

  • External API contracts: Endpoints for managing contact opt-ins/opt-outs, scheduling or canceling campaigns, and listing scheduled campaigns over a requested time window.
  • Data modeling & audience semantics: Schemas for organizations, contacts, scheduled campaigns, and per-recipient delivery state—along with a justified product choice on whether recipient eligibility is frozen when scheduled or resolved when dispatch begins.
  • Due-campaign scheduling at scale: How the scheduler identifies campaigns ready to fire, when database polling suffices, and how the timer layer evolves at much higher trigger volumes.
  • End-to-end delivery reliability: Handling client retries, worker crashes, duplicate suppression, opt-out compliance, rate limits, and downstream gateway failures.

Step-by-step walkthrough

  1. Clarify requirements and spot the real bottleneck

    In a broadcast scheduling system, deciding when a broadcast is due is the easy 5% of the problem. The hard 95% is fan-out: turning one database row ("send this message to Organization org_77 at 16:00") into 20 million external SMS or email calls without double-messaging anyone, never messaging someone who just unsubscribed, respecting carrier rate limits, surviving worker crashes mid-flight, and keeping a 20M-subscriber broadcast from starving a 5,000-subscriber broadcast scheduled for the exact same minute.

    Functional requirements

    • Maintain per-tenant audiences: Opt contacts in (create or re-activate), record opt-outs (unsubscribe), paginate contact rosters, and run asynchronous bulk imports.
    • Register and manage campaigns: Queue an outbound message targeting an organization's active audience at a future send_at timestamp (with an optional max_delay_s staleness cutoff), update or cancel a pending campaign, and halt unsent batches of an active campaign.
    • Filter campaigns over a time interval: Return an organization's campaigns inside [from, to) filtered optionally by status, with cursor pagination.
    • Monitor delivery outcomes: Surface live counts of sent, failed, and skipped_opted_out recipients while ensuring every eligible active contact receives the message.

    Non-functional requirements

    • Timeliness & fairness: Begin sending within a few seconds of send_at. A 20M-subscriber send will take over an hour to finish due to carrier rate limits, so show an estimated_finish time up front and isolate companies so one huge broadcast never delays small companies.
    • No duplicates & strict opt-out compliance: Duplicate SMS messages cost money per message and frustrate recipients; texting an opted-out subscriber violates telecom compliance rules.
    • Fault tolerance: No single node crash, queue redelivery, or brief database failover may drop a scheduled broadcast or double-send a batch.

    Explicit assumptions

    • Messages are sent via an external SMS/email gateway that accepts individual or small-batch HTTP calls, supports an optional client idempotency reference, and sends asynchronous delivery-receipt webhooks.
    • Each company has a provisioned max_send_rate (messages/second) tied to its sender identity (short code, toll-free number, or email domain).
  2. Estimate scale with back-of-the-envelope math

    Let's size storage, database queries, and network concurrency step by step.

    1. Companies & Subscribers
       Companies                           10,000
       Subscribers                         300M total (median company: 5,000; largest: 20,000,000)
       Subscriber storage (~200 B / row)   300M × 200 B = 60 GB (~120 GB including indexes)
    
    2. Broadcast Schedule Volume
       Scheduled broadcasts                40,000 / day -> 40,000 / 86,400 s ≈ 0.46 due/s average
       Top-of-the-hour burst (e.g. 16:00)  2,000 broadcasts due in the exact same second
       Broadcast metadata (~2 KB / row)    40,000 × 2 KB = 80 MB / day (~29 GB / year — tiny!)
    
    3. Message Fan-out & Delivery State
       Daily messages                      400M / day normal; 2B / day on peak retail holidays
       Active daytime send window (~8 h)   8 × 3,600 = 28,800 seconds
       Send throughput                     Normal: 400M / 28,800 s ≈ 13,900 msg/s (~14k/s)
                                           Peak:   2B   / 28,800 s ≈ 69,400 msg/s (~70k/s)
       Delivery state (~150 B / message)   400M × 150 B = 60 GB / day normal (300 GB peak day)
                                           90-day TTL retention -> ~5.4 to 6.5 TB total
       Delivery write rate (2-3 writes/msg)Peak: 70k × 3 = ~210,000 writes/s
    
    4. Single Largest Broadcast Duration
       20,000,000 subscribers at company max_send_rate = 3,000 msg/s:
       20,000,000 / 3,000 = 6,667 seconds ≈ 1 hour 51 minutes (20,000 batches of 1,000 IDs)
    

    Three architectural decisions follow immediately from this math:

    1. Finding due broadcasts is tiny (~0.5 rows/s average, 2,000 rows in a top-of-hour burst) — a relational database handles the schedule effortlessly.
    2. Delivery-state tracking (~210,000 writes/s at peak, ~6 TB) would crush the subscriber database, so per-recipient delivery state belongs in a horizontally scaled key-value / wide-column store with automatic 90-day expiration.
    3. send_at means "start time", not "instantaneous arrival". A 20M send takes nearly two hours by math alone, so batching, progress tracking, and mid-send cancellation are essential.
  3. Design the external APIs

    All routes are authenticated per company_id. Mutation endpoints require an Idempotency-Key header (a unique client UUID saved by the server so retrying after a timeout returns the original resource instead of creating a duplicate). Phone numbers use E.164 format (+15551234567) inside JSON bodies — never in URL paths or query strings, which get written into plaintext load-balancer logs.

    1. Manage Subscribers
       POST /v1/companies/org_77/subscribers         -- upsert (opt-in or re-subscribe)
            {"phone": "+15559876543", "attributes": {"first_name": "Maya"}}
         -> 200/201 {"subscriber_id": "sub_01K3B", "status": "active"}
    
       POST /v1/companies/org_77/subscribers/sub_01K3B/unsubscribe
         -> 200 {"subscriber_id": "sub_01K3B", "status": "unsubscribed"}
    
       GET  /v1/companies/org_77/subscribers?status=active&limit=500&cursor=...
       POST /v1/companies/org_77/subscriber-imports  {"file_url": "s3://..."} -> 202 {"import_id": "..."}
    
    2. Schedule, Edit, and Cancel Broadcasts
       POST /v1/companies/org_77/broadcasts
            Idempotency-Key: 8a14d9c0-52e1-4f88-9b30-778899001122
            {"body": "Product launch live now! Reply STOP to opt out.",
             "send_at": "2026-12-10T16:00:00Z",
             "max_delay_s": 3600}
         -> 201 Created
            {"broadcast_id": "cmp_408", "status": "SCHEDULED", "version": 1,
             "estimated_audience": 1500000, "estimated_finish": "2026-12-10T16:08:20Z"}
    
       PATCH /v1/companies/org_77/broadcasts/cmp_408
             If-Match: 1                             -- optimistic concurrency check on version!
             {"send_at": "2026-12-10T17:00:00Z", "body": "Updated launch announcement"}
         -> 200 OK (version: 2) | 412 Precondition Failed (already claimed or inside 2-min freeze)
    
       POST /v1/companies/org_77/broadcasts/cmp_408/cancel -> 200 OK
    
    3. Query Scheduled Broadcasts by Time Range & Inspect Progress
       GET  /v1/companies/org_77/broadcasts?from=2026-12-10T00:00:00Z&to=2026-12-17T00:00:00Z
                                           &status=SCHEDULED&limit=100&cursor=...
         -> 200 OK {"items": [... ordered by (send_at, broadcast_id) ...], "next_cursor": "..."}
    
       GET  /v1/companies/org_77/broadcasts/cmp_408
         -> 200 OK {"broadcast_id": "cmp_408", "status": "SENDING",
                    "progress": {"planned_audience": 1500000, "sent": 820000,
                                 "failed": 640, "skipped_opted_out": 118}}
    

    Key API design rules: - Half-open [from, to) UTC intervals + keyset cursor: Using send_at >= from AND send_at < to guarantees adjacent queries ([00:00, 01:00) and [01:00, 02:00)) never double-count a broadcast at 01:00:00Z, and encoding (send_at, broadcast_id) in cursor keeps deep paging O(log n + limit). - Optimistic concurrency (If-Match: version): Checking WHERE version = :v AND status = 'SCHEDULED' prevents a last-second client edit from silently overwriting a broadcast the scheduler just started sending. - max_delay_s staleness guard: Prevents a time-sensitive "lunch flash sale" from going out at 8 PM if an external carrier outage delays sending past send_at + max_delay_s.

  4. Define the relational and delivery-tracking schemas

    We shard PostgreSQL by company_id for core relational entities and use a sharded wide-column / key-value store (Cassandra, ScyllaDB, or DynamoDB) with a 90-day TTL (Time-To-Live — automatic background expiration of old rows) for per-recipient deliveries.

    -- PostgreSQL (sharded by company_id)
    CREATE TABLE companies (
      company_id     BIGINT PRIMARY KEY,
      name           TEXT NOT NULL,
      sender_id      TEXT NOT NULL,
      max_send_rate  INT  NOT NULL,          -- contracted messages/second for this company
      created_at     TIMESTAMPTZ NOT NULL
    );
    
    CREATE TABLE subscribers (
      company_id      BIGINT NOT NULL,
      subscriber_id   BIGINT NOT NULL,       -- monotonic ID per company for clean range slicing
      phone_e164      TEXT   NOT NULL,
      status          TEXT   NOT NULL,       -- 'active' | 'unsubscribed'
      subscribed_at   TIMESTAMPTZ NOT NULL,  -- updated to latest opt-in time on re-subscribe!
      unsubscribed_at TIMESTAMPTZ,           -- NULL while active; set when opting out
      PRIMARY KEY (company_id, subscriber_id),
      UNIQUE (company_id, phone_e164)
    );
    
    CREATE TABLE broadcasts (
      broadcast_id       TEXT PRIMARY KEY,
      company_id         BIGINT NOT NULL,
      body               TEXT NOT NULL,
      send_at            TIMESTAMPTZ NOT NULL,
      status             TEXT NOT NULL,      -- SCHEDULED | SENDING | COMPLETED | CANCELED | EXPIRED
      version            INT  NOT NULL DEFAULT 1,
      max_delay_s        INT,
      audience_cutoff_at TIMESTAMPTZ,        -- frozen moment when sending began
      planned            BOOLEAN NOT NULL DEFAULT false,
      total_batches      INT  NOT NULL DEFAULT 0,
      completed_batches  INT  NOT NULL DEFAULT 0,
      sent_count         BIGINT NOT NULL DEFAULT 0,
      failed_count       BIGINT NOT NULL DEFAULT 0,
      skipped_count      BIGINT NOT NULL DEFAULT 0,
      idempotency_key    TEXT NOT NULL,
      request_hash       BYTEA NOT NULL,
      UNIQUE (company_id, idempotency_key)
    );
    
    -- Serves GET /broadcasts?from=...&to=... in exact cursor order
    CREATE INDEX broadcasts_company_time_idx ON broadcasts (company_id, send_at, broadcast_id);
    -- Partial index: holds ONLY future scheduled rows, staying tiny forever!
    CREATE INDEX broadcasts_due_idx ON broadcasts (send_at) WHERE status = 'SCHEDULED';
    
    CREATE TABLE broadcast_batches (
      broadcast_id        TEXT NOT NULL,
      batch_no            INT  NOT NULL,
      first_subscriber_id BIGINT NOT NULL,
      last_subscriber_id  BIGINT NOT NULL,
      status              TEXT NOT NULL,     -- PENDING | RUNNING | DONE | CANCELED | EXPIRED
      lease_until         TIMESTAMPTZ,
      PRIMARY KEY (broadcast_id, batch_no)
    );
    
    -- Transactional outbox: written in the same transaction as status transitions
    CREATE TABLE outbox (
      outbox_id  BIGSERIAL PRIMARY KEY,
      topic      TEXT NOT NULL,
      msg_key    TEXT NOT NULL,
      payload    JSONB NOT NULL,
      created_at TIMESTAMPTZ NOT NULL
    );
    
    -- Wide-column / KV store (Cassandra / DynamoDB), TTL = 90 days
    -- Partition key = (broadcast_id, batch_no), clustering key = subscriber_id
    deliveries (
      broadcast_id        TEXT,
      batch_no            INT,
      subscriber_id       BIGINT,
      state               TEXT,              -- SENDING | ACCEPTED | DELIVERED | FAILED | SKIPPED | UNKNOWN
      provider_message_id TEXT,
      attempts            INT,
      last_error          TEXT,
      updated_at          TIMESTAMP,
      PRIMARY KEY ((broadcast_id, batch_no), subscriber_id)
    )
    

    Notice four deliberate schema choices: - Partial index (WHERE status = 'SCHEDULED' — an index storing only rows matching a filter): Even after 50 million historical broadcasts finish, this index only holds upcoming broadcasts (~280k rows for a 7-day horizon), keeping scheduler polls blazingly fast. - ID-range batches instead of copying recipients: Recording (first_subscriber_id, last_subscriber_id) turns a 20M-subscriber broadcast into 20,000 tiny batch rows instead of writing 20,000,000 recipient rows before sending a single text. - Re-subscribe timestamp invariant: Updating subscribed_at to the latest opt-in timestamp (and clearing unsubscribed_at = NULL) guarantees that someone who unsubscribed yesterday and re-subscribes 30 minutes into today's broadcast is cleanly recognized as having joined after audience_cutoff_at. - Rollup counters on broadcasts: Incrementing sent_count, failed_count, skipped_count, and completed_batches once as each batch transitions RUNNING -> DONE makes GET /broadcasts/{bid} an O(1) single-row lookup instead of summing 20,000 batch rows.

  5. Audience membership: freeze at dispatch start vs. snapshot on creation

    When a marketer schedules a Thursday 16:00 campaign on Monday morning, who should get it? Let's compare the three product choices:

    Option                        Behavior                           Verdict
    ----------------------------  ---------------------------------  -----------------------------------
    1. Snapshot at schedule time  Copy subscriber list on Monday.    Bad default: writes 20M rows days
                                                                     early, misses Wed/Thu sign-ups, and
                                                                     STILL must filter Thu opt-outs!
    
    2. Pure live scan per batch   Send to whoever is active at the   Bad: a 2-hour send has a moving
                                  moment their batch executes.       target total, and retrying a failed
                                                                     batch pulls in brand-new sign-ups.
    
    3. Cutoff at send start       Freeze audience_cutoff_at = 16:00  Recommended default: captures all
       + live opt-out check       when sending starts; check live    sign-ups up to 16:00, retries are
                                  opt-out status right before send.  deterministic, opt-outs always win!
    

    Here is the exact batch query for Option 3 and a 4-subscriber trace (audience_cutoff_at = 16:00:00Z):

    SELECT subscriber_id, phone_e164, status
      FROM subscribers
     WHERE company_id = :cid
       AND subscriber_id BETWEEN :first_id AND :last_id
       AND subscribed_at <= :audience_cutoff_at
       AND (status = 'active' OR unsubscribed_at > :audience_cutoff_at)
     ORDER BY subscriber_id;
    
    Subscriber    History                                     Query match?  Worker action at 16:30
    ------------  ------------------------------------------  ------------  -------------------------------
    sub_1 (Maya)  Subscribed Mon, still active                Yes           Sends message -> ACCEPTED
    sub_2 (Liam)  Subscribed Mon, texted STOP at 16:10        Yes           Sees status='unsubscribed' ->
                                                                            skips & increments skipped_count!
    sub_3 (Nora)  Subscribed Thu at 16:15 (after cutoff)      No            Excluded (stable denominator)
    sub_4 (Owen)  Unsubscribed Tue, re-subscribed at 16:20    No            subscribed_at=16:20 > 16:00 ->
                                                                            cleanly excluded!
    

    Mention one nuance to the interviewer: for regulated legal notices ("send to the exact audited CSV I approved on Monday"), we can offer an explicit snapshot_mode = true option backed by an immutable recipient file in object storage — while still enforcing live opt-out suppression at send time.

  6. Sketch the high-level architecture

      Company Clients
            |  HTTPS (Idempotency-Key, If-Match)
            v
      +-------------+     SQL      +-----------------------------------------------+
      | API Service |<------------>| PostgreSQL (sharded by company_id)            |
      +-------------+              | companies, subscribers, broadcasts,           |
                                   | broadcast_batches, outbox                     |
                                   +-----------------------------------------------+
                                      ^  poll due (1/s)         | transactional
                                      |  SKIP LOCKED            v outbox relay
                                +-----------+           +------------------+
                                | Scheduler |           | Durable Queue:   |
                                | (2+ pods) |           | broadcast.due    |
                                +-----------+           +------------------+
                                                                |
                                                                v
                                                        +---------------+
                                                        | Batch Planner |  scans subscriber_id index,
                                                        |               |  writes 1,000-ID ranges
                                                        +---------------+
                                                                |
                                                                v
                                          +-----------------------------------------+
                                          | Fair Send Scheduler / Per-Company Lanes |
                                          | (weighted round-robin across companies) |
                                          +-----------------------------------------+
                                                                |
                                                                v
      +-----------------------+  tokens   +---------------+   HTTP    +--------------------+
      | Redis Token Buckets   |<--------->| Async Send    |---------->| SMS / Email        |
      | (company + global)    |  (50/req) | Workers       |           | Gateway Provider   |
      +-----------------------+           +---------------+           +--------------------+
                                               |     ^                          |
                                         state v     | dedup check              | webhooks
                                          +-----------------------+             v
                                          | deliveries KV Store   |<---- Receipt Workers
                                          | (90-day TTL)          |
                                          +-----------------------+
    
  7. Deep dive 1: Due-broadcast scheduling — polling vs. large-scale timers

    How the scheduler claims due broadcasts safely:

    On each database shard, 2+ stateless Scheduler instances run a 1-second loop using FOR UPDATE SKIP LOCKED (a SQL locking modifier that locks available due rows for this transaction while skipping rows already locked by another scheduler pod instead of waiting) and a transactional outbox (inserting the queue event into the outbox table inside the exact same transaction as the UPDATE so a crash can never change status without emitting an event, or vice versa):

    BEGIN;
    -- 1. Claim up to 200 due broadcasts using the DB clock now() (avoids app clock skew!)
    WITH due AS (
      SELECT broadcast_id, company_id, send_at, max_delay_s
        FROM broadcasts
       WHERE status = 'SCHEDULED'
         AND send_at <= now()
       ORDER BY send_at
       LIMIT 200
       FOR UPDATE SKIP LOCKED
    ),
    -- 2. Mark broadcasts past their staleness deadline as EXPIRED (do NOT send!)
    expired AS (
      UPDATE broadcasts b
         SET status = 'EXPIRED', version = b.version + 1
        FROM due d
       WHERE b.broadcast_id = d.broadcast_id
         AND d.max_delay_s IS NOT NULL
         AND now() > d.send_at + make_interval(secs => d.max_delay_s)
      RETURNING b.broadcast_id
    ),
    -- 3. Flip runnable broadcasts to SENDING and freeze audience_cutoff_at
    claimed AS (
      UPDATE broadcasts b
         SET status = 'SENDING',
             audience_cutoff_at = now(),
             version = b.version + 1
        FROM due d
       WHERE b.broadcast_id = d.broadcast_id
         AND d.broadcast_id NOT IN (SELECT broadcast_id FROM expired)
      RETURNING b.broadcast_id, b.company_id, b.audience_cutoff_at
    )
    -- 4. Enqueue outbox events ONLY for claimed runnable broadcasts
    INSERT INTO outbox (topic, msg_key, payload, created_at)
    SELECT 'broadcast.due', broadcast_id,
           jsonb_build_object('broadcast_id', broadcast_id, 'company_id', company_id),
           now()
      FROM claimed;
    COMMIT;
    -- If due returned 200 rows, loop immediately with 0 sleep to drain top-of-hour bursts!
    

    Is simple 1-second database polling acceptable here? Yes — decisively: - Across 16 shards × 2 scheduler pods, polling broadcasts_due_idx runs 32 tiny in-memory B-tree probes per second against an index holding only future rows. - A top-of-the-hour spike of 2,000 broadcasts at 16:00:00Z drains in 10 zero-sleep iterations (2,000 / 200) in < 200 ms. - Using send_at <= now() means if a shard fails over for 8 seconds, the very first poll after recovery automatically picks up every missed broadcast.

    When polling breaks at 1,000× schedule scale — and how to upgrade it: If the product expands from company-wide broadcasts (~0.5 due/s) to per-subscriber triggered journeys ("send abandoned-cart SMS 45 minutes after each shopper's visit", generating 50,000 due timers/s), updating 50,000 relational schedule rows/s contends heavily. We upgrade in three steps: 1. Two-tier DB + in-memory timing wheel: Every 60 seconds, a lookahead loader streams items due in the next 5 minutes from sharded storage into an in-memory hierarchical timing wheel (a circular array of time-slot buckets, advancing one slot per 100 ms like clock hands, firing due items in O(1) memory operations) or sharded Redis sorted sets (ZADD scored by send_at). After a node restart, reloading the 5-minute window and deduplicating by ID recovers cleanly. 2. Minute-bucketed schedule partitions: Store timers in schedule_buckets(minute_bucket, shard_id, item_id) with a persisted last_processed_minute watermark per shard so scanning is a sequential partition read and old minutes are freed instantly via DROP PARTITION. 3. Pre-planning (T - 2 min): During a 2-minute edit-freeze before send_at, pre-compute batch ID ranges (leaving the final batch's upper ID open-ended until audience_cutoff_at) so messages start flowing at T + 0.1 s.

  8. Deep dive 2: Fair multi-tenant fan-out and rate limiting

    1. Crash-safe batch planning: When the Batch Planner consumes broadcast.due, it scans (company_id, subscriber_id) on a read replica in pages of 1,000 eligible IDs and writes all broadcast_batches rows plus planned = true, total_batches = N in one transaction. If planned is already true on a redelivered event, the planner does not recompute ranges — keeping (broadcast_id, batch_no) boundaries immutable so every subscriber belongs to at most one batch forever.

    2. Why a single FIFO queue (or shared Kafka topic) breaks multi-tenant fairness: Suppose Company A (20M subscribers = 20,000 batches) and Company B (5,000 subscribers = 5 batches) both schedule for 16:00. In a single FIFO queue — or even a 32-partition Kafka topic where Company B hashes onto the same partition as Company A — Company B's 5 batches sit stuck for nearly two hours behind Company A's 20,000 batches!

    Instead, we maintain one virtual lane per active company: - Workers pick the next eligible company via weighted round-robin (excluding companies currently out of rate-limit tokens) and claim one PENDING (or lease-expired RUNNING) batch from broadcast_batches via SKIP LOCKED (or per-company Redis queues). - Company B's 5 batches get pulled immediately alongside Company A's first few batches and finish in seconds!

    3. Token-bucket rate limiting and worker sizing: - Each company's max_send_rate and the global provider ceiling are enforced by Redis token buckets (counters that refill at R permits/second up to a small burst cap). To avoid 140,000 Redis calls/s at 70k msg/s peak, workers lease blocks of 50 tokens at a time (< 3,000 Redis calls/s). - By Little's Law (in-flight calls = throughput × latency), 70,000 msg/s × 0.10 s = 7,000 concurrent HTTP requests. Using async I/O workers holding 200 concurrent requests each requires only ~35–50 stateless Send Worker pods (and 100× fewer calls if the provider offers a 100-message batch API).

  9. Deep dive 3: End-to-end deduplication, crash windows, and retries

    Duplicates can sneak in at four distinct layers, so we guard each boundary explicitly:

    Layer 1: Client -> API           UNIQUE (company_id, idempotency_key) + request_hash check
    Layer 2: Scheduler -> Planner    FOR UPDATE SKIP LOCKED + transactional outbox + planned=true
    Layer 3: Batch Worker retries    60s batch lease + deliveries[(broadcast_id, batch_no), sub_id]
    Layer 4: Worker -> SMS Provider  Write state='SENDING' BEFORE HTTP call + provider idempotency key
    

    Solving the hardest edge case — the ambiguous crash window (Layer 4): Inside a batch, the worker follows one golden rule: record the intent before executing the side effect.

    For each subscriber S in leased batch (broadcast_id, batch_no):
      1. Read deliveries[(broadcast_id, batch_no), S.subscriber_id]:
         - ACCEPTED / DELIVERED / FAILED / SKIPPED -> already finished; skip!
         - SENDING (left over from a crashed worker!) -> see reconciliation below!
      2. Re-check S.status == 'active' (if unsubscribed now -> write SKIPPED, continue).
      3. Acquire 1 send token; write deliveries state = 'SENDING', attempts += 1.
      4. POST message to provider with Idempotency-Key = sha256(broadcast_id || ':' || S.subscriber_id).
      5. Write deliveries state = 'ACCEPTED', provider_message_id = resp.id.
    

    What if the worker crashes after step 4 reached the provider, right before step 5? - Case A — Provider supports idempotency keys (best): The replacement worker sees state = SENDING and safely re-sends with the exact same deterministic key sha256(broadcast_id || ':' || S.subscriber_id). The provider deduplicates the retry and returns the original provider_message_id — achieving end-to-end effectively-once delivery! - Case B — Provider lacks idempotency keys: Blindly retrying state = SENDING would double-text the user! Instead, mark stuck SENDING rows UNKNOWN, wait a 15-minute grace window for asynchronous provider delivery webhooks (matched via client metadata (broadcast_id, batch_no, subscriber_id)), and apply an explicit campaign policy (at-least-once re-send vs. at-most-once skip-and-report) to the tiny handful (<= 200 in-flight calls of one crashed pod) still unresolved.

    Error classification & failure recovery: - Connection reset before bytes sent / HTTP 5xx: Retry via a delayed retry queue using exponential backoff with full jitter (randomizing waits within [0, 2^attempt s] up to 32 s across max 6 attempts so retries never synchronize into a thundering herd), stopping at send_at + max_delay_s. - HTTP socket timeout after sending request bytes: Treat identically to a crash in the ambiguous window (do not blind-retry without a provider idempotency key!). - HTTP 429 Too Many Requests: Do not burn a retry attempt; throttle back the token bucket rate and honor Retry-After. - Provider outage: A circuit breaker (an automatic switch that halts calls when error rates spike) pauses batch pulls globally so workers don't spin; broadcasts exceeding send_at + max_delay_s transition cleanly to EXPIRED. - Delivery KV store outage: Workers fail closed (pause sending immediately) — never call the external provider when unable to write state = SENDING first, or a crash would cause mass duplicates.

  10. Summarize the architectural trade-offs

    • 1-second SKIP LOCKED polling on a partial index vs. in-memory timing wheels: Keeps PostgreSQL as the single crash-proof source of truth for ~0.5 due broadcasts/s with zero state-rebuild complexity; introduce lookahead timing wheels only if per-user timers push due rates into thousands/second.
    • Send-start audience_cutoff_at + live opt-out check vs. schedule-time snapshot: Avoids copying millions of rows days early, keeps progress denominators fixed and retries deterministic, and guarantees opt-outs always take precedence.
    • Subscriber ID-range batches vs. materialized recipient rows: Cuts planning writes 1,000× (20k batch rows instead of 20M recipient rows) before sending begins, while deliveries records per-user outcomes as batches execute.
    • Weighted round-robin per-company lanes vs. single FIFO queue: Sacrifices a sliver of batch-packing simplicity so a 20M-subscriber whale can never delay smaller companies scheduled at the same minute.
    • Sharded SQL + TTL KV store vs. single database: Gives ACID transactions on schedules/outbox and 210k writes/s scalability with free 90-day expiry on delivery logs, bridged safely by idempotent keys.

Intuition & how it works

Think of a broadcast scheduling service like running an alarm clock connected to a busy stadium turnstile. Setting the alarm for 16:00 is the easy part — even 40,000 alarms a day is less than one ring per second. The real challenge begins the instant the 16:00 alarm rings for an organization with 20,000,000 subscribers: pushing 20 million people through a carrier turnstile capped at 3,000 people per second takes nearly two hours, requires checking a live opt-out clipboard right before each message leaves, needs a checklist per person so a tripped worker never texts the same customer twice, and requires separate lanes per organization so a 50-person group isn't stuck waiting two hours behind the 20-million-person crowd.

A naive implementation runs a cron script once a minute (SELECT * FROM broadcasts WHERE send_at = current_minute) and loops through subscribers in one process calling the SMS provider one by one. That fails in four places: a 60-second deploy or failover misses current_minute and silently drops the broadcast forever; running two cron servers for high availability sends every message twice; one 20M-subscriber loop blocks every other company; and crashing at subscriber #8,000,000 with no per-recipient ledger forces an impossible choice between dropping the remaining 12 million people or re-texting the first 8 million.

Let's trace a concrete mini-example of scheduling campaign cmp_408 for org_77 at 16:00:00Z across 4 contacts (sub_1..sub_4, batch size = 2):

1. 13:00:00Z — Client calls POST /broadcasts with Idempotency-Key "k1", send_at = 16:00:00Z.
   -> Stored in PostgreSQL with status = 'SCHEDULED' (indexed in the tiny partial index).

2. 16:00:00Z — Scheduler polls WHERE status='SCHEDULED' AND send_at <= now() FOR UPDATE SKIP LOCKED.
   -> Atomically sets status = 'SENDING', freezes audience_cutoff_at = 16:00:00Z, and writes
      a 'broadcast.due' row into the transactional outbox table.

3. 16:00:01Z — Planner reads subscriber IDs <= cutoff and writes 2 tiny ID-range batches:
      Batch 1: [sub_1 .. sub_2],  Batch 2: [sub_3 .. sub_4],  planned = true.

4. 16:00:02Z — Contact sub_2 texts "STOP" (status becomes 'unsubscribed').
   Send Worker leases Batch 1 [sub_1 .. sub_2] from org_77's fair lane:
   - sub_1 (active): writes deliveries[cmp_408, 1, sub_1] = SENDING -> calls SMS API with provider
                     idempotency key hash("cmp_408:sub_1") -> updates state = ACCEPTED!
   - sub_2 (opted out at 16:00:02Z): sees live status = 'unsubscribed' -> writes SKIPPED!
   If the worker crashes right after texting sub_1, the backup worker sees sub_1 in SENDING,
   re-sends with the exact same key hash("cmp_408:sub_1") so the SMS gateway deduplicates it,
   and moves on to finish Batch 1 cleanly.

Key trade-offs

  • 1-second database polling vs. an in-memory timer / timing wheel: Polling a partial index (an index containing only status = 'SCHEDULED' rows) with FOR UPDATE SKIP LOCKED once per second handles ~0.5 due broadcasts/s effortlessly while keeping PostgreSQL as the single source of truth — zero state needs rebuilding after a crash. An in-memory timing wheel (a ring buffer of time slots that fires timers in O(1)) or Redis sorted set cuts sub-second jitter and offloads the database, at the cost of maintaining a second copy of the schedule that must be synced on edits/cancels and reloaded after restarts. Upgrade only when per-subscriber triggers push due items into thousands per second.
  • Cutoff at send start vs. schedule-time snapshot vs. pure live scan: Freezing audience_cutoff_at when sending starts and checking live opt-out status right before each send avoids copying 20M rows days in advance, gives progress bars a fixed total, makes batch retries deterministic, and guarantees opt-outs are always honored. A schedule-time snapshot is only worth its storage write amplification when strict regulatory audits require freezing an exact pre-approved recipient list.
  • Subscriber ID-range batches vs. pre-materializing 20M delivery rows: Planning (first_subscriber_id, last_subscriber_id) ranges writes 20,000 rows instead of 20,000,000 rows before the first message leaves, starting broadcasts seconds after send_at. Pre-materializing every recipient row makes querying "who hasn't been attempted yet?" trivial at the start, at the cost of massive upfront write latency.
  • End-to-end delivery guarantees in the crash window: Writing state = SENDING before calling the provider narrows uncertainty to the tiny in-flight window of a crashed worker (~200 messages). When the SMS/email provider supports client idempotency keys, retrying gives exact effectively-once delivery; when a legacy provider does not, you must explicitly trade off rare duplicates (at-least-once re-send after webhook reconciliation) against rare misses (at-most-once skip-and-report).
  • Per-company fair lanes vs. single global FIFO queue: Pulling batches round-robin across per-company lanes with per-company token buckets (rate-limiting permit counters refilling at max_send_rate) keeps 5,000-subscriber broadcasts on time even while a 20M-subscriber broadcast runs for two hours, trading off a tiny amount of scheduler bookkeeping compared to one global queue.
  • Splitting PostgreSQL and a TTL wide-column store: Sharded PostgreSQL gives strict transactions for schedules, optimistic-locking edits, and the outbox, while a wide-column / key-value store (Cassandra or DynamoDB) absorbs ~210,000 delivery-state writes/s at peak and expires 90-day-old logs for free via TTL (Time-To-Live), trading off cross-store SQL joins in favor of batch-level rollup counters on broadcasts.

Common mistakes

  • Assuming send_at means all 20M messages arrive at 16:00:00: At a realistic carrier rate of 3,000 messages/s, 20M messages take ~1 hour 51 minutes. Failing to calculate duration leads to missing batching, progress APIs, max_delay_s expiration, and mid-send cancellation.
  • Querying WHERE send_at = current_minute instead of send_at <= now(): If a database failover or deploy pauses the cron job for one minute, exact-minute matching permanently abandons every broadcast scheduled for that minute.
  • Two schedulers claiming the same broadcast (SELECT then separate UPDATE) or dual-writing DB + queue: Without FOR UPDATE SKIP LOCKED (or atomic UPDATE ... WHERE status = 'SCHEDULED') and a transactional outbox (writing the queue message inside the same DB transaction), races and mid-step crashes either double-fire or silently strand broadcasts in SENDING.
  • Keeping original subscribed_at unchanged when an unsubscribed user opts back in: If someone unsubscribed yesterday and re-subscribes 20 minutes after today's broadcast starts, failing to update subscribed_at to their latest opt-in time tricks subscribed_at <= audience_cutoff_at AND status = 'active' into including them mid-broadcast.
  • Deduplicating only at the HTTP API (Idempotency-Key) and forgetting worker/provider deduplication: API idempotency prevents creating two broadcasts rows, not worker crashes re-sending half a batch of 1,000 texts.
  • Blindly retrying HTTP timeouts against a non-idempotent SMS gateway: Unlike "connection refused", a read timeout after request bytes left the socket often means the provider already queued the SMS; immediate blind retries double-text customers.
  • Using a shared multi-tenant Kafka topic as the send queue and assuming it is fair: Because thousands of companies hash onto a few dozen partitions and consumers read each partition sequentially, any small company hashing onto the same partition as a 20M-subscriber broadcast still waits hours behind it.
  • Putting phone numbers or emails in URL query parameters (GET /subscribers?phone=+1555...): URLs are logged unencrypted across proxies, CDNs, and APM tools, leaking PII.

Follow-up questions

  • How would you extend the scheduler to deliver a campaign at 10:00 AM in each recipient's local time zone? Store an IANA time zone (or current UTC offset, ~38 distinct offsets worldwide) on each subscribers row and add an index on (company_id, utc_offset, subscriber_id). When the client creates one parent campaign, generate ~38 child sub-campaign rows — one per UTC offset with its own UTC send_at — so the existing SKIP LOCKED scheduler, per-zone audience_cutoff_at, and ID-range batch planner work with zero architectural changes! Contacts with unknown time zones fall back to the organization's default time zone, and legal quiet-hours checks (such as 8 AM–9 PM local windows) run as a final safety gate in the Send Worker.
  • How does batch planning change when a campaign targets a dynamic behavioral segment (such as subscribers who placed an order in the past 30 days) rather than the entire audience? Because behavioral segments depend on order/event tables and do not form contiguous subscriber_id ranges, evaluate the segment query once at audience_cutoff_at (or 2–5 minutes early during the freeze window against an analytics replica / data warehouse) and stream the matching sorted subscriber_ids into partitioned chunk files in object storage (1,000 IDs per chunk). Each broadcast_batches row then points to one immutable chunk index instead of (first_id, last_id), while Send Workers still perform the live subscribers lookup per chunk to fetch phone numbers and honor up-to-the-second opt-outs.
  • What happens if the downstream messaging gateway suffers a partial brownout that cuts your send throughput in half during a multi-million-recipient campaign? Gateway 429 responses and rising latencies automatically step down the global and per-company Redis token-bucket refill rates via multiplicative decrease and gradual additive recovery, while throttled requests reschedule onto a delayed retry queue honoring Retry-After without counting toward failure caps. Weighted round-robin across company lanes shares the remaining 50% capacity fairly so smaller campaigns still finish promptly, estimated_finish updates dynamically from live velocity, and any batches pushed past send_at + max_delay_s mark EXPIRED cleanly (similarly, if outbound texts contain shortened promo URLs, serve 302 redirects from an edge CDN cache and log clicks asynchronously via Kafka so tap spikes never hit PostgreSQL).

Follow-up questions

Similar questions

More Attentive interview questions

All 16 Attentive questions →