Automated Patient Outreach Sequence Service
Easy · System Design · Software Engineer · Technical Screen
Prompt
Architect a backend platform that runs automated, multi-step outreach sequences on behalf of healthcare organizations. Each sequence delivers a timed cadence of SMS and email touchpoints to a patient contact—for instance, an immediate welcome text at T+0, a follow-up email at T+12h, and a final reminder text at T+48h. Whenever a recipient replies on any channel—or the client organization cancels the outreach—the system must immediately halt that sequence and prevent any remaining scheduled steps from firing.
Your design must satisfy the following functional and operational guarantees:
- Multi-step cadences & instant stop: Execute arbitrary per-sequence timing intervals per contact, and abort all pending future steps upon recipient response or client cancellation.
- Persistent lifecycle state: Durably record sequence status (including
PENDING,COMPLETED,CANCELLED, andSTOPPED_BY_RESPONSE) alongside per-message delivery receipts and an audit history of every state transition. - Resilient retries: Recover from transient third-party gateway errors (such as HTTP
5xxfailures or temporary throttling) via exponential backoff without sending duplicate messages. - Scale & concurrency safety: Support
100,000simultaneously active sequences across varied schedules while guaranteeing that a race between a due scheduled dispatch and an inbound reply never causes duplicate sends.
Scope & Expectations
- Storage schema: Define relational or distributed tables for sequence templates/enrollments, individual scheduled message jobs, delivery attempts, inbound responses, and state-transition audit logs.
- API contracts: Specify endpoints for launching or cancelling outreach sequences and ingesting inbound reply webhooks.
- Scheduling & idempotency architecture: Explain how future tasks are scheduled durably across multi-day horizons and how retries, webhooks, and worker crashes stay strictly idempotent.
- Race-condition & trade-off analysis: Trace how the system resolves simultaneous or out-of-order events—such as a patient reply arriving while a scheduled message is mid-dispatch.
Step-by-step walkthrough
Clarify vocabulary, requirements, and healthcare constraints
Sending three messages on a schedule sounds simple until three distributed-systems realities collide: a user reply can arrive at the exact millisecond a scheduled reminder wakes up, retrying a failed network call must never send duplicate texts to a patient, and multi-day timers (
T+48h) must survive worker crashes and deployments without losing track of anyone.Separate two concepts right away. Specifications often say "sequence" or "campaign" for both the template and one recipient's run. Giving them distinct names prevents data-model confusion: - A campaign is the client's reusable blueprint: an ordered list of steps (
step 0: SMS at T+0,step 1: Email at T+12h,step 2: SMS at T+48h). - An enrollment is one specific contact's stateful journey through that campaign (PENDING,ACTIVE,COMPLETED,CANCELLED,STOPPED_BY_RESPONSE,FAILED). "100,000 active sequences" means 100,000 simultaneously active enrollments (and we will verify our design scales to 10M).Functional requirements
- Clients define multi-step SMS/email campaigns and enroll contacts individually or in batches.
- If a recipient responds—or a client cancels either one enrollment or the whole campaign—execution halts right away and all remaining scheduled steps are aborted.
- Every enrollment and individual message task maintains durable state in storage, including provider delivery receipts (
SENT,DELIVERED,FAILED). - Transient third-party errors (
429rate limits,503unavailable, connection drops) retry automatically using exponential backoff without creating duplicate messages. - Every state change writes an immutable audit-log entry recording what changed, when, and why.
Non-functional requirements and clarifying assumptions
- Zero duplicate sends across retries, duplicate webhooks, or race conditions.
- Stop latency: A reply stops future dispatches within seconds of hitting our webhook.
- Timer accuracy: Messages fire within
1 minuteof their due time under normal load, and pace smoothly to provider rate limits during large batch uploads. - Healthcare privacy (HIPAA): Outreach goes to healthcare members, so contact records and message text may involve PHI (Protected Health Information). Encrypt message bodies at rest, redact them from application logs, keep sensitive clinical details out of lock-screen SMS templates, and use only SMS/email providers under a signed BAA (Business Associate Agreement).
- Reply matching & opt-outs: Each healthcare client sends from dedicated phone numbers and reply-to email addresses, so
(inbound_to_address, sender_phone_or_email)uniquely identifies(client_id, contact_id). A human reply stops all open enrollments for that contact under that client;STOPkeywords additionally record a channel-wide opt-out suppression; out-of-office auto-replies are logged without stopping the sequence by default. - Schedule anchor: Step offsets (
T+12h,T+48h) are measured from the enrollment'sstart_attimestamp so a 10-minute retry delay on Step 0 does not shift Step 1 into the middle of the night.
Back-of-the-envelope numbers and burst math
By Little's law (
active_items = arrival_rate * average_lifetime), if enrollments stay open for up to48 hours(2 days), sustaining100,000active enrollments requires roughly100,000 / 2 days = 50,000new enrollments per day (early replies shorten average lifetime and cancel later steps, reducing total messages sent for a given daily intake).Steady-state load (100,000 active enrollments, 3 steps over 48 hours) new enrollments ~50,000/day (~2,080/hour = ~0.58/second) outbound messages <= 3 * 50,000 = ~150,000/day (~1.7 messages/second average!) inbound replies (10% rate) ~5,000/day pending future timers ~2 future tasks per active enrollment = ~200,000 timers Redis timer memory 200,000 timers * ~100 bytes = ~20 MB Morning batch burst (where the real pressure lives) client uploads 50,000 contacts at 09:00 -> 50,000 T+0 SMS tasks become due at the exact same second assumed provider caps SMS = 100 msgs/sec per account; Email = 500 msgs/sec SMS burst drain time 50,000 / 100 per sec = 500 seconds (~8.3 minutes) Database storage & 100x headroom check rows per enrollment 1 enrollment + 3 tasks + ~3 attempts + ~10 audit rows + ~3 receipts = ~20 rows annual DB growth 50,000/day * 20 rows * 300 B = ~300 MB/day = ~110 GB/year at 100x (10M enrollments) ~170 msgs/sec average, ~20M timers (~2 GB Redis), ~11 TB/year partitionedTwo lessons from the math
- Database throughput is tiny (
< 20 writes/secsteady state), so one PostgreSQL primary easily serves as our single source of truth. - Bursts are bottlenecked by external SMS/email rate limits, not our CPU. Because a 50,000-contact upload takes ~8 minutes to drain through the SMS provider, tasks sit "due but not yet sent" for minutes—making it very common for a cancellation or reply to arrive right in the middle of a wave!
- Database throughput is tiny (
API design
1. Create a campaign blueprint POST /v1/campaigns { "name": "Lab Follow-Up Cadence", "steps": [ { "step_no": 0, "channel": "sms", "template_id": "lab-sms-1", "offset": "PT0S", "max_lateness": "PT4H" }, { "step_no": 1, "channel": "email", "template_id": "lab-eml-2", "offset": "PT12H", "max_lateness": "PT6H" }, { "step_no": 2, "channel": "sms", "template_id": "lab-sms-3", "offset": "PT48H", "max_lateness": "PT12H" } ], "stop_on_auto_reply": false } -> 201 { "campaign_id": "cmp-84", "version": 1 } 2. Start a campaign for one contact (or :batch for up to 1,000 contacts) POST /v1/campaigns/{campaign_id}/enrollments Header: Idempotency-Key: <client-request-uuid> { "contact": { "external_id": "mbr-7042", "phone": "+13125550194", "email": "maya@example.com", "timezone": "America/Chicago" }, "start_at": "2026-11-30T14:00:00Z", "variables": { "first_name": "Maya" } } -> 201 { "enrollment_id": "enr-4b9", "status": "PENDING", "tasks": [{ "task_id": "enr-4b9:0", "step_no": 0, "due_at": "2026-11-30T14:00:00Z" }, ...] } -> 200 same body on retry with same Idempotency-Key or duplicate (campaign_id, contact_id) -> 409 CAMPAIGN_NOT_ACTIVE | 422 CONTACT_OPTED_OUT 3. Cancel an individual enrollment or an entire campaign POST /v1/enrollments/{enrollment_id}/cancel -> 200 { "status": "CANCELLED" } POST /v1/campaigns/{campaign_id}/cancel -> 202 { "status": "CANCELLED", "open_enrollments": 48210 } 4. Register an inbound user response (called by signature-verified provider webhooks) POST /v1/responses { "provider": "twilio", "provider_message_id": "SM4c18e", "channel": "sms", "from": "+13125550194", "to": "+18885550123", "received_at": "2026-11-30T14:02:11Z", "text": "Confirmed, I booked Thursday morning!" } -> 200 { "response_id": "rsp-3d", "kind": "REPLY", "stopped_enrollments": ["enr-4b9"] } -> 200 identical payload if provider retries the same provider_message_id 5. Inspect state and audit trail GET /v1/enrollments/{enrollment_id} -> current enrollment status + per-step delivery state GET /v1/enrollments/{enrollment_id}/history -> ordered list of every state transition and causeNotice
max_latenesson each step: if an SMS provider goes down for 10 hours, a"Your appointment is in 2 hours"reminder is stale past6 hoursand should be markedSKIPPEDrather than sent embarrassingly late. AndPOST /campaigns/{id}/cancelreturns202 Acceptedin milliseconds by flippingcampaigns.status = 'CANCELLED'immediately (blocking all future sends instantly) while a background sweeper updates the 48,210 child rows in clean batches.Data model and explicit state machines
PostgreSQL stores all durable state. Redis (introduced next) is strictly a disposable wake-up index that can be rebuilt from PostgreSQL at any time.
CREATE TABLE campaigns ( campaign_id TEXT PRIMARY KEY, client_id TEXT NOT NULL, status TEXT NOT NULL, -- ACTIVE | CANCELLED | ARCHIVED version INT NOT NULL, steps JSONB NOT NULL, -- array of {step_no, channel, template_id, offset, max_lateness} settings JSONB NOT NULL, cancelled_at TIMESTAMPTZ ); CREATE TABLE contacts ( contact_id TEXT PRIMARY KEY, client_id TEXT NOT NULL, external_id TEXT NOT NULL, phone_e164 TEXT, email TEXT, timezone TEXT NOT NULL DEFAULT 'UTC', UNIQUE (client_id, external_id) ); CREATE INDEX contacts_by_phone ON contacts (client_id, phone_e164); CREATE INDEX contacts_by_email ON contacts (client_id, email); CREATE TABLE suppressions ( -- channel opt-outs (STOP) and hard bounces client_id TEXT NOT NULL, channel TEXT NOT NULL, address TEXT NOT NULL, reason TEXT NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT now(), PRIMARY KEY (client_id, channel, address) ); CREATE TABLE enrollments ( enrollment_id TEXT PRIMARY KEY, client_id TEXT NOT NULL, campaign_id TEXT NOT NULL REFERENCES campaigns, contact_id TEXT NOT NULL REFERENCES contacts, campaign_version INT NOT NULL, -- freezes step definitions at enrollment time status TEXT NOT NULL, -- PENDING | ACTIVE | COMPLETED | CANCELLED | STOPPED_BY_RESPONSE | FAILED started_at TIMESTAMPTZ NOT NULL, ended_at TIMESTAMPTZ, end_reason TEXT, idempotency_key TEXT NOT NULL, UNIQUE (campaign_id, contact_id), UNIQUE (campaign_id, idempotency_key) ); CREATE INDEX open_enrollments_by_contact ON enrollments (client_id, contact_id) INCLUDE (enrollment_id) WHERE status IN ('PENDING', 'ACTIVE'); CREATE TABLE message_tasks ( task_id TEXT PRIMARY KEY, -- deterministic: enrollment_id || ':' || step_no campaign_id TEXT NOT NULL REFERENCES campaigns, enrollment_id TEXT NOT NULL REFERENCES enrollments, step_no INT NOT NULL, channel TEXT NOT NULL, due_at TIMESTAMPTZ NOT NULL, -- scheduled send time or next backoff retry time status TEXT NOT NULL, -- SCHEDULED | DISPATCHING | SENT | DELIVERED | CANCELLED | SKIPPED | FAILED | UNCERTAIN | DEAD_LETTERED attempts INT NOT NULL DEFAULT 0, lease_until TIMESTAMPTZ, -- worker crash lease while status = 'DISPATCHING' provider TEXT, provider_message_id TEXT, last_error TEXT, UNIQUE (enrollment_id, step_no) ); CREATE INDEX overdue_scheduled_tasks ON message_tasks (due_at) WHERE status = 'SCHEDULED'; CREATE INDEX expired_dispatch_leases ON message_tasks (lease_until) WHERE status = 'DISPATCHING'; CREATE TABLE send_attempts ( task_id TEXT NOT NULL REFERENCES message_tasks, attempt INT NOT NULL, provider TEXT NOT NULL, outcome TEXT NOT NULL, http_status INT, error TEXT, at TIMESTAMPTZ NOT NULL DEFAULT now(), PRIMARY KEY (task_id, attempt) ); CREATE TABLE delivery_receipts ( provider TEXT NOT NULL, provider_event_id TEXT NOT NULL, task_id TEXT NOT NULL, status TEXT NOT NULL, provider_ts TIMESTAMPTZ NOT NULL, PRIMARY KEY (provider, provider_event_id) ); CREATE TABLE responses ( -- inbound user response log response_id TEXT PRIMARY KEY, provider TEXT NOT NULL, provider_message_id TEXT NOT NULL, client_id TEXT, contact_id TEXT, channel TEXT NOT NULL, kind TEXT NOT NULL, -- REPLY | OPT_OUT | AUTO_REPLY received_at TIMESTAMPTZ NOT NULL, body_encrypted BYTEA, -- encrypted PHI stopped_enrollment_ids TEXT[] NOT NULL DEFAULT '{}', UNIQUE (provider, provider_message_id) -- deduplicates webhook retries ); CREATE TABLE state_transitions ( -- append-only audit log id BIGSERIAL PRIMARY KEY, entity_type TEXT NOT NULL, -- campaign | enrollment | task entity_id TEXT NOT NULL, from_status TEXT, to_status TEXT NOT NULL, cause TEXT NOT NULL, -- api | dispatcher | reply | receipt | sweeper | operator cause_ref TEXT, at TIMESTAMPTZ NOT NULL DEFAULT now() ); CREATE INDEX state_transitions_by_entity ON state_transitions (entity_type, entity_id, id); CREATE TABLE outbox ( id BIGSERIAL PRIMARY KEY, topic TEXT NOT NULL, payload JSONB NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT now(), published_at TIMESTAMPTZ ); CREATE TABLE dead_letters ( task_id TEXT PRIMARY KEY REFERENCES message_tasks, reason TEXT NOT NULL, attempts INT NOT NULL, last_error TEXT, moved_at TIMESTAMPTZ NOT NULL DEFAULT now(), resolved_at TIMESTAMPTZ, resolution TEXT );Two coupled state machines:
1. Enrollment state machine (terminal states on the right can never transition again) [ PENDING ] ---- first task SENT ----> [ ACTIVE ] ---- all tasks terminal ----> [ COMPLETED ] | | +--- user reply -----------------------+----------------------------------> [ STOPPED_BY_RESPONSE ] +--- client cancels -------------------+----------------------------------> [ CANCELLED ] +--- all tasks failed/skipped (0 sent) -----------------------------------> [ FAILED ] 2. Individual message_task state machine retryable error (sets next backoff due_at) +-----------------------------------------------+ v | [ SCHEDULED ] -------- due & enrollment open --------> [ DISPATCHING ] ---> 2xx ---> [ SENT ] ---> [ DELIVERED ] | | | | | | | +-- past max_lateness / suppressed -> [ SKIPPED ]| | | +-- timeout, no dedup --> [ UNCERTAIN ] | | | +------ invalid recipient --> [ FAILED ] +------- reply or cancel ----------------> [ CANCELLED ]<-+ retries exhausted --> [ DEAD_LETTERED ] (if stopped mid-attempt)High-level architecture
Client Backend SMS / Email Providers (BAA) | REST (campaigns, enrollments, cancel) ^ | v | HTTPS send | webhooks (replies, [ Campaign API ] [ Provider Adapters ] | delivery receipts) | 1 SQL tx: enrollment + 3 tasks token-bucket pacing & v | + transitions + outbox rows circuit breaker [ Webhook Ingester ] v ^ verify HMAC sig [ PostgreSQL Primary + Sync Standby ] | | (campaigns, enrollments, message_tasks, | v responses, state_transitions, outbox) | [ Response Service ] | ^ | locks enrollment, marks | | 1. lock & mark DISPATCHING | STOPPED_BY_RESPONSE, | | 3. lock & record outcome | cancels SCHEDULED tasks | +------------- [ Dispatcher Pool ] -+ | v ^ 2. claim due task_ids | [ Outbox Relay ] --- ZADD ---> [ Redis Delayed Timer Sets ] <--- ZREM ---------+ timers:{client:channel} [ Reconciler (every 5 min) ] re-queues overdue SCHEDULED tasks & resolves expired DISPATCHING leases [ Campaign Cancel Sweeper ] batches cancelled campaign enrollments (1,000 rows/tx)- Enrollment write path: One SQL transaction writes the
enrollmentsrow, its threemessage_tasksrows, audit transitions, andoutboxtimer jobs. If the server crashes mid-request, nothing commits; once it returns201, the outbox relay pushes the due timestamps into Redis. - Timer send path: Dispatchers pop due
task_ids from Redis only as fast as provider rate-limit tokens allow, verify state in PostgreSQL, call the provider, and record the outcome. - Stop path: Inbound replies commit a
responsesrow, lock the contact's open enrollments, transition them toSTOPPED_BY_RESPONSE, and mark remainingSCHEDULEDtasksCANCELLEDin a single transaction. Best-effortZREMcleans up Redis, while PostgreSQL guarantees correctness even ifZREMfails.
- Enrollment write path: One SQL transaction writes the
Deep dive 1: Durable multi-day scheduling with a delayed queue
Why not just run
SELECT ... WHERE due_at <= now()every second? Let's compare the four standard scheduling patterns honestly:Scheduling pattern Strengths Weaknesses Database table polling ( FOR UPDATE SKIP LOCKED)Single system of record; zero sync glue; actually works fine at 100K enrollments with a partial index Dozens of workers constantly hammer the primary DB even when idle; sub-second precision requires aggressive polling; contends at 10M+ timers Cloud queue delay (e.g., AWS SQS DelaySeconds) Fully managed Hard maximum delay of 15 minutes—a48-hourstep would have to wake up and re-enqueue itself 192 timesDurable workflow engine (e.g., Temporal) Built-in multi-day timers, reply signals, and retry state Heavy operational dependency; workflow code must obey strict determinism rules; harder to run ad-hoc SQL reports across enrollments Redis Sorted Set + PostgreSQL Reconciler (Chosen) Sub-second firing; O(log N)timer claims regardless of how many million tasks sit days ahead; zero idle DB loadSecond store that can lose recent seconds of writes on failover—solved completely by our outbox + 5-minute DB reconciler How the Redis delayed queue works without losing tasks
We maintain two sorted sets per
(client_id, channel)using Redis Cluster hash tags{client:channel}so an atomic Lua script (a tiny script Redis executes as one uninterruptible step) can move tasks fromtimerstoinflight:Redis keys per client & channel: timers:{c19:sms} score = due_at_epoch_ms, member = task_id ("enr-4b9:0") inflight:{c19:sms} score = claim_lease_expiry_epoch_ms, member = task_id Atomic claim Lua script (run every 200 ms for n available rate-limit tokens): 1. ids = ZRANGEBYSCORE timers:{c19:sms} -inf <now_ms> LIMIT 0 <n> 2. For each id in ids: ZREM timers:{c19:sms} id ZADD inflight:{c19:sms} <now_ms + 60000> id 3. Return ids Completion: Dispatcher runs ZREM inflight:{c19:sms} <task_id> once PostgreSQL records the attempt outcome.Separating sets by
(client_id, channel)solves two subtle problems at once: 1. Channel isolation:50,000queued SMS messages waiting for100/secSMS tokens never block urgent emails behind them. 2. Multi-tenant fairness: Dispatchers pull round-robin across active clients so one hospital uploading50,000flu reminders at 09:00 never delays a smaller clinic's50appointment texts.The 5-minute PostgreSQL reconciler acts as our safety net: - Any
SCHEDULEDtask withdue_at < now() - interval '2 minutes'is re-pushed to Redis usingZADD NX(NXmeans "add only if missing", so tasks calmly waiting their turn in Redis during a big burst are untouched while timers lost in a Redis failover are restored). - AnyDISPATCHINGtask withlease_until < now()(meaning its worker crashed mid-call) is handed to crash recovery.Deep dive 2: State-machine locking and the reply-vs-send race
How do we prevent a race condition when Maya texts back
"Confirmed!"at the exact instant herT+12hemail wakes up? Never hold a database transaction open across a slow external HTTP call (which would exhaust DB connections and stall reply webhooks). Instead, use a three-phase check-claim-record protocol with a strict parent-before-child lock hierarchy (campaigns->enrollmentsin sorted ID order ->message_tasks) so two transactions can never deadlock:from datetime import timedelta OPEN_ENROLLMENT_STATES = ("PENDING", "ACTIVE") DISPATCH_LEASE = timedelta(seconds=60) def dispatch_task(db, providers, task_id: str, now) -> str: """Phase 1: Lock & claim in DB. Phase 2: Send outside lock. Phase 3: Lock & record.""" snapshot = db.get_task(task_id) if snapshot is None: return "missing" # Phase 1: Short DB transaction to verify eligibility and move SCHEDULED -> DISPATCHING. with db.transaction(): # Lock parent campaign FOR SHARE first, then child enrollment FOR UPDATE -> zero deadlocks! campaign = db.lock_campaign_for_share(snapshot.campaign_id) enrollment = db.lock_enrollment_for_update(snapshot.enrollment_id) # Lazy campaign cancellation check: takes effect immediately for all 50,000 enrollments. if campaign.status == "CANCELLED" and enrollment.status in OPEN_ENROLLMENT_STATES: db.close_enrollment(enrollment, "CANCELLED", cause="campaign_cancelled") # Re-read the task inside the enrollment lock so we see fresh state. task = db.get_task(task_id) if task.status != "SCHEDULED": # Already cancelled by a reply, already sent, or duplicate Redis wake-up. return "already_handled" if task.due_at > now: return "not_yet_due" if now > db.step_deadline(campaign, enrollment, task.step_no): db.update_task_status(task, "SKIPPED", cause="exceeded_max_lateness") db.advance_enrollment_if_complete(enrollment) return "skipped_stale" if db.is_contact_suppressed(enrollment, task.channel): db.update_task_status(task, "SKIPPED", cause="channel_suppressed") db.advance_enrollment_if_complete(enrollment) return "skipped_suppressed" # Claim the send slot with a 60-second crash lease. db.mark_task_dispatching( task, attempts=task.attempts + 1, lease_until=now + DISPATCH_LEASE, ) # Phase 2: Call external SMS/email provider OUTSIDE any DB transaction (10s HTTP timeout). # Pass deterministic task_id ("enr-4b9:1") so retries never send twice! send_result = providers.send(task, idempotency_key=task.task_id) # Phase 3: Re-acquire enrollment lock and record the outcome. record_send_result(db, task_id, send_result, now) return send_result.outcomeNotice
FOR SHAREoncampaigns: multiple dispatch workers reading the same campaign run completely in parallel because shared locks do not block each other, yetUPDATE campaigns SET status = 'CANCELLED'waits for active Phase-1 checks and forces every subsequent dispatch to see'CANCELLED'immediately!Meanwhile, inbound replies run
register_response, locking open enrollments in sortedenrollment_idorder:def register_response(db, inbound_msg) -> list[str]: """Idempotently record an inbound user message and stop matching open enrollments.""" with db.transaction(): # UNIQUE (provider, provider_message_id) deduplicates webhook retries cleanly. existing = db.find_response(inbound_msg.provider, inbound_msg.provider_message_id) if existing is not None: return existing.stopped_enrollment_ids if inbound_msg.kind == "OPT_OUT": db.insert_suppression(inbound_msg.client_id, inbound_msg.channel, inbound_msg.sender) stopped_ids = [] # Sorted enrollment_id order prevents deadlocks when a contact is in two campaigns. open_ids = db.open_enrollment_ids_sorted(inbound_msg.client_id, inbound_msg.contact_id) for enrollment_id in open_ids: enrollment = db.lock_enrollment_for_update(enrollment_id) if enrollment.status in OPEN_ENROLLMENT_STATES and db.should_stop_on(inbound_msg, enrollment): # Marks enrollment STOPPED_BY_RESPONSE and flips all SCHEDULED tasks to CANCELLED. db.close_enrollment(enrollment, "STOPPED_BY_RESPONSE", cause=inbound_msg.response_id) stopped_ids.append(enrollment_id) db.insert_response(inbound_msg, stopped_enrollment_ids=stopped_ids) return stopped_idsTracing every possible race ordering between a reply and a scheduled send
Case 1: Reply commits at t=10ms, Dispatcher runs Phase 1 at t=12ms -> Reply already locked enrollment and set task to 'CANCELLED'. -> Dispatcher Phase 1 sees task.status == 'CANCELLED' -> returns "already_handled". Zero messages sent! Case 2: Dispatcher commits 'DISPATCHING' at t=10ms, Reply commits at t=12ms (during the 150ms HTTP call) -> That single HTTP request is already flying over the wire to Twilio/SendGrid (cannot be un-sent). -> Reply immediately sets enrollment = 'STOPPED_BY_RESPONSE' and cancels Step 2 (T+48h). -> At t=160ms, Phase 3 sees enrollment is closed: if the HTTP call succeeded, it logs 'SENT' with an audit flag (sent_after_stop=true); if the HTTP call failed with 503, it marks the task 'CANCELLED' instead of scheduling a retry! At most 1 in-flight message ever crosses a reply.That sub-second network flight window is physically irreducible—after all, a user's SMS reply also spends 1–3 seconds inside cell carrier towers before reaching our webhook. Holding a database lock during the HTTP call would not recall the packet, and would freeze webhook writes.
Deep dive 3: End-to-end idempotency and exponential backoff with jitter
Every network boundary uses a deterministic idempotency key: 1. Client -> API:
Idempotency-Keyheader +UNIQUE (campaign_id, contact_id)prevents double enrollment. 2. Redis -> Dispatcher: AtomicSCHEDULED -> DISPATCHINGcheck under the enrollment lock prevents duplicate timer firings from sending twice. 3. Dispatcher -> Provider: Every attempt for Stepkpasses the exact same deterministictask_id("enr-4b9:1"). Generating a fresh UUID per retry would defeat deduplication! 4. Provider -> Webhook:UNIQUE (provider, provider_message_id)ignores duplicate webhook deliveries.Classifying provider outcomes safely
Provider response Did the user get it? State transition 200 / 202+provider_message_idAccepted SENT(laterDELIVEREDvia webhook receipt)429 Too Many Requests,503, TCP connect refusedDefinitely NOT sent Retry with full-jitter exponential backoff HTTP timeout, 500 / 502 / 504, connection reset after writeAmbiguous (provider may have queued it!) Retry only if provider supports idempotency keys or status lookup confirms missing; otherwise mark UNCERTAIN(never blind-resend!)400invalid phone / hard bouncePermanent recipient issue FAILED+ add address tosuppressions401 / 403bad API key or broken templateSystem configuration bug DEAD_LETTERED+ open circuit breaker + page on-callExponential backoff with full jitter. Suppose a 2-minute carrier hiccup fails
12,000SMS sends (100/sec * 120s). Fixed delays (60s, 120s, 240s) cause all12,000tasks to slam back together in synchronized spikes every few minutes. Full jitter picks a uniform random delay between0and the exponential cap, smearing retries smoothly across time:import random from datetime import timedelta BASE_BACKOFF_S = 60 MAX_BACKOFF_S = 3600 MAX_SEND_ATTEMPTS = 8 def full_jitter_delay_seconds(attempt_number: int, rng=random) -> float: """Return uniform random wait in [0, min(3600s, 60s * 2^(attempt - 1))].""" exponential_cap = min(MAX_BACKOFF_S, BASE_BACKOFF_S * (2 ** (attempt_number - 1))) return rng.uniform(0.0, float(exponential_cap)) def record_send_result(db, task_id: str, result, now) -> None: """Phase 3: Under the enrollment lock, record attempt outcome or schedule backoff.""" snapshot = db.get_task(task_id) with db.transaction(): enrollment = db.lock_enrollment_for_update(snapshot.enrollment_id) task = db.get_task(task_id) db.insert_send_attempt(task, result) # Guard: if a fast delivery receipt or crash reconciler already finalized the task, stop. if task.status != "DISPATCHING": return enrollment_still_open = enrollment.status in OPEN_ENROLLMENT_STATES if result.outcome == "accepted": db.mark_task_sent(task, result.provider_message_id, after_stop=not enrollment_still_open) elif result.outcome == "retryable": # Never retry if the contact replied or client cancelled while this attempt was in flight! if not enrollment_still_open: db.update_task_status(task, "CANCELLED", cause="stopped_during_attempt") elif task.attempts >= MAX_SEND_ATTEMPTS: db.move_to_dead_letter(task, result) elif now > db.step_deadline_for_task(task): db.update_task_status(task, "SKIPPED", cause="exceeded_max_lateness") else: next_due = now + timedelta(seconds=full_jitter_delay_seconds(task.attempts)) db.reschedule_task(task, next_due) db.insert_outbox("timers.schedule", {"task_id": task.task_id, "due_at": next_due.isoformat()}) elif result.outcome == "ambiguous": db.resolve_ambiguous_send(task, result) elif result.outcome == "recipient_invalid": db.update_task_status(task, "FAILED", error=result.error) db.insert_suppression_from_task(task, result.error) else: db.move_to_dead_letter(task, result) # Always check completion—even if the final step was SKIPPED or FAILED, the enrollment must close! db.advance_enrollment_if_complete(enrollment)Scaling, failure handling, observability, and trade-offs
Scaling from 100K to 10M active enrollments
- At 100K enrollments: 1 PostgreSQL primary + 1 sync standby, 1 Redis primary + replica, and 3 stateless API/dispatcher nodes handle everything with massive headroom. Shared Redis token buckets pace each provider account cleanly (
100 SMS/sec,500 email/sec). - At 10M enrollments (
100x): Shard large clients' Redis timer sets into 16 hash buckets (timers:{c19:sms:0..15}) across Redis Cluster, and monthly-partitionmessage_tasks,send_attempts, andstate_transitionsso historical archival drops old partitions cleanly without vacuum bloat.
Failure handling and observability
- Redis crash or failover: If Redis loses a few seconds of writes, the 5-minute PostgreSQL reconciler restores missing timers via
overdue_scheduled_tasks. If Redis goes completely offline, dispatchers temporarily fall back to pollingoverdue_scheduled_taskswithFOR UPDATE SKIP LOCKEDevery 10 seconds. - Worker crash during Phase 2: Once the 60-second
lease_untilexpires, the reconciler inspects the task: if the provider supports idempotency keys or message-lookup bytask_id, it resolves cleanly; otherwise it marksUNCERTAINrather than risking a duplicate text. - Key metrics & auditability: Alert on due-to-send lag (p99
< 60soutside bursts), provider 5xx rates, circuit-breaker trips, dead-letter inflow,UNCERTAINtask counts, and reply-to-stop latency. Support engineers debug any member complaint fromGET /enrollments/{id}/historywithout ever exposing raw PHI in text logs.
Summary of key trade-offs
- PostgreSQL truth + Redis delayed queue vs. DB-only or workflow engine: Sub-second timer dispatch and zero idle DB polling without adopting a heavy workflow engine, at the cost of a simple outbox + 5-minute reconciler.
- 3-phase lock-send-lock vs. holding DB locks across HTTP: Keeps database transactions under a few milliseconds and reply webhooks instant, leaving only the unavoidable sub-second network flight window.
- Deterministic
task_id+UNCERTAINon unverified timeouts vs. blind at-least-once retries: Guarantees patients never get spammed with duplicate healthcare texts, surfacing ambiguous timeouts explicitly instead of guessing.
- At 100K enrollments: 1 PostgreSQL primary + 1 sync standby, 1 Redis primary + replica, and 3 stateless API/dispatcher nodes handle everything with massive headroom. Shared Redis token buckets pace each provider account cleanly (
Intuition & how it works
Picture an automated clinic front desk with a wall of cheap alarm clocks (a delayed job queue, a fast data structure sorted by wake-up timestamp) and one locked paper chart per patient (a state machine, a set of allowed status steps stored in a relational database). An alarm clock never sends a text message on its own—it only taps a clerk on the shoulder and says, "Check Maya's chart now." Whenever a clerk hears an alarm—or whenever Maya's reply arrives at the mail slot—they first check out Maya's chart under lock so two clerks can never act on Maya at the same instant. If Maya already replied, the alarm clerk sees "STOPPED_BY_RESPONSE" written in ink and throws the reminder slip away; otherwise the clerk writes "Step 1 dialing now" with a 60-second lease, puts the chart back so nobody else is blocked while the phone rings, dials the SMS carrier using a fixed ticket number (enr-4b9:1), and finally logs the outcome back in the chart.
Naive designs break in three predictable ways. First, keeping timers in server memory (sleep(43200)) wipes out every pending 12-hour and 48-hour reminder whenever a container restarts, while naively scanning an unindexed database table every second hammers the database even when nothing is due. Second, checking "has Maya replied?" without locking Maya's enrollment row lets an incoming reply and a scheduled send slip past each other so later reminders still fire after she answered. Third, generating a fresh random request ID on each retry means that whenever a network timeout hides a successful send, retrying sends the patient the exact same healthcare text twice.
Follow one concrete enrollment (enr-4b9 for Maya: Step 0 SMS at T+0, Step 1 Email at T+12h, Step 2 SMS at T+48h):
T+00:00:00 API commits 1 SQL transaction: enrollment enr-4b9 (PENDING) + 3 SCHEDULED tasks + outbox jobs.
Outbox relay adds task "enr-4b9:0" to Redis sorted set timers:{c19:sms} with score = now.
T+00:00:01 Dispatcher claims "enr-4b9:0", locks enr-4b9, marks task DISPATCHING (attempt 1), unlocks,
and calls SMS provider with Idempotency-Key = "enr-4b9:0".
Provider returns 503 Service Unavailable -> clearly not sent!
Dispatcher locks enr-4b9, reschedules "enr-4b9:0" to T+00:00:38 (full-jitter backoff).
T+00:00:38 Retry wakes up, passes the EXACT SAME key "enr-4b9:0" -> 200 OK!
Task 0 becomes SENT; enrollment enr-4b9 moves PENDING -> ACTIVE.
T+12:00:00 Maya texts back "Confirmed!" at the exact millisecond Task 1 ("enr-4b9:1") pops from Redis:
- Webhook locks enr-4b9 FIRST -> sets enr-4b9 = STOPPED_BY_RESPONSE,
and flips Task 1 & Task 2 from SCHEDULED -> CANCELLED.
- Dispatcher acquires enr-4b9 lock 2 ms later -> sees Task 1 is CANCELLED -> exits cleanly!
Key trade-offs
- PostgreSQL truth + Redis sorted-set timers vs. DB polling vs. a workflow engine. Polling PostgreSQL with a partial index (an index covering only
WHERE status = 'SCHEDULED') andFOR UPDATE SKIP LOCKEDis simplest at 100K enrollments, but forces workers to query the primary database nonstop as worker counts and timer horizons grow. A Redis sorted set fires due tasks in milliseconds withO(log N)lookups and zero idle database traffic, trading off a lightweight transactional outbox (saving timer updates in PostgreSQL inside the business transaction before relaying to Redis) and a 5-minute reconciler to heal lost Redis writes. Full workflow engines like Temporal provide durable timers and signals out of the box, at the cost of running a heavyweight cluster and writing deterministic workflow code. - Pessimistic per-enrollment row lock vs. optimistic version retries. Locking the single
enrollmentsrow (SELECT ... FOR UPDATE) serializes dispatches, replies, and cancellations for that one contact so state transitions are trivial to verify. Because one patient's sequence only experiences a handful of events over 48 hours, lock contention is near zero—making a row lock much cleaner than multi-table optimistic retry loops, while parent-first lock order (campaigns FOR SHARE->enrollments FOR UPDATEin sorted ID order) guarantees zero deadlocks. - Three-phase lock-send-lock vs. holding the DB transaction across HTTP. Releasing the database transaction before calling Twilio or SendGrid prevents slow third-party networks from exhausting database connection pools or stalling reply webhooks. The trade-off is an irreducible sub-second flight window where a packet already sent to the carrier crosses an inbound reply—a window that holding a database lock could never close anyway.
- Deterministic idempotency keys +
UNCERTAINstate vs. blind retries. An idempotency key is a stable unique identifier (enrollment_id:step_no) attached to every attempt of the same logical step so the receiver executes it at most once. When a provider times out without supporting idempotency keys or status lookups, marking the taskUNCERTAINinstead of blindly resending honors the strict "no duplicate messages" rule at the cost of surfacing rare ambiguous sends in reporting. - Per-client, per-channel timer queues with token-bucket pacing vs. one global queue. Firing all 50,000 due tasks of a 9 AM upload at once triggers
429rate-limit errors and retry storms. Pacing via a token bucket (a counter refilling at the provider's allowed rate, such as100 SMS/sec) across isolated{client:channel}queues means bursts take ~8 minutes to drain, but prevents SMS backlogs from blocking emails and stops one large client from starving smaller clinics.
Common mistakes
- Checking for replies outside the transaction that claims the task, leaving a gap where an inbound reply commits right before the send starts and fails to stop future steps.
- Holding
SELECT ... FOR UPDATEopen during external SMS/email HTTP calls, tying up database connections for up to 10 seconds per slow call and freezing inbound webhook processing. - Generating a new random UUID on each retry attempt instead of reusing deterministic
enrollment_id:step_no, making provider-side deduplication impossible. - Retrying every HTTP
500or socket timeout blindly, forgetting that the provider may have already accepted and sent the SMS right before the response dropped. - Treating Redis as the primary source of truth, so a Redis failover silently drops 48-hour reminders or fires cancelled tasks whose
ZREMwas missed. - Retrying with fixed exponential intervals (
60s, 120s, 240s) and zero jitter, causing 10,000 tasks that failed during a brief blip to slam the recovering provider in synchronized waves (thundering herd). - Retrying stale time-sensitive healthcare reminders forever without a
max_latenesscutoff, texting a patient about a morning lab visit after the clinic has closed. - Checking opt-out suppressions (
STOP) only at enrollment creation instead of right before every step's send, violating telecom rules when a user textsSTOPmid-campaign. - Advancing enrollment completion only on
SENT, leaving enrollments stuck inACTIVEforever whenever the final step ends inSKIPPED,FAILED, orDEAD_LETTERED.
Follow-up questions
- What happens when an external SMS gateway goes down for multiple hours, and how should your system respond? Wrap each provider adapter in a circuit breaker (an automatic switch that trips "open" when, say,
> 50%of the last 50 calls fail within 60 seconds). While open, if no secondary SMS carrier is configured, dispatchers stop claiming tasks from SMS timer sets altogether—tasks stay peacefully queued in Redis in due-time order without burning their 8-attempt retry budget or flooding the dead-letter queue, while email steps continue unaffected on their own queues. If a standby SMS provider under a BAA is configured, newSCHEDULEDtasks route to the standby (never auto-resendingUNCERTAINtasks from the primary, since the standby cannot deduplicate against the first carrier). Once the primary recovers, the breaker probes health with1%traffic ("half-open") and ramps rate-limit tokens from10%to100%over 15 minutes; any task whose outage delay exceeded its step'smax_latenesstransitions cleanly toSKIPPED. - Suppose product adds local quiet-hour windows that dynamically defer sends based on time of day—how would your scheduling design adapt? Store quiet-hour rules on the campaign (for example, allow sends only
08:00–21:00in each contact's local time zone) and check the rule at dispatch time insidedispatch_task(), not just when enrollments are created. Evaluating lazily at dispatch means changing a campaign's allowed hours immediately governs all200,000already-scheduled tasks with zero bulk database rewrites! Whenever a due task wakes up outside the contact's local window, the dispatcher reschedulesdue_atto the next window opening plus0–15 minutesof random jitter (preventing a massive08:00:00spike) and logs aDEFERRED_QUIET_HOURSaudit row:
```python import random from datetime import datetime, time, timedelta, timezone from zoneinfo import ZoneInfo
SEND_WINDOW_START = time(8, 0) SEND_WINDOW_END = time(21, 0)
def next_allowed_send_utc(candidate_utc: datetime, contact_tz: str, rng=random) -> datetime: """Return candidate_utc if inside [08:00, 21:00) local time, else next 08:00 + jitter.""" tz = ZoneInfo(contact_tz) local_dt = candidate_utc.astimezone(tz)
# Already inside allowed daytime hours -> send right away.
if SEND_WINDOW_START <= local_dt.time() < SEND_WINDOW_END:
return candidate_utc
# After 9 PM moves to tomorrow morning; before 8 AM stays on today's date.
target_date = local_dt.date()
if local_dt.time() >= SEND_WINDOW_END:
target_date = target_date + timedelta(days=1)
next_open_local = datetime.combine(target_date, SEND_WINDOW_START, tzinfo=tz)
jitter = timedelta(seconds=rng.uniform(0, 15 * 60))
return (next_open_local + jitter).astimezone(timezone.utc)
```
- How should you design and operate a dead-letter mechanism for tasks that repeatedly fail delivery? Reserve the dead-letter queue (DLQ) (a holding table for poisoned tasks requiring human investigation) strictly for actionable failures: tasks that exhausted all
8backoff retries or hit system bugs like broken template variables or401credential errors—whereas normal recipient failures like disconnected phone numbers or hard email bounces go toFAILEDplussuppressionsso they do not drown operators in noise. Moving a task setsstatus = 'DEAD_LETTERED', writes adead_lettersrow capturing the payload metadata and every attempt's HTTP response, trips the provider circuit breaker immediately if the error was401/403(saving thousands of sibling tasks from failing one by one), and pages on-call when DLQ inflow exceeds0.5%of volume. An operator console groups dead letters by error signature and supports two audited actions: discard (transition toFAILED) or redrive (a conditional SQL update resettingstatus = 'SCHEDULED'only if the enrollment is still open and withinmax_lateness, keeping the exact sametask_idso provider deduplication stays intact).
Follow-up questions
- What happens when an external SMS gateway goes down for multiple hours, and how should your system respond?
- Suppose product adds local quiet-hour windows that dynamically defer sends based on time of day—how would your scheduling design adapt?
- How should you design and operate a dead-letter mechanism for tasks that repeatedly fail delivery?
Similar questions
- State-Licensed Virtual Care Queue
- Identify Clients Missing Nearby Specialty Care
- Morse Code Translation and Provider Proximity
- Global Live Video Streaming Platform
- Multi-User Collaborative Document Editor
- Burst-Resilient Multi-Channel Notification Platform