Design a Medication Approval Tracking Platform with Worklists and Digests
System DesignModel answerLast updated
Design backend services for managing async insurance approval workflows, including real-time status tracking, a concurrent pharmacist task queue, and scheduled digest emails.
Background
A healthcare platform helps pharmacy teams manage medication approval requests submitted to insurance companies. Because insurers respond on their own schedules — sometimes within hours, sometimes over weeks — the platform must handle incoming status updates asynchronously and surface the right work to the right person at the right time.
You are designing the core backend for this platform. The three capabilities it must deliver are:
- Status tracking — ingest approval status updates from insurers and let clinics query the current status and full history of any request.
- Pharmacist worklist — maintain a prioritized, filterable queue of open cases that pharmacists can pick up, work on, and close, without two people stepping on the same case simultaneously.
- Daily email digests — send each clinic staff member and pharmacist a personalized morning summary of overnight changes, pending actions, and approaching deadlines.
Scale and Constraints
- 100,000 active approval requests at any point in time
- 500,000 inbound status events per day (with burst spikes of 10–20×)
- 25,000 digest recipients spread across multiple time zones
- Worklist queries and status lookups must respond within 200 ms at p95
- Status transitions must be strictly ordered, durable, and auditable; duplicate inbound events must be handled safely
- Digest delivery must follow at-least-once semantics without sending the same digest twice on retry
What to Cover
- Architecture overview — the major services, how events flow from inbound update through to the pharmacist UI and email delivery
- Data model — tables or collections for request state, audit history, worklist entries with locking, and digest tracking
- Worklist engine — how you index, prioritize, and safely assign cases to concurrent users
- Digest pipeline — how you schedule, personalize, batch, and recover from failures across time zones
Explain your key design decisions and the trade-offs you considered at each step.
Hints
Hint 1
Before picking any technology, estimate actual throughput. 500,000 events per day is only ~6 per second on average — that changes which tools make sense compared to a system processing millions per second.
Hint 2
A transactional outbox pattern lets you update request state, append to the audit log, update the worklist, and queue a downstream notification all in one atomic database transaction, eliminating dual-write inconsistencies.
Hint 3
For the digest pipeline, idempotency lives in a delivery tracking table with a unique key on (recipient, date). Insert with ON CONFLICT DO NOTHING before sending — that prevents a retry from generating a duplicate email regardless of what happened to the previous attempt.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Size the Problem Before Choosing Tools
Turning stated numbers into real load estimates is the first thing an interviewer wants to see — it justifies every tool choice that follows.
Ingestion: 500K events/day averages roughly 6 events/second. Payers send in batches, so budget for 10–20× bursts: around 100–150 events/second peak. That is well within what a single Postgres instance can absorb.
Active state: 100K requests at ~2 KB each is ~200 MB of working set. Fits in memory and in one database primary with room to spare.
Audit log: 500K events/day at ~1 KB each accumulates ~180 GB/year. Partition by month and retain for at least six years for regulatory compliance.
Digests: 25K emails per day. A single time zone might concentrate 5–8K sends around 8 AM local time — plan the scheduler around that burst, not the daily average.
Key conclusion: This is a correctness and compliance problem, not a throughput problem. A relational database (Postgres) with strong transactions is the right foundation. Avoid premature sharding.
Clarifying questions worth asking: Does the insurer provide a monotonic sequence number per request? Which statuses are terminal? What is the SLA definition (e.g., 72 hours for urgent, 14 days for standard)? Can digest emails contain patient-identifiable information?
2. Architecture Overview
Five logical layers:
Ingestion Gateway normalizes events from webhooks, polling adapters, and clearinghouse feeds into a canonical event format. It verifies signatures and writes the raw payload to an inbox table with a unique constraint on (payer_id, payer_event_id) before returning 202. Duplicate webhooks hit the constraint and are silently acknowledged.
State Machine Service consumes the inbox in order per request (Kafka partitioned by request ID, or SELECT … FOR UPDATE SKIP LOCKED on inbox rows). For each event it validates the transition and, in a single database transaction:
- appends a row to the immutable audit log,
- updates the current-state projection,
- upserts the worklist entry,
- writes one row to an outbox table.
Outbox Relay tails the outbox and fans changes to the Worklist Service (cache invalidation, websocket push), the Digest Aggregator, and analytics consumers. Because the outbox is written in the same transaction as the state change, the audit log and worklist can never diverge.
Query Layer serves status lookups from the primary and audit history from a read replica. Hot worklist pages are cached in Redis with a short TTL (30–60 seconds).
Digest Pipeline runs as a separate scheduled system described in section 5.
3. Data Model
-- Current state projection (rebuilt from audit log if needed)
approval_request(
request_id PK,
clinic_id, patient_ref, payer_id, drug_code,
state, version INT, priority, due_at,
last_payer_seq, updated_at
)
-- Append-only audit log; monthly partitions; DELETE revoked at DB role level
audit_event(
request_id, seq,
event_id UNIQUE, source,
payer_ts, payer_seq, received_at,
from_state, to_state, actor,
payload_ref, -- encrypted blob in object storage
PRIMARY KEY (request_id, seq)
)
-- Idempotency store for raw inbound payloads
inbox(
payer_id, payer_event_id,
raw_payload_ref, status,
PRIMARY KEY (payer_id, payer_event_id)
)
-- Worklist (unresolved items only, ~10–30K rows)
worklist_item(
request_id PK,
queue, priority_score, due_at, clinic_id,
claimed_by NULL, lease_expires_at NULL,
version INT,
resolved BOOLEAN
)
INDEX (queue, clinic_id, priority_score DESC, due_at)
WHERE resolved = false
-- Digest pre-aggregation
digest_change(recipient_id, digest_date, request_id, summary_json)
-- Delivery tracking; idempotency key prevents duplicate sends
digest_delivery(
recipient_id, digest_date,
status, provider_msg_id,
attempts,
PRIMARY KEY (recipient_id, digest_date)
)
audit_event is the source of truth. approval_request is a projection that can be rebuilt by replaying events. Raw payloads are stored encrypted in object storage and referenced by ID — never inlined.
4. Worklist Engine
Indexing and ranking. priority_score is computed on write from urgency, time-to-SLA, and denial type. A background job recalculates scores every five minutes for items approaching their deadline, so ranking is never done at query time.
Claiming with a database-level lease:
UPDATE worklist_item
SET claimed_by = :pharmacist_id,
lease_expires_at = now() + interval '10 min',
version = version + 1
WHERE request_id = :id
AND (claimed_by IS NULL OR lease_expires_at < now())
RETURNING version;
Zero rows returned means someone else holds the claim — return 409 with the holder's name. The UI sends heartbeats to extend the lease while the case is open. Abandoned leases expire automatically; no cleanup job needed.
Optimistic concurrency on actions. Any write action (e.g., submitting an appeal) must supply both the lease_token and expected_version. If a payer event arrived mid-review and changed the request, the action fails with a "case updated, please refresh" error. This prevents acting on stale state — a correctness requirement, not just a nice-to-have.
Why Postgres over Redis for locking? Locking in the same database as the data eliminates split-brain between the lock and the record. At this scale, row contention is negligible.
"Next case" button: SELECT … ORDER BY priority_score DESC FOR UPDATE SKIP LOCKED LIMIT 1 distributes work across concurrent pharmacists without collision.
5. Digest Pipeline
Phase 1 — incremental aggregation. The Digest Aggregator consumes outbox events and upserts rows into digest_change for every relevant recipient. "Pending actions" and "upcoming deadlines" are snapshot queries run at generation time against a read replica.
Phase 2 — scheduling. A scheduler running every 15 minutes selects recipients whose local send time falls in the next window. Each recipient has a precomputed send_hour_utc derived from their time zone (recalculated when DST changes). For each eligible recipient, it inserts:
INSERT INTO digest_delivery (recipient_id, digest_date, status)
VALUES (:id, :date, 'pending')
ON CONFLICT DO NOTHING;
This is the idempotency gate. If the row already exists (from a prior run or a retry), nothing happens. The scheduler then enqueues a generation job partitioned by time zone to smooth the burst.
Phase 3 — dispatch. Workers pull from the queue, render the email from digest_change rows, call the email provider, and update digest_delivery to sent with the provider message ID. On failure, the job is retried with exponential backoff. Because the idempotency row was inserted before sending, a duplicate job on retry skips generation and calls the provider exactly once.
Common Mistakes to Avoid
- Dual writes without an outbox. Updating the state table and publishing to a queue in separate steps means a crash between them leaves state and events inconsistent.
- Clock-based deduplication. Comparing timestamps to detect duplicate webhooks is unreliable. The unique constraint on
(payer_id, payer_event_id)is the only safe approach. - Computing priority at query time. Running scoring logic inside a worklist query adds latency and makes the index less useful. Pre-compute and index the score.
- Skipping the
expected_versioncheck. Without it, a pharmacist can submit an action against a request that changed while they were reviewing it. - Sending digests before writing the idempotency row. The insert must happen before the send, not after, or a crash mid-send produces a duplicate on retry.