Health Insurance Claims Adjudication and Payout System
Medium · System Design · Software Engineer · Technical Screen
Prompt
Architect a complete claims adjudication and payout platform for a health insurance carrier. Your platform owns every stage of a medical claim—from initial filing and benefit-rule evaluation through manual review, disbursement, and regulatory audit logging—while cleanly accommodating multi-year data growth.
Support four distinct user personas and end-to-end capabilities:
- Personas:
- Enrolled members: File claims, attach itemized bills or clinical records (PDFs and photos), and check claim progress on web or mobile.
- Healthcare providers (clinics & hospitals): Submit claims directly on a patient's behalf.
- Claims adjusters: Work prioritized queues, filter and search claims, request missing documentation, approve or reject line items, and authorize payouts.
- Operations admins: Author and publish benefit rules, monitor operational metrics and reports, and inspect compliance history.
- Lifecycle & capabilities: Each submission references member and policy IDs, lists one or more line items (clinical procedures, services, or prescriptions with dates, standard billing codes, and amounts), and links binary attachments. Automated checks evaluate benefit caps, prior authorizations, and plan exclusions, advancing claims across
Submitted -> Under review -> Pending info -> Approved / Denied -> Paidwhile recording an immutable audit history of who viewed or changed what and when. - Operating constraints & boundaries: Assume tens of thousands of active enrollees accumulating millions of claims over several years (only a few writes/sec at peak), zero data loss for accepted submissions,
~200–500 msread latency for status/history views (with asynchronous adjudication after fast intake), and strict HIPAA-grade PHI protection (encryption in transit and at rest, least-privilege access, and full auditability). Existing external systems already serve as the Policy Administration System (PAS) for member/policy/benefit records and the payment processor for moving funds.
Scope & Expectations
- APIs, schemas & workflow state machine: Define intake, status, and adjuster endpoints, relational schemas for core entities (
Claim,ClaimItem,Policy,Member,Attachment,ClaimEvent,Payment), and guarded transitions across the claim lifecycle. - Architecture, storage & integrations: Draw the service boundaries, database and object-storage choices, external PAS and payment-gateway integrations, and downstream analytics/reporting pipeline.
- Consistency, concurrency & reliability: Show how you prevent conflicting adjuster actions, eliminate lost or duplicate payouts across service boundaries, and guarantee zero claim loss.
- Security & compliance: Detail authentication, role- plus ownership-based authorization, PHI handling, and immutable mutation/read audit trails.
Step-by-step walkthrough
Clarify scope, ownership, and requirements
Before sketching services, draw a sharp boundary between what our system owns and what external systems own—that boundary determines where our transactional guarantees live.
- We own: Claim intake, document tracking, automated adjudication (evaluating coverage rules and pricing a claim), human adjuster workflows, annual benefit-usage counters, the compliance audit trail, and payment orchestration.
- We integrate with:
- PAS (Policy Administration System): The authoritative system of record for members, dependents, active policies, and plan benefit rules.
- External Payment Processor: Moves money via ACH/EFT or card networks and sends settlement reports.
- Healthcare Clearinghouse: Exchanges standardized provider batch files (EDI X12 837 inbound claims and 835 outbound payment remittances).
Functional requirements
- Claim submission: Members and providers submit claims with 1+ line items (procedure/drug codes, service dates, amounts) and PDF/image attachments, receiving a claim ID immediately while adjudication runs asynchronously.
- Validation and workflow: Validate coverage, pre-authorizations, duplicates, and annual caps; drive claims through
SUBMITTED -> UNDER_REVIEW -> PENDING_INFO -> APPROVED / DENIED -> PAID. - Member & adjuster experiences: Members view status and history in
200–500 ms; adjusters pull from prioritized queues, search claims, request documents, and approve/deny lines. - Payouts, rules, and audit: Trigger payouts on approval, let admins publish coverage rules safely, and record an immutable audit trail of both changes and views.
Non-functional requirements & assumptions
- Scale: 50,000 active members (~20 claims/member/year =
1,000,000 claims/year), growing 30% annually. Target 70% auto-adjudication; 30% routed to human adjusters. - Durability & financial safety: RPO = 0 (Recovery Point Objective of zero—zero loss of any acknowledged claim) and zero double payments across crashes or timeouts.
- HIPAA-grade security: Encrypt all PHI (Protected Health Information—identifiable medical records) in transit and at rest, enforce least-privilege access, retain audit records for 7+ years, and log read access separately from state mutations.
- Pending-info policy: Send reminders at days 7 and 30 and escalate to an adjuster at day 45 rather than auto-denying by timer (matching US ERISA post-service 45-day claimant response protections).
Back-of-the-envelope numbers
1. Claim volume & throughput - Annual claims today: 50,000 members x 20 claims/yr = 1,000,000 claims/year - 5-year total (30% growth): 1.0M + 1.3M + 1.69M + 2.20M + 2.86M ≈ 9.05M stored claims - Daily average: 1,000,000 / 365 ≈ 2,740 claims/day - Peak hour (post-holiday): 2x daily volume, 10% in peak hour ≈ 550 claims/hr ≈ 0.15 claims/s (even a 20x batch burst is only ~3 claims/s!) 2. Database write & read rates - Writes over a claim's life: ~25 rows (claim, ~3 items, ~2 attachments, ~6 transitions x [claim_event + outbox], benefit entry, payment, timers) - Average DB row writes: 2,740 x 25 / 86,400 s ≈ 0.8 row writes/s (~4-40 writes/s on bursts) - Member status reads: ~50,000/day -> ~10 reads/s at peak - Human adjuster load: 30% manual = 300,000/yr ≈ 1,200/workday -> ~30 adjusters online - Total read QPS: Well under 100 req/s! 3. 5-year storage footprint - Relational tables + indexes: 9M claims x ~10 KB ≈ 90 GB (easily fits on one DB server!) - Attachments (PDFs/photos): 1M claims/yr x 2 files x 1 MB = ~2 TB/year (in object storage) - PHI read-access audit log: ~100,000 views/day x 300 B ≈ 30 MB/day (~11 GB/year)Why this math drives every architectural choice: - This is a correctness-and-compliance problem, NOT a high-QPS sharding problem. At ~1–40 row writes/s and 90 GB over five years, sharding or splitting into a dozen microservices would introduce distributed-transaction bugs for zero throughput benefit. One unsharded PostgreSQL cluster handles 100x this volume while giving us local ACID transactions. - Attachments and access logs dominate byte growth, so binary files belong in encrypted object storage and read logs belong in monthly-partitioned tables.
APIs and user flows
Every mutating endpoint requires an
Idempotency-Key(a client-generated UUID per action so network retries never create duplicate claims or payouts), and every decision suppliesexpected_versionto prevent lost updates.1. Member / Provider Submission Flow (2 steps: direct file upload, then fast async submit) POST /v1/attachments/upload-slots Body: { "files": [ { "content_type": "application/pdf", "size_bytes": 745200, "sha256": "..." } ] } -> 201 { "slots": [ { "attachment_id": "att_4c", "presigned_put_url": "https://...", "ttl_s": 900 } ] } POST /v1/claims Headers: Authorization, Idempotency-Key: <client-uuid> Body: { "member_id": "MBR_804", "policy_id": "POL_219", "dependent_id": null, "provider_id": "PRV_44", "currency": "USD", "attachment_ids": ["att_4c"], "items": [ { "type": "SERVICE", "code_system": "CPT", "code": "97140", "service_date": "2026-09-14", "quantity": 1, "claimed_cents": 12000 } ] } -> 202 Accepted { "claim_id": "clm_09K", "reference": "CLM-2026-008410", "status": "SUBMITTED", "version": 1 } -> 409 IDEMPOTENCY_KEY_CONFLICT (same key reused with different payload hash) 2. Member Status & Follow-Up APIs GET /v1/claims?member_id=MBR_804&cursor=... GET /v1/claims/{claim_id} // Current status, line-item decisions, payout status GET /v1/claims/{claim_id}/history // Member-visible timeline from claim_events POST /v1/claims/{claim_id}/info // Upload extra docs / reply to PENDING_INFO POST /v1/claims/{claim_id}/withdraw // Body: { "expected_version": 2 } 3. Adjuster Work Queue & Adjudication APIs POST /v1/work-queue/next // Body: { "queues": ["dental", "paramed"] } -> 200 { "claim_id": "clm_09K", "version": 3 } POST /v1/claims/{claim_id}/actions Headers: Authorization, Idempotency-Key: <client-uuid> Body: { "action": "APPROVE" | "DENY" | "REQUEST_INFO" | "REASSIGN", "expected_version": 3, "item_decisions": [ { "line_no": 1, "decision": "APPROVED", "approved_cents": 9000, "reason_codes": ["COINSURANCE_75"] } ], "note": "Invoice verified; 75% plan coverage." } -> 200 { "status": "APPROVED", "version": 4 } -> 409 VERSION_CONFLICT | 403 OVER_AUTHORITY_LIMIT GET /v1/claims/search?status=UNDER_REVIEW&member_id=MBR_804&min_cents=40000&sort=age 4. Admin Rule-Versioning APIs POST /v1/rule-sets // Create immutable DRAFT version POST /v1/rule-sets/{id}/approve // Four-eyes approval by a second admin POST /v1/rule-sets/{id}/publish // Activate for service dates >= effective_fromNotice presigned URLs in Step 1: a presigned URL is a short-lived, cryptographically signed link letting the browser upload a 5 MB PDF directly to encrypted object storage, keeping bulky binary streams out of our API servers and database.
Data model
Money is stored strictly as integer minor units (
BIGINTcents +CHAR(3)currency—never floating-point numbers, which introduce0.01rounding bugs). Although the external PAS ownsMemberandPolicymaster records, we maintain read-only synced reference tables (members_ref,policies_ref) plus immutable point-in-timecoverage_snapshotsso member authorization checks still work even during a PAS outage:members_ref // Read-only projection synced from PAS events (PAS is system of record) member_id PK, primary_subscriber_id, policy_id, relationship ('SELF'|'SPOUSE'|'CHILD'), status policies_ref // Read-only projection synced from PAS policy_id PK, plan_id, group_id, currency CHAR(3), effective_from DATE, effective_to DATE NULL claims // Core lifecycle aggregate claim_id UUID PK, reference TEXT UNIQUE, member_id FK, policy_id FK, dependent_id NULL, provider_id NULL, submitted_by_type ('MEMBER'|'PROVIDER'|'EDI'), submitted_by_id TEXT, idempotency_key TEXT, request_hash TEXT, UNIQUE (submitted_by_id, idempotency_key), status TEXT, version INT NOT NULL, received_at TIMESTAMPTZ, service_date_from DATE, service_date_to DATE, total_claimed_cents BIGINT, total_approved_cents BIGINT NULL, currency CHAR(3), queue TEXT, priority INT, assigned_adjuster_id NULL, due_at TIMESTAMPTZ NULL, rule_set_version INT NULL, coverage_snapshot_id UUID NULL, INDEX (member_id, received_at DESC), INDEX (status, queue, priority DESC, due_at, received_at) claim_items // Individual procedures, services, or medications on a claim (claim_id, line_no) PK, item_type ('PROCEDURE'|'SERVICE'|'MEDICATION'), code_system TEXT, code TEXT, service_date DATE, quantity INT, claimed_cents BIGINT, decision ('PENDING'|'APPROVED'|'PARTIAL'|'DENIED'), approved_cents BIGINT NULL, member_resp_cents BIGINT NULL, benefit_code TEXT NULL, reason_codes TEXT[] attachments // Metadata only; binary file lives in encrypted S3/GCS attachment_id UUID PK, claim_id UUID NULL, uploaded_by TEXT, object_key TEXT, sha256 TEXT, size_bytes BIGINT, content_type TEXT, scan_status ('PENDING'|'CLEAN'|'INFECTED') claim_events // Append-only mutation audit trail (INSERT + SELECT only for app role) (claim_id, seq) PK, event_type TEXT, from_status TEXT, to_status TEXT, actor_type TEXT, actor_id TEXT, payload JSONB, created_at TIMESTAMPTZ payments // Owned by Payment Service; payment_id doubles as processor idempotency key payment_id UUID PK, claim_id UUID, payee_type ('MEMBER'|'PROVIDER'), payee_token TEXT, payment_seq INT, UNIQUE (claim_id, payee_type, payment_seq), amount_cents BIGINT, currency CHAR(3), status ('CREATED'|'SUBMITTED'|'UNKNOWN'|'CONFIRMED'|'FAILED'|'RETURNED'), processor_ref TEXT NULL, attempts INT, created_at TIMESTAMPTZ, updated_at TIMESTAMPTZ Supporting consistency & compliance tables: benefit_accumulators (member_id, benefit_code, plan_year) PK, limit_cents BIGINT, used_cents BIGINT CHECK (used_cents >= 0 AND used_cents <= limit_cents) accumulator_entries entry_id PK, member_id, benefit_code, plan_year, claim_id, line_no, delta_cents rule_sets (rule_set_id, version) PK, status, effective_from DATE, rules JSONB, approved_by coverage_snapshots snapshot_id UUID PK, policy_id, pas_payload JSONB, fetched_at TIMESTAMPTZ outbox id BIGSERIAL PK, aggregate_id, event_type, payload JSONB, published_at NULL processed_messages (consumer, message_id) PK timers timer_id UUID PK, claim_id, kind, due_at TIMESTAMPTZ, fired_at NULL phi_access_log actor_id, actor_role, action, resource_id, member_id, at TIMESTAMPTZ (partitioned monthly so old partitions archive/drop cleanly!)Why keep
claim_eventsunpartitioned while partitioningphi_access_logby month?claim_eventsgrows by only ~8M rows/year and relies on a global(claim_id, seq)primary key to guarantee gap-free state-machine ordering—which PostgreSQL cannot enforce across monthly partitions withoutcreated_atin the key.phi_access_loghas no cross-month uniqueness constraint and grows ~36M rows/year, making monthly partitions ideal.High-level architecture
Members (Web/Mobile) Providers (REST API) Clearinghouse (EDI 837 in / 835, 277CA out) | | | v v v +-----------------------------------------+ +-------------------+ | API Gateway (TLS 1.3, OIDC/mTLS, | | EDI Gateway |-- parses X12 837 | rate limits, request tracing) | +---------+---------+ into internal +--------------------+--------------------+ | POST /v1/claims | | v v +----------------------------------------------------------------------------+ | Claims Core (Modular Monolith + Async Adjudication & Timer Workers) |---> [ External PAS ] | intake | finite state machine | rules & pricing | work queue | RBAC+ABAC |<--- (eligibility & +--------------------+---------------------------------------------+---------+ plan sync) 1 ACID tx: claims | claim_events + outbox + phi_access_log | presigned URLs v v +-----------------------------------------+ +-------------------+ | PostgreSQL Primary (AZ 1) | | Object Storage | | + Synchronous Standby (AZ 2, RPO = 0) | | (quarantine -> | | + Read Replica + WAL Archive (PITR) | | AV scan -> clean)| +--------------------+--------------------+ +-------------------+ | Outbox Relay v +----------------------------------------------------------------------------+ | At-Least-Once Message Bus (Kafka / SQS-SNS) | +----+-------------------+-------------------+----------------+--------------+ | | | | v v v v [Payment Service] [Notification Svc] [Search Indexer] [Warehouse & WORM] (own DB + tokens) (email/push: zero (OpenSearch for (analytics marts + | PHI in text!) free-text/ops) hash-chained audit) v [External Payment Processor] (webhooks + daily settlement file)Architectural rationale: - Modular monolith over microservices: Intake, adjudication, and adjuster workflows share one codebase and one PostgreSQL primary so status transitions, audit events, benefit reservations, and outbox rows commit atomically. - Isolated Payment Service: Payments split into a separate service and database because bank tokens, processor API credentials, and settlement reconciliation carry distinct PCI/financial blast-radius boundaries. - Two-stage attachment quarantine: Uploaded files land in an isolated quarantine bucket prefix; claims wait until an asynchronous antivirus/malware worker verifies
scan_status = 'CLEAN'and moves the object to the clean prefix.Deep dive 1: Finite state machine and adjuster concurrency
Modeling
claims.statusas a free-form string updated across scattered endpoints invites race conditions. Instead, every lifecycle change passes through one finite state machine (FSM)—a strict lookup table mapping(current_status, action) -> next_status:Current Status Action Allowed Actor Next Status -------------------------- -------------- ------------------- ------------ (new) submit member/provider/EDI SUBMITTED SUBMITTED auto_approve adjudication worker APPROVED SUBMITTED auto_deny adjudication worker DENIED SUBMITTED route_manual adjudication worker UNDER_REVIEW UNDER_REVIEW request_info assigned adjuster PENDING_INFO PENDING_INFO info_received member/provider UNDER_REVIEW UNDER_REVIEW info_received member/provider UNDER_REVIEW (attaches late doc!) PENDING_INFO escalate_sla timer worker (d=45) UNDER_REVIEW (flags overdue) UNDER_REVIEW approve assigned adjuster APPROVED UNDER_REVIEW deny assigned adjuster DENIED APPROVED mark_paid payment consumer PAID (once ALL payees paid) SUBMITTED / UNDER_REVIEW / withdraw member/provider WITHDRAWN PENDING_INFOEvery transition executes compare-and-set (an atomic SQL
UPDATEthat succeeds only ifstatusandversionstill match what the caller read) alongside the audit event and outbox message in one local transaction:TRANSITIONS = { ("SUBMITTED", "auto_approve"): "APPROVED", ("SUBMITTED", "auto_deny"): "DENIED", ("SUBMITTED", "route_manual"): "UNDER_REVIEW", ("UNDER_REVIEW", "request_info"): "PENDING_INFO", ("PENDING_INFO", "info_received"): "UNDER_REVIEW", ("UNDER_REVIEW", "info_received"): "UNDER_REVIEW", ("PENDING_INFO", "escalate_sla"): "UNDER_REVIEW", ("UNDER_REVIEW", "approve"): "APPROVED", ("UNDER_REVIEW", "deny"): "DENIED", ("APPROVED", "mark_paid"): "PAID", ("SUBMITTED", "withdraw"): "WITHDRAWN", ("UNDER_REVIEW", "withdraw"): "WITHDRAWN", ("PENDING_INFO", "withdraw"): "WITHDRAWN", } def apply_claim_action(db, claim, action, actor, expected_version, payload): """Execute one guarded state transition + audit log + outbox event atomically.""" next_status = TRANSITIONS.get((claim.status, action)) if next_status is None: raise ValueError(f"Illegal transition: {claim.status} + {action}") # Enforce RBAC + object ownership / assignee check + dollar approval authority limit. verify_authorization(actor, action, claim, payload) with db.transaction(): # Compare-and-set: row lock serializes concurrent actors; loser updates 0 rows. rows = db.execute( """ UPDATE claims SET status = %s, version = version + 1, updated_at = now() WHERE claim_id = %s AND status = %s AND version = %s """, (next_status, claim.claim_id, claim.status, expected_version), ) if rows == 0: raise RuntimeError("VERSION_CONFLICT: reload claim and retry") # seq = expected_version + 1 enforces a 1-to-1 gap-free audit row per version bump. db.execute( """ INSERT INTO claim_events (claim_id, seq, event_type, from_status, to_status, actor_type, actor_id, payload, created_at) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, now()) """, (claim.claim_id, expected_version + 1, action, claim.status, next_status, actor.kind, actor.id, payload), ) # Transactional outbox guarantees downstream services learn of the committed change. db.execute( "INSERT INTO outbox (aggregate_id, event_type, payload, created_at) VALUES (%s, %s, %s, now())", (claim.claim_id, f"claim.{action}", payload), )How adjusters avoid stepping on each other: - Collision-free queue pull:
POST /v1/work-queue/nextselects the highest-priority unassignedUNDER_REVIEWrow usingFOR UPDATE SKIP LOCKED(ordered bypriority DESC, due_at ASC, received_at ASC), setsassigned_adjuster_id, bumpsversion, and logsASSIGNED. Thirty adjusters clicking "Next" simultaneously never block or receive the same claim. - No lost late uploads: Notice("UNDER_REVIEW", "info_received") -> "UNDER_REVIEW". If the day-45escalate_slatimer fires one second before a member finishes uploading a medical receipt, the member's retry reloads the claim inUNDER_REVIEWand still attaches the receipt cleanly rather than failing!Deep dive 2: Auto-adjudication, versioned rules, and benefit caps
Background workers claim
SUBMITTEDrows (once attachments areCLEAN) and run a 7-step pipeline: 1. Structural check: Valid procedure/drug codes, non-future service dates, positive integer cents. 2. PAS eligibility: Fetch member/dependent coverage onservice_dateand save an immutablecoverage_snapshotsrow. 3. Business duplicate check: Flag if another open or paid claim has the same(member_id, provider_id, code, service_date)(distinct from HTTP idempotency, which catches network retries of the same submission). 4. Versioned rule evaluation: Select theACTIVErule_setsversion whoseeffective_from <= item.service_date(checking exclusions, frequency caps, and prior authorizations). Recordingrule_set_versionandcoverage_snapshot_idonclaimsmakes every past decision 100% reproducible and ensures admin rule edits never silently alter settled claims. 5. Pricing: Apply allowed amount, deductible, and coinsurance in integer cents per line. 6. Atomic annual benefit reservation (race condition fix!): Suppose MemberMBR_804has a600 USD(60000cents) annual manual-therapy cap with54000cents already used, and submits two100 USD(10000cent) claims at the exact same moment:Naive read-then-write bug: Worker A reads used_cents = 54000 -> sees 6000 left -> approves 6000 cents Worker B reads used_cents = 54000 -> sees 6000 left -> approves 6000 cents -> Paid 660 USD on 600 USD cap! Safe row-locked reservation inside the decision transaction: Worker A: SELECT used_cents, limit_cents FROM benefit_accumulators WHERE (member_id, benefit_code, plan_year) = ('MBR_804', 'THERAPY', 2026) FOR UPDATE; -> locks row; computes approved = min(eligible=10000, 60000 - 54000) = 6000 cents (PARTIAL) -> UPDATE used_cents = 60000 + INSERT accumulator_entries (+6000) + COMMIT. Worker B: unblocks; reads updated used_cents = 60000 -> computes min(10000, 0) = 0 cents -> DENIED (MAX_REACHED)!- Routing: Clean claims below the auto-approval dollar threshold execute
auto_approve; clear non-coverage executesauto_deny; everything ambiguous routes toUNDER_REVIEWwith machine-generated flags shown to the adjuster.
- Routing: Clean claims below the auto-approval dollar threshold execute
Deep dive 3: Avoiding dual writes and paying exactly once
Updating
claims.status = 'APPROVED'in PostgreSQL and directly calling an HTTP payment service is a classic dual-write bug: a crash between the two either approves a claim that never gets paid, or pays money for an unapproved claim!We combine the transactional outbox, idempotent consumers, and persisted payment idempotency keys:
[Claims Core DB] [Message Bus] [Payment Service + Own DB] ---------------- ------------- -------------------------- BEGIN; claims.status = 'APPROVED' INSERT claim_events ('approve') INSERT outbox ('claim.approved') COMMIT; | +---> Outbox Relay polls ----> publishes ----------> Consumer tx: unpublished rows at-least-once INSERT processed_messages (skip on dup) INSERT payments (payment_id = uuid, UNIQUE (claim_id, payee_type, seq=1)) | v Payment Worker calls Processor: POST /payouts Idempotency-Key: <payment_id> - 2xx -> status = SUBMITTED - timeout / 5xx -> status = UNKNOWN (retry later with SAME payment_id!) | +<--- 'payment.confirmed' <--- Webhook / Daily <---------------+ marks claim PAID Settlement File status = CONFIRMED (once ALL payees for claim are CONFIRMED!)Why double payment is impossible: 1. Duplicate bus delivery: Blocked by
processed_messagesandUNIQUE (claim_id, payee_type, payment_seq). Noticepayee_typeallows a single claim to split payout cleanly (for example, paying the clinic directly for Line 1 and reimbursing the member for Line 2), transitioning the parent claim fromAPPROVEDtoPAIDonly when everypaymentsrow forclaim_idreachesCONFIRMED. 2. Processor HTTP timeout:payment_idis generated and committed topaymentsbefore the first network call. Every retry reuses that exactpayment_id, so the processor deduplicates retries on its side. 3. Morning settlement reconciliation: Every day, a batch job diffs the processor's settlement file againstpaymentsbypayment_id, flagging any missing, returned, or mismatched transfer for finance operations and generating provider EDI 835 remittances.Security, integrations, failure handling, and trade-offs
HIPAA security and access control - Authentication: OIDC + MFA for members, mutual TLS + OAuth2 client credentials for providers, corporate SSO + mandatory MFA for adjusters and admins. - RBAC + Object-Level Authorization: Role-Based Access Control (
role = MEMBER) is never sufficient alone—every read and write enforces relationship rules (claim.member_id == caller.idor an authorized dependent inmembers_ref; providers see only claims they submitted; adjusters cannot adjudicate their own or family claims and cannot exceed their dollar authority limit), backed by PostgreSQL Row-Level Security returning404on unauthorized IDs. - Two distinct audit logs:claim_eventsrecords who changed what, whilephi_access_logsynchronously records every PHI view, search, and attachment download (failing closed if logging fails). Both streams ship hourly to WORM (Write-Once-Read-Many object-locked) storage with cryptographic hash chains. - Zero PHI leakage: Push notifications and emails say"Your claim CLM-2026-008410 has an update"—never procedure names or diagnoses. Bank account numbers stay tokenized inside the payment processor.Failure modes and resilience
Failure scenario System response Primary DB host crashes Synchronous AZ-2 standby promoted in ~30s (RPO = 0, zero lost claims); clients retry idempotently External PAS outage POST /v1/claimsand member reads keep working viamembers_ref; adjudication pauses inSUBMITTEDand retries with backoffPayment processor timeout Payment enters UNKNOWN; retried with identicalpayment_idor resolved via lookup / daily settlement fileMalware scanner backlog Claims with PENDINGattachments wait safely before adjudication; ops alert fires on queue ageEDI 837 file sent twice EDI gateway derives Idempotency-Keyfrom(partner_id, hash(claim_segments))-> duplicates ignored cleanlySummary of core trade-offs - Modular monolith + single Postgres primary vs. sharded microservices: Trades independent sub-service deployability for rock-solid local ACID transactions across claims, benefit caps, audit events, and outbox rows at ~1–40 writes/s. - Async adjudication (
202 Accepted) vs. synchronous decision: Adds a briefSUBMITTEDstate in the UI in exchange for fast< 200 msintake that survives PAS slowdowns and post-holiday spikes. - Immutable effective-dated rule sets vs. in-place rule edits: Requires a draft/approve/publish workflow for admins in exchange for 100% reproducible historical audits. - Escalate-to-human vs. auto-deny onPENDING_INFOexpiry: Adds small adjuster review load at day 45 in exchange for avoiding wrongful automated denials, regulatory penalties, and costly member appeals.
Intuition & how it works
Think of an insurance claims system not as a high-speed social media feed, but as a regulated claims courthouse attached to a bank vault. Even a health insurer with 50,000 members only receives around 2,700 claims per day (~1–4 writes per second)—so the challenge is never raw throughput; it is ironclad financial and medical correctness. Every claim gets a numbered case folder (claims) whose status can only advance along legal steps on a printed state chart (finite state machine), every decision stamps an uneditable entry into the court transcript (claim_events), every person who even opens a folder signs a visitor logbook (phi_access_log), and approved payouts drop a sealed payment slip into an outgoing mail chute (transactional outbox) inside the exact same database commit so a server crash can never approve a claim without paying it—or pay the same claim twice.
A naive design goes wrong in three classic places. First, splitting a 2-writes-per-second system into sharded NoSQL microservices destroys local transactions right where you need atomic updates across claim status, annual benefit caps, and audit logs. Second, updating status without compare-and-set (checking the exact expected status and version number inside the UPDATE) lets two adjusters—or an adjuster and a member withdrawal—overwrite each other. Third, updating the database to 'APPROVED' and then calling a payment API over HTTP (dual write) either drops the payout if the server crashes in between, or double-pays the provider if a network timeout triggers a retry with a fresh request ID.
Concrete walkthrough of a 120 USD (12000 cent) manual-therapy claim (clm_09K):
1. Idempotent intake (version = 1): Member MBR_804 uploads a PDF invoice directly to an encrypted quarantine bucket via a presigned URL (a short-lived signed upload link) and sends POST /v1/claims with claimed_cents = 12000 and Idempotency-Key = "k_4". Our core commits clm_09K (status = SUBMITTED, version = 1), logs seq = 1 in claim_events, and returns 202 Accepted in 80 ms.
2. Adjudication & benefit cap lock (version = 2): Once malware scanning marks the PDF CLEAN, a worker fetches MBR_804's plan from the PAS (Policy Administration System—the external system of record for policies), saves a coverage_snapshot, evaluates the rule set active on the visit date (75% coverage = 9000 cents), locks MBR_804's 2026 manual-therapy row in benefit_accumulators (FOR UPDATE) to add 9000 cents without exceeding the annual cap, and atomically flips clm_09K to APPROVED (version = 2) while inserting claim.approved into outbox.
3. Crash-safe payout: The outbox relay publishes claim.approved to the Payment Service, which inserts one row in payments (payment_id = "pay_6", enforced unique by (claim_id, payee_type, payment_seq)) and calls the external payment processor passing Idempotency-Key: "pay_6". Even if that HTTP call times out and retries three times, "pay_6" guarantees 90.00 USD leaves the bank once.
4. Settlement (version = 3): When the processor confirms "pay_6", an event triggers apply_claim_action (WHERE status = 'APPROVED' AND version = 2), moving clm_09K to PAID (version = 3).
Key trade-offs
- Modular monolith on one PostgreSQL cluster vs. sharded microservices. Splitting intake, workflow, and adjudication into separate microservices gives teams separate deploy pipelines, but forces distributed sagas (multi-step compensating workflows) across data that only sees ~1–40 writes/s and totals ~90 GB over five years. Keeping claims, audit events, benefit counters, and the outbox in one PostgreSQL primary with a synchronous standby (a replica in a second zone that acknowledges every commit before returning so RPO = 0—zero acknowledged claims are ever lost) makes every state transition a simple local ACID transaction, splitting out only the Payment Service to isolate bank credentials and external processor retries.
- Accept fast (
202 Accepted) + async adjudication vs. synchronous adjudication. Adjudicating synchronously duringPOST /v1/claimsties member submission uptime and latency directly to external PAS calls and malware scans. Accepting durably in< 200 msand adjudicating on background workers absorbs post-holiday claim bursts and PAS outages cleanly, at the small UX trade-off of showing"Submitted — reviewing coverage"for a few seconds. - Transactional outbox + stored
payment_idvs. direct HTTP calls ("exactly-once effect"). Networks only provide at-least-once delivery (messages can be delivered more than once after timeouts), never true exactly-once transport. Combining an outbox table, consumer deduplication, aUNIQUE (claim_id, payee_type, payment_seq)constraint, a persistedpayment_ididempotency key, and daily settlement-file reconciliation achieves exactly-once financial effect, in exchange for operating a relay worker, anUNKNOWNpayment state, and a morning reconciliation job. - Immutable, effective-dated
rule_setsvs. editable live rules. Business admins often ask to edit coverage numbers in place, but mutating a rule makes historical claim audits irreproducible. RequiringDRAFT -> APPROVED -> ACTIVE (effective_from)rule versions withrule_set_versionstamped on every claim preserves complete auditability at the cost of a lightweight publishing workflow. - Owning
benefit_accumulatorslocally vs. querying PAS on every claim. While the PAS owns plan design (what the600 USDannual limit is), usage changes millisecond-by-millisecond as we approve claims. Locking and updatingused_centsinside our own PostgreSQL decision transaction prevents concurrent claims from overspending an annual cap without needing distributed two-phase commits across the PAS. - Synchronous, fail-closed
phi_access_logvs. async log shipping. Writing aphi_access_logrow before returning any claim or presigned download URL adds one tinyINSERTper read (~100/s peak), and in exchange guarantees under HIPAA (the US health-data privacy law) that zero PHI (Protected Health Information) is ever viewed without an immutable record.
Common mistakes
- Over-engineering for massive QPS (sharding NoSQL databases, complex event meshes): Ignores the back-of-the-envelope math (~1–4 writes/s) and sacrifices ACID transactions right where money and medical compliance depend on them.
- Updating
claims.statuswithout a transition table andversioncompare-and-set: Allows illegal jumps (likePAID -> DENIED) or lets two adjusters approve conflicting amounts simultaneously. - Writing audit trails outside the database transaction (or only to stdout logs): A crash between the DB commit and log flush leaves financial decisions with no compliance record, and stdout logs fail to separate mutation history (
claim_events) from PHI read-access tracking (phi_access_log). - Dual-writing DB state and payment calls (or holding DB locks during processor HTTP calls): Either strands approved claims unpaid, double-pays on retry, or exhausts DB connections when the bank API slows down.
- Generating a fresh
Idempotency-Keyon each payment retry: Defeats processor deduplication and pays the provider twice whenever the first HTTP response times out in flight. - Storing money as
FLOAT/DOUBLE: Binary floating-point arithmetic (0.1 + 0.2 != 0.3) causes penny discrepancies between line items and claim totals; always store integerBIGINTcents. - Checking annual benefit caps via application
SELECTthenUPDATE: Lets two concurrent claims for the same member both read"60 USD remaining"and both approve60 USD. - Enforcing RBAC (
role == MEMBER) without object-level ownership: Allows any logged-in member who guesses anotherclaim_idto read a stranger's medical records (IDOR—Insecure Direct Object Reference). - Storing multi-megabyte PDFs in database
BYTEA/BLOBcolumns or leaking PHI in emails: Bloats database backups and RAM, while putting diagnosis codes in email subjects leaks PHI onto lock screens.
Follow-up questions
- Suppose a claim sits in Pending info until its response deadline expires without receiving the requested records. How does your workflow handle that timeout, and why is automatically rejecting the claim on a timer risky in health insurance? Durable rows in
timersfire PHI-free nudges on days 7 and 30, and on day 45 the scheduler invokes our standardapply_claim_actionstate machine withescalate_sla(PENDING_INFO -> UNDER_REVIEW, setting anoverdue_infoflag and bumping queue priority). Because the timer uses the exact sameversioncompare-and-set as member uploads, a document arriving one second before the timer makes the timer a harmless0-row no-op, while a document arriving one second after matches our("UNDER_REVIEW", "info_received") -> "UNDER_REVIEW"rule so late medical records are never rejected or lost! Auto-denying by clock is a dangerous default in health insurance because an automated denial is a formal adverse benefit determination triggering legal notice and appeal rights (and regulated minimum windows such as ERISA's 45-day claimant response rule), missing records are frequently stuck at a busy clinic's fax room rather than member neglect, and routing to an adjuster lets them pay clean lines immediately while denying only undocumented lines with proper appeal instructions. - If an outbound payout call to the external payment gateway times out before returning a response, how do you ensure retries pay the clinic or member once and never twice? Before making the very first HTTP call, the Payment Service commits a single row in
paymentsprotected byUNIQUE (claim_id, payee_type, payment_seq)whose primary keypayment_idis permanently saved as the processorIdempotency-Key. When the HTTP request times out, the worker markspayments.status = 'UNKNOWN'and schedules exponential-backoff retries that send the exact samepayment_id—so if the processor processed the first request, it recognizespayment_idand returns the original receipt without moving money a second time. IfUNKNOWNpersists near the processor's idempotency retention window (typically 24 hours), the worker stops blind POST retries and resolves the row strictly viaGETlookup by reference or the next morning's settlement file reconciliation before transitioning the claim toPAID. - When an operations admin lowers an annual coverage limit, how do you prevent previously settled claims from changing retroactively, and how should rule versions be stored for future audits? Settled claims are legal financial determinations governed by the coverage terms active on the member's date of service, so lowering a limit must never silently re-adjudicate historical claims. In our schema,
rule_setsrows are immutable: an admin creates a new(rule_set_id, version)inDRAFT, a second admin approves it (APPROVED, logged with actor IDs and JSON diff), and publishing marks itACTIVEforservice_date >= effective_from, while every adjudicated claim permanently recordsrule_set_versionandcoverage_snapshot_id. If a genuine regulatory error or bug requires retroactive repricing, operations runs an explicit, two-person-approved adjustment campaign that previews affected claims byrule_set_versionand appends new adjustmentclaim_eventsplus incrementalpayment_seq = 2payouts or recoveries rather than overwriting original decisions. - As historical volume reaches millions of claims, multi-filter adjuster queries (for instance, open review claims for a specific member above a dollar threshold ordered oldest-first) start lagging. How would you offload those searches while keeping results aligned with the primary database? For member-scoped filters like that query, even at 10 million total claims a single member has
< 100claims—so routing adjuster searches to a PostgreSQL read replica with a composite index on(member_id, status, received_at)(or(status, total_claimed_cents, received_at)for cross-member queues) answers in< 10 mswithout touching the primary or adding infrastructure. Once adjusters need unselective multi-field filtering or fuzzy text search across provider names and notes, we stream committedoutbox/ CDC events into an encrypted OpenSearch index where every document write passesclaims.versionas anexternalversion guard—guaranteeing out-of-order or replayed messages can never overwrite newer state with older state, backed by a nightly(claim_id, version)drift reconciler. Because clicking a search result loads the authoritative row from PostgreSQL and every action enforcesWHERE version = :expected_version, a 1-second lag in search can never cause an invalid adjudication, and every search query still writes tophi_access_log.
Follow-up questions
- Suppose a claim sits in Pending info until its response deadline expires without receiving the requested records. How does your workflow handle that timeout, and why is automatically rejecting the claim on a timer risky in health insurance?
- If an outbound payout call to the external payment gateway times out before returning a response, how do you ensure retries pay the clinic or member once and never twice?
- When an operations admin lowers an annual coverage limit, how do you prevent previously settled claims from changing retroactively, and how should rule versions be stored for future audits?
- As historical volume reaches millions of claims, multi-filter adjuster queries (for instance, open review claims for a specific member above a dollar threshold ordered oldest-first) start lagging. How would you offload those searches while keeping results aligned with the primary database?
Similar questions
- Global Live Video Streaming Platform
- Multi-User Collaborative Document Editor
- Burst-Resilient Multi-Channel Notification Platform
- Prior Authorization Status Engine, Clinical Worklists, and Digests
- Diagnosing and Optimizing Full-Stack Web Request Latency
- Multi-Source Enterprise Question Answering System