Prior Authorization Status Engine, Clinical Worklists, and Digests

Hard · System Design · Software Engineer · Technical Screen

Prompt

Medical clinics and specialty pharmacies file Prior Authorization (PA) requests with health insurers to obtain pre-approval before dispensing high-cost medications or performing procedures. Insurer determinations return asynchronously over hours or weeks through HTTP webhooks, polled status APIs, clearinghouse batch feeds, and manual staff entries.

Architect the core backend platform that powers prior-authorization operations for clinical pharmacy teams across these requirements:

  • Asynchronous status capture & audit history: Ingest insurer status transitions (such as Approved, Denied, Additional Information Required, and Expired) and serve clinic endpoints returning both the latest PA state and its full chronological history.
  • Clinical pharmacist worklist: Serve a prioritized, filterable task queue of PAs needing clinical action—such as denial appeals, requests for supplemental notes, or urgent cases approaching SLA deadlines—so multiple pharmacists can claim, edit, and complete tasks concurrently without stepping on one another.
  • Time-zone-aware daily digests: Compile and deliver morning email briefings for clinic teams and pharmacy reviewers recapping overnight status transitions, open review items, and approaching deadlines.
  • Scale, latency & reliability targets: Support 100,000 concurrently active PAs, 500,000 incoming status events per day, and 25,000 daily digest subscribers across multiple time zones. Every clinical state change requires strict ordering, durable persistence, full auditability, and idempotent handling of duplicate webhooks; digest emails require at-least-once delivery without duplicate spam on retries; and worklist queries plus PA status lookups must finish in < 200 ms at p95.

Scope & Expectations

  • System boundaries & event flow: Outline the end-to-end services connecting insurer ingestion, normalized state transitions, live pharmacist queues, and scheduled email dispatch.
  • Persistence & audit data model: Design schemas for current PA state, immutable transition logs, work-item claims/leases, and digest tracking.
  • Worklist indexing & concurrency control: Explain how queues are indexed and filtered under < 200 ms and how claims/locks prevent duplicate pharmacist work or mid-review race conditions.
  • Digest scheduling & delivery pipeline: Detail how time-zone-aware summaries are aggregated, batched, retried, and protected against duplicate sends.

Step-by-step walkthrough

  1. Clarify requirements and scope

    A prior authorization (PA) is an insurance company's required pre-approval before a clinic or pharmacy can dispense an expensive medication or perform a procedure. At ~6 status events per second on average, raw throughput here is modest—the real engineering challenge is clinical correctness: payer updates arrive days apart, duplicated, or out of order; dozens of pharmacists click on urgent queues at the same time; and daily summary emails must land reliably at 8:00 AM local time without leaking patient data or spamming inboxes.

    Functional requirements

    • Status ingestion and history: Ingest asynchronous payer updates from webhooks (HTTP callbacks pushed by payers), scheduled polling of payer APIs, clearinghouse batch files (intermediary healthcare hubs that exchange standardized files), and manual staff entries from phone or fax results. Expose APIs to read any PA's current status and complete history.
    • Clinical review queue: Serve a prioritized, filterable task list of PAs needing clinical intervention (denial appeals, requests for extra chart notes, urgent cases nearing SLA deadlines) where multiple pharmacists claim, edit, and complete tasks concurrently without stepping on one another.
    • Morning briefing digests: Compile and send personalized 08:00 local-time summary emails to clinic teams and pharmacists recapping overnight state transitions, open tasks, and nearing deadlines.

    Non-functional targets

    • Workload scale: 100,000 concurrently active PAs, 500,000 incoming status updates daily, and 25,000 morning digest subscribers spread across time zones.
    • Consistency and auditability: Per-PA state transitions must be durable, strictly ordered, and auditable. Duplicate payer notifications must be idempotent (processing the exact same message twice produces the exact same state as processing it once).
    • Digest delivery: At-least-once delivery (every non-empty scheduled digest is delivered unless the email address is invalid or down for hours), without flooding users with duplicate retries.
    • Latency: Worklist queries and PA status lookups return in < 200 ms at p95 (95 out of 100 requests finish within 200 ms).
    • Healthcare compliance: Protect PHI (Protected Health Information—any identifiable patient medical data) under HIPAA (the US health-privacy law) via encryption in transit and at rest, strict tenant isolation, and full read/write audit trails.

    Explicit assumptions

    • Clinic staff only view PAs for their own clinic; clinical pharmacist teams serve an assigned set of clinics within an organization (org_id).
    • Payer-specific status codes map to eight canonical states: SUBMITTED, PENDING_PAYER, INFO_REQUIRED, APPROVED, DENIED, APPEALED, EXPIRED, CANCELLED.
    • Every work item carries an absolute SLA (Service-Level Agreement—target completion time) timestamp due_at derived from the payer's response deadline or urgency rules.
    • By default, digest emails contain aggregate counts and an authenticated portal link rather than raw patient names or drug names.
    • Audit logs are retained for 7 years to satisfy healthcare regulatory audits.
  2. Back-of-the-envelope numbers

    1. Status ingestion
       - Average rate:               500,000 / 86,400 s ≈ 5.8 events/s
       - Payer batch / morning burst (assume 50x-150x): ~300 to 1,000 events/s
       - Events per active PA:       500,000 / 100,000 = 5 events/PA/day
                                     -> Most are repeated "still pending" polls or webhook retries!
       - Raw payload (~5 KB each):   500,000 x 5 KB = 2.5 GB/day -> ~0.9 TB/year (tiered to object storage)
       - Normalized event (~500 B):  500,000 x 500 B = 250 MB/day -> ~90 GB/year (fewer after dedup)
    
    2. Active dataset in database memory
       - Active PAs:                 100,000 rows x ~2 KB ≈ 200 MB (fits easily in RAM on one server)
       - Open work items (~20%):     ~20,000 rows x ~500 B ≈ 10 MB
    
    3. Interactive read & write traffic
       - 2,000 pharmacists online (list refresh / 30s + 2 actions/min): ~140 req/s
       - 5,000 clinic staff + EHR (Electronic Health Record) lookups:   ~280 req/s
       - Total interactive traffic:  < 500 req/s (comfortable for read replicas + one primary)
    
    4. Morning digest peak
       - 25,000 recipients/day; largest zone (US Eastern, ~45%): ~11,250 emails at 08:00 ET
       - Database build cost:        11,250 users x 3 indexed queries x 5 ms ≈ 169 s of DB CPU time
                                     Spread across a 30-minute (1,800 s) pre-build window ≈ 0.1 CPU core!
       - Email dispatch rate:        11,250 emails / 300 s (5 minutes) ≈ 38 emails/s
    

    What these numbers tell us: - Do not shard the database. One PostgreSQL primary with a synchronous standby and two read replicas holds the entire active working set in RAM and gives us ACID transactions, row locks, and unique constraints. - Deduplicate at the front door. Five events per active PA per day means polling and webhook retries repeat themselves heavily; dropping exact duplicates immediately saves most downstream work. - Pre-building digests eliminates the 8:00 AM spike. Spreading aggregation over 30 minutes on a read replica uses a tenth of one CPU core.

  3. API design

    Inbound ingestion APIs (payers and staff)

    POST /v1/payer-webhooks/{payer_id}          // Payer payload; verified via HMAC signature or mTLS
      -> 200 OK                                 // Returned once raw payload is saved (including duplicates!)
      -> 401 Unauthorized                       // Invalid signature
      -> 503 Service Unavailable                // Storage temporarily down -> tells payer to retry later
    
    POST /v1/pas/{pa_id}/manual-updates
      Headers: Authorization, Idempotency-Key: <client-uuid>
      Body:    { "status": "DENIED", "payer_ref": "RX-991", "effective_at": "...", "note": "..." }
      -> 202 Accepted { "inbound_id": "inb_81f..." }
    

    Clinic status and history APIs

    GET /v1/pas/{pa_id}
      -> 200 { "pa_id": "...", "status": "INFO_REQUIRED", "status_effective_at": "...",
               "version": 4, "due_at": "...", "open_work_items": [...] }
    
    GET /v1/pas/{pa_id}/history
      -> 200 [ { "seq": 1, "from_status": null, "to_status": "SUBMITTED", "effective_at": "...",
                 "received_at": "...", "source": "ehr", "disposition": "APPLIED", "actor": "system" }, ... ]
    
    GET /v1/pas?clinic_id=...&status=...&updated_since=...&cursor=...
    

    Pharmacist worklist APIs

    GET  /v1/worklist?team_id=...&types=DENIAL_APPEAL,INFO_REQUESTED&payer_id=...&claimed=unclaimed|mine|all&cursor=...
    POST /v1/worklist/next                      // Atomically claim highest-priority unclaimed item for team
         Body: { "team_id": "tm_4", "types": ["DENIAL_APPEAL", "INFO_REQUESTED"] }
      -> 200 { "item_id": "wi_9", "pa_id": "pa_42", "claim_token": "tok_a8...", "lease_expires_at": "..." }
    
    POST /v1/work-items/{id}/claim
      -> 200 { "claim_token": "tok_a8...", "lease_expires_at": "..." }
      -> 409 { "error": "ALREADY_CLAIMED", "claimed_by": "usr_7", "lease_expires_at": "..." }
    
    POST /v1/work-items/{id}/heartbeat          // Sent every 60s by open tab to extend 10-minute lease
         Body: { "claim_token": "tok_a8..." }
    POST /v1/work-items/{id}/release            // Explicit unclaim when pharmacist steps away
         Body: { "claim_token": "tok_a8..." }
    
    POST /v1/work-items/{id}/resolve
         Body: { "claim_token": "tok_a8...", "expected_pa_version": 4,
                 "action": "APPEAL_SUBMITTED" | "INFO_SENT" | "NO_ACTION", "note": "..." }
      -> 200 { "status": "APPEALED", "pa_version": 5 }
      -> 409 { "error": "LEASE_LOST" }          // Lease expired AND another pharmacist claimed the item
      -> 409 { "error": "PA_CHANGED", "current_status": "APPROVED", "pa_version": 5 }
    

    Digest APIs

    PUT /v1/users/{user_id}/digest-preferences
        Body: { "enabled": true, "local_time": "08:00", "time_zone": "America/Chicago" }
    GET /v1/digests/{run_id}                    // Authenticated portal view linked from the daily email
    

    Why these contracts prevent subtle bugs: - Returning 200 on duplicate webhooks stops payers from treating an already-processed event as a failure and retrying for days. - An Idempotency-Key is a client-generated unique token per action so a network retry never records a manual update twice. - Separating claim_token from expected_pa_version distinguishes who owns the task (LEASE_LOST) from whether the clinical facts changed underneath them (PA_CHANGED).

  4. Data model and state machine

    All core tables live in one PostgreSQL cluster, scoped by org_id with PHI columns encrypted at rest:

    inbound_messages       // Raw landing table: every webhook, poll, file line, or manual entry
      inbound_id PK, payer_id, source ('webhook' | 'poll' | 'file' | 'manual'),
      dedup_key TEXT, UNIQUE (payer_id, dedup_key),
      payload_ref TEXT (encrypted S3 URI), received_at TIMESTAMPTZ,
      state ('RECEIVED' | 'NORMALIZED' | 'APPLIED' | 'QUARANTINED'), error TEXT
    
    prior_auths            // Fast current-state lookup row (1 row per PA)
      pa_id PK, org_id, clinic_id, team_id, patient_id, payer_id, payer_case_ref,
      UNIQUE (payer_id, payer_case_ref),
      urgency ('STANDARD' | 'EXPEDITED'), status TEXT, status_effective_at TIMESTAMPTZ,
      last_seq INT, last_event_hash TEXT, version INT, due_at TIMESTAMPTZ,
      created_at TIMESTAMPTZ, updated_at TIMESTAMPTZ
    
    pa_events              // Immutable append-only audit log, partitioned monthly by received_at
      pa_id, seq INT, received_at TIMESTAMPTZ, inbound_id,
      clinic_id, team_id, canonical_status, effective_at TIMESTAMPTZ,
      disposition ('APPLIED' | 'NO_CHANGE' | 'SUPERSEDED' | 'NEEDS_REVIEW'),
      from_status, to_status, actor, prev_hash TEXT, hash TEXT,
      INDEX (pa_id, seq),
      INDEX (clinic_id, received_at) WHERE disposition = 'APPLIED',
      INDEX (team_id, received_at)   WHERE disposition = 'APPLIED'
    
    work_items             // Actionable pharmacist tasks
      item_id PK, pa_id FK, org_id, team_id, clinic_id, payer_id,
      type ('DENIAL_APPEAL' | 'INFO_REQUESTED' | 'URGENT_FOLLOW_UP' | 'STATUS_CONFLICT' | 'RENEWAL'),
      status ('OPEN' | 'CLAIMED' | 'RESOLVED' | 'CANCELLED'),
      priority_tier SMALLINT, due_at TIMESTAMPTZ,
      claimed_by, claim_token, lease_expires_at TIMESTAMPTZ, version INT,
      UNIQUE (pa_id, type) WHERE status IN ('OPEN', 'CLAIMED'),
      INDEX (team_id, priority_tier, due_at, item_id) WHERE status IN ('OPEN', 'CLAIMED')
    
    outbox                 // Transactional event queue for live UI updates & clinic webhooks
      outbox_id BIGSERIAL PK, topic, partition_key, payload JSONB, created_at, published_at
    
    digest_preferences
      user_id PK, org_id, email, time_zone TEXT, local_time TIME, enabled BOOL,
      next_send_at_utc TIMESTAMPTZ, last_covered_until TIMESTAMPTZ
    
    digest_runs
      run_id PK, recipient_id, digest_date DATE, UNIQUE (recipient_id, digest_date),
      window_start TIMESTAMPTZ, window_end TIMESTAMPTZ, send_at_utc TIMESTAMPTZ,
      status ('PENDING' | 'BUILT' | 'SENDING' | 'SENT' | 'SKIPPED_EMPTY' | 'FAILED' | 'EXPIRED'),
      content_ref TEXT, attempts SMALLINT, claimed_at TIMESTAMPTZ, next_attempt_at TIMESTAMPTZ,
      provider_message_id TEXT
    

    Two important schema details: 1. Immutable timeline + fast current row: pa_events is append-only (the app database role only has SELECT and INSERT privileges, never UPDATE or DELETE). Each row hashes prev_hash || row_fields, and prior_auths.last_event_hash caches the latest hash so appending an event never has to scan older monthly partitions to find the previous hash. Meanwhile, GET /v1/pas/{pa_id} reads prior_auths in 1 ms, and GET /v1/pas/{pa_id}/history filters received_at >= prior_auths.created_at so Postgres prunes almost all monthly partitions. 2. Partitioned uniqueness: PostgreSQL cannot enforce a global UNIQUE (pa_id, seq) across monthly partitions without received_at in the key. Instead, the apply transaction guarantees uniqueness by (a) atomically transitioning inbound_messages.state from 'NORMALIZED' to 'APPLIED' once and (b) assigning seq = last_seq + 1 while holding SELECT ... FOR UPDATE on prior_auths.

    Allowed automatic PA state transitions (any unlisted jump routes to NEEDS_REVIEW for a human):

    SUBMITTED ------> PENDING_PAYER ------> APPROVED ------> EXPIRED
        |                   |                  ^
        +---> INFO_REQUIRED <------------------+ (only via APPEALED, never directly from APPROVED!)
        |         |         |
        |         v         v
        +-----> DENIED -> APPEALED (pharmacist action) -> INFO_REQUIRED | APPROVED | DENIED
    (SUBMITTED, PENDING_PAYER, and INFO_REQUIRED can also move to CANCELLED or EXPIRED)
    
  5. High-level architecture

     Payers & Clearinghouses                                            Clinic / Pharmacy Staff
      Webhooks        Status APIs         Batch Files                    Manual Portal Updates
         |                 ^                   |                                  |
         v                 |                   v                                  v
    [Webhook Gateway] [Payer Pollers]    [Batch Loader]                  [Manual Update API]
         |                 |                   |                                  |
         +-----------------+-------------------+----------------------------------+
                           v
            inbound_messages (encrypted raw payload, UNIQUE (payer_id, dedup_key))
                           |   <-- HTTP 200 returned immediately after this commit
                           v
            [Normalizer Workers]  map payer formats (NCPDP / X12 278 / JSON) -> canonical event
                           |      unmapped code or unknown case -> state = 'QUARANTINED' + ops alert
                           v      ordered queue partitioned by pa_id
            [PA State Service]    single ACID transaction per event:
                                  lock prior_auths -> decide disposition -> append pa_events ->
                                  update prior_auths -> open/cancel work_items -> write outbox
                           |
            +--------------+-----------------------------------------------+
            |  PostgreSQL: Primary + Sync Standby (AZ 2) + 2 Read Replicas |
            +--------------+--------------------+--------------------------+
                           |                    |                          |
                           v                    v                          v
                   [Status & History]   [Worklist Service]         [Outbox Relay] -> Event Bus
                    clinics & EHRs       pharmacists                  |                  |
                                             ^                        v                  v
                                             +--- live UI (SSE) ------+        [Clinic Webhooks]
    
            [Digest Scheduler] -> digest_runs -> [Digest Builders (Replica)] -> [TZ Dispatchers] -> Email ESP
    

    Key architectural boundaries: - Store first, process second: Raw payer payloads hit durable storage before returning 200, decoupling brittle payer retries from normalization bugs. - Synchronous worklist creation: Work items open or cancel inside the exact same database transaction that updates prior_auths, so an approved PA never leaves a stale "Write Appeal" task visible. - A transactional outbox is a database table written in the same commit as business data and relayed asynchronously to external consumers (such as SSE—Server-Sent Events that push live one-way browser updates—and clinic webhooks), preventing lost notifications if a process crashes right after commit. - Isolated digest reads: Digest builders query read replicas so morning email aggregation never contends with interactive pharmacist locks on the primary.

  6. Deep dive 1: Idempotent, ordered status ingestion

    1. Smart front-door deduplication. When a message arrives, the receiver writes raw bytes to encrypted object storage and runs:

    INSERT INTO inbound_messages (inbound_id, source, payer_id, dedup_key, payload_ref, received_at, state)
    VALUES (:id, 'webhook', :payer_id, :dedup_key, :payload_ref, now(), 'RECEIVED')
    ON CONFLICT (payer_id, dedup_key) DO NOTHING;
    

    How dedup_key is constructed matters: - Payer provides a unique event_id: use event_id. - No event_id, but payer provides effective_at timestamp: hash (payer_case_ref, raw_status, effective_at). Repeated "still pending as of Tuesday 09:00" polls collapse cleanly into one row. - Neither event_id nor effective_at: use a delivery-specific ID (poll run ID, batch filename + line number, or webhook payload hash + receive hour). Hashing (payer_case_ref, raw_status) alone would be a bug: if a PA went PENDING_PAYER -> INFO_REQUIRED -> PENDING_PAYER, the second PENDING_PAYER would collide with the first and be silently dropped!

    2. Handling out-of-order events (effective_at vs. received_at). Events for pa_id route to the same queue partition so normal arrivals process sequentially, and the database transaction locks prior_auths (FOR UPDATE) so even consumer rebalances cannot race. We compare payer event time (effective_at) before checking the transition table:

    ALLOWED = {
        "SUBMITTED": {"PENDING_PAYER", "INFO_REQUIRED", "APPROVED", "DENIED", "CANCELLED"},
        "PENDING_PAYER": {"INFO_REQUIRED", "APPROVED", "DENIED", "EXPIRED", "CANCELLED"},
        "INFO_REQUIRED": {"PENDING_PAYER", "APPROVED", "DENIED", "EXPIRED", "CANCELLED"},
        "DENIED": {"APPEALED"},
        "APPEALED": {"INFO_REQUIRED", "APPROVED", "DENIED"},
        "APPROVED": {"EXPIRED"},
    }
    
    
    def decide_disposition(current_status, current_eff, new_status, new_eff):
        """Decide how an incoming canonical event affects the PA's current state."""
        # Exact status repeat (e.g., poll returning PENDING_PAYER again) is a harmless no-op.
        if new_status == current_status:
            return "NO_CHANGE"
    
        # If both carry payer timestamps and the incoming event happened earlier, do not regress state.
        if new_eff is not None and current_eff is not None and new_eff < current_eff:
            return "SUPERSEDED"
    
        # Equal timestamps (common when payers send date-only strings) fall through to transition rules.
        if new_status in ALLOWED.get(current_status, set()):
            return "APPLIED"
    
        # Illegal or contradictory jump (e.g., APPROVED -> INFO_REQUIRED with a newer/missing date).
        return "NEEDS_REVIEW"
    

    Let's trace an out-of-order webhook pair on pa_42 to see why every row stays auditable:

    Time received   Webhook payload                       Decision & state after commit
    -------------   -----------------------------------   --------------------------------------------------
    10:02:00 UTC    status=APPROVED, eff=10:00 UTC        PENDING_PAYER -> APPROVED is in ALLOWED -> APPLIED
                                                          prior_auths: status=APPROVED, eff=10:00, seq=2, v=2
                                                          pa_events:   seq=2 (PENDING_PAYER -> APPROVED)
    
    10:05:00 UTC    status=INFO_REQUIRED, eff=09:15 UTC   new_eff (09:15) < current_eff (10:00) -> SUPERSEDED
    (delayed!)                                            prior_auths: stays APPROVED, seq=3, v=2 (unchanged!)
                                                          pa_events:   seq=3 recorded with disposition=SUPERSEDED
                                                          work_items:  NO 'INFO_REQUESTED' task created!
    

    Notice two safeguards: first, pa_events still records seq=3 so compliance auditors see the delayed message and why it was ignored; second, prior_auths.version increments only when disposition == 'APPLIED', so harmless duplicate or superseded webhooks do not break an active pharmacist's screen. And if INFO_REQUIRED arrived with eff = 10:30 UTC (newer than approval!), APPROVED -> INFO_REQUIRED is not in ALLOWED, so it records NEEDS_REVIEW, keeps APPROVED provisionally, opens a Tier-1 STATUS_CONFLICT task, and triggers an immediate live API poll to verify with the payer.

  7. Deep dive 2: Concurrent pharmacist worklist and lease locks

    Next, consider how we prevent two pharmacists from working the same case simultaneously. Pure optimistic concurrency (checking a version number only when saving at the end) prevents double writes, after two pharmacists have both wasted 20 minutes drafting duplicate denial appeals! Instead, we combine short-lived row-level lease locks (to prevent duplicate human effort) with optimistic version checks on resolve (to catch mid-review payer updates).

    1. Sub-200ms filtering and sorting. A team has only a few thousand open items. We index (team_id, priority_tier, due_at, item_id) WHERE status IN ('OPEN', 'CLAIMED')—a partial index (an index storing only active rows so resolved history never slows down queries). Rather than OFFSET 200 (which scans and discards 200 rows), we use keyset pagination (passing the last row's sort tuple as the next query's starting cursor):

    SELECT item_id, pa_id, type, priority_tier, due_at,
           CASE WHEN status = 'CLAIMED' AND lease_expires_at > now() THEN claimed_by ELSE NULL END AS active_owner
    FROM work_items
    WHERE team_id = :team_id
      AND status IN ('OPEN', 'CLAIMED')
      AND type = ANY(:types)
      AND (
        :filter = 'all'
        OR (:filter = 'unclaimed' AND (status = 'OPEN' OR lease_expires_at <= now()))
        OR (:filter = 'mine'      AND status = 'CLAIMED' AND claimed_by = :me AND lease_expires_at > now())
      )
      AND (priority_tier, due_at, item_id) > (:cursor_tier, :cursor_due, :cursor_id)
    ORDER BY priority_tier, due_at, item_id
    LIMIT 50;
    

    Treating lease_expires_at <= now() as unclaimed right inside the query guarantees abandoned items stay visible immediately, while a lightweight 1-minute reaper flips expired CLAIMED rows back to OPEN so team SSE feeds update promptly.

    2. Atomic claiming and "Get Next" without collisions. Clicking a specific item runs one conditional UPDATE using the database clock (now()). Clicking "Next Urgent Case" uses FOR UPDATE SKIP LOCKED (a PostgreSQL clause that skips rows currently locked by other transactions instead of waiting), letting 50 pharmacists pull work simultaneously with zero collisions:

    UPDATE work_items w
    SET status = 'CLAIMED',
        claimed_by = :me,
        claim_token = :new_uuid_token,
        lease_expires_at = now() + interval '10 minutes',
        version = w.version + 1
    FROM (
        SELECT item_id FROM work_items
        WHERE team_id = :team_id AND type = ANY(:types)
          AND (status = 'OPEN' OR (status = 'CLAIMED' AND lease_expires_at <= now()))
        ORDER BY priority_tier, due_at, item_id
        LIMIT 1
        FOR UPDATE SKIP LOCKED
    ) target
    WHERE w.item_id = target.item_id
    RETURNING w.item_id, w.pa_id, w.claim_token, w.lease_expires_at;
    

    The browser sends a heartbeat every 60 seconds matching claim_token to slide lease_expires_at forward by 10 minutes. Closing the laptop automatically frees the case within 10 minutes.

    3. Safe resolution and deadlock-free lock ordering. Look at what happens if Pharmacist Alice takes a long phone call, or if a payer approves pa_42 while Alice is submitting an appeal:

    Race A (Stale tab after lease expiry):
      10:00  Alice claims wi_9 -> claim_token = "tok_1", lease_expires_at = 10:10
      10:11  Alice's Wi-Fi dropped; Bob claims wi_9 -> claim_token = "tok_2", lease_expires_at = 10:21
      10:12  Alice reconnects and clicks Resolve with "tok_1" -> token mismatch -> 409 LEASE_LOST!
             (If nobody had claimed wi_9 at 10:12, "tok_1" still matches and Alice's work is saved!)
    
    Race B (Payer webhook arrives mid-appeal):
      10:00  Alice loads pa_42 (status = DENIED, pa_version = 4) and drafts appeal
      10:04  Late payer webhook sets pa_42 -> APPROVED, pa_version = 5, and cancels wi_9
      10:05  Alice clicks Submit Appeal with expected_pa_version = 4 -> 0 rows match -> 409 PA_CHANGED!
    

    In the resolve transaction, we always lock prior_auths before work_items—the exact same lock order used by the status-ingestion service—so a concurrent webhook and pharmacist submission on the same PA can never deadlock:

    BEGIN;
    -- Step 1: Lock prior_auths FIRST (matches ingestion lock order) and verify expected_pa_version.
    UPDATE prior_auths
    SET status = :post_action_status, last_seq = last_seq + 1, version = version + 1, updated_at = now()
    WHERE pa_id = :pa_id AND version = :expected_pa_version
    RETURNING last_seq, last_event_hash;                       -- 0 rows -> ROLLBACK & return 409 PA_CHANGED
    
    -- Step 2: Lock work_items SECOND and verify nobody else took over the lease.
    UPDATE work_items
    SET status = 'RESOLVED', version = version + 1
    WHERE item_id = :item_id AND status = 'CLAIMED' AND claim_token = :claim_token;
                                                               -- 0 rows -> ROLLBACK & return 409 LEASE_LOST
    
    -- Step 3: Append audit row to pa_events & write outbox notification.
    COMMIT;
    
  8. Deep dive 3: Time-zone-aware daily digests without spam

    We decouple daily digests into an aggregation (build) phase and an idempotent dispatch phase partitioned by recipient time zone. Separating them guarantees that retrying a failed network send re-transmits the exact stored email rather than re-running queries at 9:15 AM and sending different numbers.

    Local time:       07:30                        08:00                     08:05          12:00
                        |--- Aggregation Window ---->|--- Dispatch Window ---->|              |
    Scheduler:    creates PENDING run          Dispatchers claim BUILT runs   All 11k      Hard expiry:
                  window = [last_covered,      via SKIP LOCKED, send via      Eastern      any unsent run
                            07:30 today)       ESP with idempotency key =     emails       marked EXPIRED;
    Builder:      queries read replica,        run_id (max 3 retries)         delivered    last_covered stays
                  saves encrypted HTML -> BUILT                                            at yesterday!
    

    1. DST-safe scheduling and gap-free windows. Storing fixed UTC offsets (like UTC-5) breaks twice a year during Daylight Saving Time. Instead, digest_preferences stores the IANA time zone (such as America/New_York) and local_time = 08:00, and computes next_send_at_utc for the next local date. Each minute, a scheduler locks due preferences (next_send_at_utc <= now() + interval '30 minutes') with FOR UPDATE SKIP LOCKED and inserts:

    INSERT INTO digest_runs (run_id, recipient_id, digest_date, window_start, window_end, send_at_utc, status)
    VALUES (:run_id, :user_id, :local_date,
            GREATEST(COALESCE(:last_covered_until, :win_end - interval '24 hours'), :win_end - interval '7 days'),
            :win_end, :send_at_utc, 'PENDING')
    ON CONFLICT (recipient_id, digest_date) DO NOTHING;
    

    Notice why tracking last_covered_until beats querying "now() - 24 hours": - On 23-hour spring-forward or 25-hour fall-back DST days, [last_covered_until, today 07:30) neither misses an hour nor double-reports an hour. - If today has zero changes and zero open tasks, the builder marks the run SKIPPED_EMPTY (preventing alert fatigue) and advances last_covered_until = window_end so tomorrow's builder still scans only 24 hours. - If today's email fails or expires (FAILED / EXPIRED), last_covered_until is not advanced—so tomorrow's digest automatically rolls in yesterday's unnotified changes (capped at 7 days).

    2. Scope-level build caching on read replicas. Ten nurses at the same Chicago clinic all share the exact same [Yesterday 07:30 CT, Today 07:30 CT) window and clinic_id. Builders group PENDING runs by (org_id, scope_id, window_start, window_end), run the indexed pa_events and work_items queries once against a read replica, and render personalized counts per user in memory before storing the summary (status = 'BUILT').

    3. Time-zone-partitioned, spam-free dispatch. Dispatch worker pools are partitioned by time-zone region so a provider slowdown during the 08:00 US Eastern wave cannot block 08:00 Central or Pacific runs. A worker claims a batch (status = 'BUILT' AND send_at_utc <= now(), moving to SENDING, attempts = attempts + 1) and calls the email provider passing Idempotency-Key: <run_id>. - 2xx accepted: mark SENT, record provider_message_id, and advance last_covered_until = window_end. - Hard bounce / invalid email (4xx): mark FAILED, add to suppression list, do not retry. - Timeout / 5xx: leave SENDING with exponential backoff (next_attempt_at at +1m, +5m, +20m). Max 3 attempts, and any run still unsent at send_at_utc + 4 hours transitions to EXPIRED so users never receive a confusing "8:00 AM Morning Briefing" at 3:00 PM.

  9. Scaling, failure modes, and trade-off summary

    Scaling bottlenecks and protections - Clearinghouse file floods: A morning file containing 100,000 updates inserts rapidly into inbound_messages, while normalizer/state workers throttle apply rate to ~500 tx/s using a separate database connection pool so pharmacist queries stay well below 200 ms p95. - Payer API rate limits: Outbound pollers enforce per-payer token buckets (rate limiters capping requests per second) and prioritize PAs with approaching due_at deadlines over quiet PAs. - 10x growth path: Partition pa_events monthly (archiving partitions older than 12 months to immutable WORM—Write-Once-Read-Many—object storage). Beyond a single large Postgres primary (~10,000 write tx/s), shard cleanly by org_id since all PAs, work items, and digests are single-tenant.

    Failure handling and HIPAA security

    Failure scenario System behavior
    Duplicate payer webhook or poll Caught by UNIQUE (payer_id, dedup_key) -> returns 200 OK immediately
    Unrecognized payer status code Marked QUARANTINED in inbound_messages + ops alert; zero data dropped
    State worker crashes mid-commit Transaction rolls back; queue redelivers; state = 'NORMALIZED' guard applies once
    Primary database node fails Synchronous standby promoted in ~30s with zero lost events; payers retry brief 503s
    Pharmacist closes laptop mid-review Heartbeats stop; 10-minute lease expires so peers can claim the item
    Lost payer webhook (never sent) Reconciliation poller queries stale PAs or PAs within 48h of due_at via payer API
    • HIPAA safeguards: TLS 1.3 in transit, KMS-managed encryption at rest, PostgreSQL Row-Level Security enforcing org_id boundaries, Business Associate Agreements (BAAs) with cloud/email vendors, synchronous audit logging of both mutations (pa_events) and PHI reads (phi_access_log), and zero patient names or drug names inside email bodies.

    Summary of core trade-offs - Single PostgreSQL cluster vs. distributed streaming store: Trades theoretical horizontal write infinity (unneeded at 6–1,000 events/s) for rock-solid ACID transactions, row locks, and conditional updates. - Append-only pa_events + prior_auths row vs. pure replay event sourcing: Writes two rows per state change in exchange for 1 ms primary-key reads and a tamper-evident hash-chained audit trail. - Database row leases + version checks vs. external Redis locks: Eliminates split-brain lock drift across failovers at the tiny cost of ~30 heartbeat writes/s for 2,000 active pharmacists. - 30-minute early digest build + stored HTML vs. live 8:00 AM queries: Moves changes between 07:30 and 08:00 into tomorrow's email in exchange for flat database CPU (~0.1 core) and identical, spam-free retries.

Intuition & how it works

Think of this system like a hospital pharmacy control tower managing thousands of insurance requests that trickle back by fax, phone, and courier over weeks. Every incoming payer letter gets stamped into a permanent, numbered ledger book (pa_events)—even duplicate or late letters—while a single index card on top (prior_auths) shows the current valid decision. Whenever a denial or info request arrives, a task folder lands in the pharmacist tray (work_items): picking up a folder clips on a 10-minute timer badge (lease lock) so no colleague duplicates your phone call, and filing your finished appeal checks that no new letter arrived on the index card while you were typing (optimistic version check). Finally, instead of 25,000 staff crowding the filing cabinet at 8:00:00 AM sharp, a night clerk prepares pre-printed summary slips between 7:30 and 8:00 AM from a read-only copy of the ledger so the 8:00 AM mailroom simply hands out finished envelopes.

A naive CRUD design breaks down in three ways. First, overwriting prior_auths.status in place ("last webhook wins") destroys the clinical audit trail and lets a delayed "Pending Info" webhook accidentally erase an "Approved" decision that arrived five minutes earlier. Second, letting pharmacists browse a plain list and click "Submit" without short-lived claims means two pharmacists routinely spend 20 minutes writing an appeal for the exact same denial. Third, running live COUNT and JOIN queries over 24 hours of events at 8:00:00 AM for 11,000 Eastern-time users creates a thundering herd (thousands of identical heavy queries hitting the database at the same millisecond) and risks sending different, duplicate emails whenever retries re-run the query.

Concrete walkthrough of one PA (pa_42) across ingestion, review, and digest: 1. Duplicate & out-of-order webhooks: At 10:02, Payer X sends {status: "DENIED", effective_at: "10:00"}. Our gateway saves the raw payload in inbound_messages (UNIQUE (payer_id, dedup_key)), returns 200 OK, appends seq = 2 (APPLIED) to pa_events, sets prior_auths to status = DENIED, version = 2, and opens work item wi_9 (DENIAL_APPEAL) in the same transaction. At 10:03, Payer X retries the exact same webhook (ON CONFLICT DO NOTHING -> instant 200 OK, zero duplicate events). At 10:04, an older delayed webhook {status: "PENDING_PAYER", effective_at: "09:30"} arrives: because 09:30 < 10:00, we log seq = 3 (SUPERSEDED) in pa_events for auditability while keeping status = DENIED, version = 2 untouched. 2. Concurrent pharmacist claim: Pharmacists Alice and Bob both click "Next Urgent Case". PostgreSQL's FOR UPDATE SKIP LOCKED gives wi_9 to Alice (claim_token = "tok_1", 10-minute lease) and immediately hands Bob the next row (wi_10) without blocking. 3. Mid-review race protection: While Alice drafts her appeal against expected_pa_version = 2, her browser heartbeats every 60 seconds. When she submits APPEAL_SUBMITTED, one transaction verifies prior_auths.version = 2 (bumping it to 3 and setting status = APPEALED) and work_items.claim_token = "tok_1" (marking wi_9 RESOLVED). 4. Morning digest: At 07:30 local time the next morning, a builder reads seq = 2 and seq = 3 from a read replica once for Alice's clinic, writes a PHI-free count summary ("1 PA appealed, 0 urgent items due") into digest_runs (status = BUILT), and at 08:00 a dispatcher sends that stored email with Idempotency-Key = run_id.

Key trade-offs

  • Single relational cluster vs. distributed event-streaming platform. An event-streaming log (such as Kafka storing long-term history with separate microservices building read views) scales to hundreds of thousands of writes per second, but introduces eventual-consistency lag between status updates and worklist items. At ~6 events/s average (~1,000/s burst), a single PostgreSQL primary with a synchronous standby (a replica that confirms every write before commit so zero data is lost on failover) enforces idempotency, row locking, and worklist creation in one local ACID transaction (an all-or-nothing database operation).
  • Append-only pa_events + mutable prior_auths row vs. pure replay event sourcing. Pure event sourcing reconstructs current state by replaying every past event on read, which complicates schema evolution and slows lookups over multi-year PAs. Writing both an immutable pa_events row and a current-state prior_auths row inside the same transaction doubles write statements (trivial at this scale) in exchange for 1 ms primary-key reads and a complete compliance timeline.
  • Ordering by payer effective_at + human review vs. arrival-time "last write wins". Trusting arrival order is simple to code, but webhooks traverse different queues and clearinghouses and regularly arrive out of order. Comparing payer effective_at first prevents stale messages from overwriting newer clinical decisions, while routing illegal jumps (like APPROVED -> INFO_REQUIRED with a newer timestamp) to a NEEDS_REVIEW task trades a few minutes of pharmacist time to avoid dangerous clinical errors.
  • Database row leases + optimistic version checks vs. external Redis locks. Putting claim_token and lease_expires_at directly on the work_items row means the lock and the task live in the same database and can never drift apart during a crash, unlike a separate Redis lock. Combining a 10-minute lease (preventing duplicated human effort) with expected_pa_version on submit (catching concurrent payer updates) gives both UX safety and data safety, at the small cost of ~30 heartbeat updates/s.
  • Pre-built 07:30 digests + stored content vs. on-the-fly 08:00 queries. Freezing the digest window at 07:30 local time pushes status changes between 07:30 and 08:00 into tomorrow's email. In return, aggregation spreads smoothly over 30 minutes on a read replica (~0.1 CPU core), clinic-level queries are shared across colleagues, and network retries resend identical stored content.
  • Bounded at-least-once email vs. unbounded retries. Because external email servers do not all support exactly-once delivery (guaranteeing one and only one inbox copy across network drops), capping retries at 3 attempts with run_id deduplication and expiring unsent runs after 4 hours prevents retry storms and afternoon "morning digests", while rolling any expired run's window forward into tomorrow's digest so no event is ever lost.

Common mistakes

  • Overwriting PA status in place without an immutable event table: Destroys the HIPAA audit trail and makes debugging out-of-order payer webhooks impossible.
  • Processing webhooks synchronously before storing them (or returning 4xx/5xx for duplicates): Causes payers to retry endlessly or loses updates whenever normalization hits an unexpected field.
  • Deduplicating keyless polls by hashing only (payer_case_ref, status): Silently drops a legitimate state transition when a PA moves PENDING_PAYER -> INFO_REQUIRED -> PENDING_PAYER without timestamps.
  • Incrementing prior_auths.version on NO_CHANGE or SUPERSEDED webhooks: Causes an active pharmacist's submit to fail spuriously with 409 PA_CHANGED when the clinical status never actually changed.
  • Checking worklist availability with SELECT before UPDATE: Lets two pharmacists read status = 'OPEN' simultaneously and claim the same PA; claiming must happen in one conditional UPDATE (or FOR UPDATE SKIP LOCKED).
  • Inconsistent lock ordering between ingestion and worklist resolution: Locking prior_auths then work_items in ingestion, while locking work_items then prior_auths on pharmacist resolve, causes PostgreSQL deadlocks under concurrent updates to the same PA.
  • Using "last 24 hours" or fixed UTC offsets (UTC-5) for digests: Fixed offsets send emails at 7:00 AM or 9:00 AM half the year due to Daylight Saving Time, and "now() - 24h" creates 1-hour gaps or duplicates on DST transition days and drops events after a failed send.
  • Including patient names, dates of birth, or medication names directly in email text: Standard SMTP email can be forwarded, cached on unmanaged phones, or misdelivered, creating severe PHI exposure risks.

Follow-up questions

  • What happens when insurer webhooks arrive out of sequence—for instance, an approval arrives five minutes before an earlier request for extra clinical documentation? Both raw webhooks are saved durably and both append a numbered row to pa_events so the audit log reflects everything received. When the delayed INFO_REQUIRED event is processed, our state service compares its payer effective_at timestamp against the current APPROVED event's effective_at: because the documentation request is older, it is recorded with disposition = 'SUPERSEDED', prior_auths.status stays 'APPROVED', version is not bumped, and no pharmacist task is created. If the payer omitted timestamps—or if INFO_REQUIRED carried a newer timestamp suggesting the payer reopened the case—APPROVED -> INFO_REQUIRED is rejected by the automatic transition table, logged as NEEDS_REVIEW, paired with a high-priority STATUS_CONFLICT pharmacist task, and triggers an immediate live API poll to confirm the authoritative payer status.
  • How do you keep 8:00 AM local-time digest deliveries across major time zones from triggering a database thundering herd? We decouple aggregation from dispatch and spread database reads across a 30-minute pre-build window (07:30 to 08:00 local time) against read replicas, completely isolating the primary database. Instead of scanning full tables per user, builders group recipients by clinic or team so all staff sharing a clinic and time zone execute just three fast partial-index queries ((clinic_id, received_at) and (team_id, priority_tier, due_at)) once per window, requiring roughly 0.1 database CPU core for an 11,000-user US Eastern wave. At 08:00, time-zone-partitioned dispatch workers simply fetch pre-rendered content via FOR UPDATE SKIP LOCKED and stream emails through a rate-limiting token bucket (~38 emails/s over 5 minutes) so one time zone's backlog never delays the next.
  • What technical and operational controls keep daily email summaries HIPAA-compliant when handling protected health information (PHI)? Apply HIPAA's minimum-necessary rule by keeping email bodies completely free of PHI by default—sending only aggregate counts ("3 PAs changed status overnight, 2 appeals due within 24 hours") alongside a time-limited link to our authenticated web portal protected by MFA (Multi-Factor Authentication) and clinic-level authorization checks. Every vendor in the delivery path operates under a signed BAA (Business Associate Agreement—a legal HIPAA contract binding vendors to protect health data), and if an enterprise customer explicitly opts into including internal case IDs, we enforce mandatory TLS (Transport Layer Security encryption) to the receiving mail server and fall back to the portal-only template whenever TLS is unsupported. Finally, we log every digest generation and portal view in an immutable audit log, honor opt-outs immediately, and auto-suppress hard-bouncing addresses so summaries never go to a recycled inbox.

Follow-up questions

Similar questions

More Latent interview questions

All 1 Latent questions →