← Back
Home › Systems › Finance and trading

insurance-claims

Prices and accepts insurance risks through underwriting, handles reported losses through claims, and estimates future payouts through reserving, for insurers.

Lemonade

Open the insurance-claims pageinsurance-claims Durable workflow executiondistributed: Ordinary code made crash-proof by logging every side-effect result and replaying the code from that log; activities run at least once, workflow logic must be deterministic.›Chain ladder reservingfinance: Loss development triangles and chain-ladder / Bornhuetter-Ferguson reserve estimationDouble-entry ledgerfinance: Append-only journal of transactions whose postings sum to zero per currency; balances are derived, so money can only move, never appear or vanish.›Money representationfinance: Store money as integer minor units with an explicit currency exponent, compute in wider integers, and round once with a named rounding mode.›Payment state machinefinance: Persisted state machine for a payment lifecycle (authorize, capture, void, refund) that treats timeouts as unknown, retries with the same key and applies webhooks idempotently.›Graph community detectiongraphs: Louvain/label propagation community detection for rings, fraud clusters and campaignsCalibrationmachine-learning: Make predicted probabilities match observed frequencies: measure with ECE, fix post hoc with temperature, Platt or isotonic scaling on held-out data.›Generalized linear models(GLMs)machine-learning: Linear model for counts, rates, positive amounts and proportions: a linear score pushed through a link, fitted by iteratively reweighted least squares.›Gradient-boosted decision trees(GBDT)machine-learning: Add small regression trees one at a time, each fitted to the loss gradient; histogram splits over 256 bins make it the strongest tabular default.›Isolation forestmachine-learning: Score each record by how few random axis-aligned splits it takes to isolate it in a small forest of random trees; anomalies are few and different, so they isolate fast.›Optical character recognition(text recognition)machine-learning: Find text lines in an image, read each crop with a CTC or attention model, then correct with a lexicon and score confidence for review routing.›Convolutional networksml-training: Layers that slide a small shared kernel over a grid, giving translation equivariance and few parameters; still the most compute-efficient choice for many vision tasks.›Monte Carlo integrationnumerics: Estimate an expectation by averaging random samples; error falls as σ/√N in any dimension, and variance reduction (antithetic, control variates, importance sampling) shrinks σ.›Tamper-evident audit logsecurity: An append-only log whose Merkle root, signed per batch, lets anyone verify an entry is present and history was never rewritten, with log-size proofs.›Bitemporal datastorage: Valid time plus transaction time on every record for as-of queries, back-dating and correctionsEntity resolutionstorage: Decide which records describe the same real-world thing: block to cut the pair space, score pairs with a probabilistic model, cluster the matches transitively.›Rete rules enginesystems: Match many rules against changing facts by caching partial matches in a shared network, so each change only does the work it actually affects.›Durable job queuedistributed: Persisted tasks that workers lease for a visibility timeout, ack on success and retry with backoff; at-least-once execution that survives worker and queue crashes.›Record replaydistributed: Record every nondeterministic input (time, randomness, I/O, model and tool outputs, per-tick player input) and re-execute deterministically for debugging, replays and state rebuildHierarchical timing wheelsystems: Timers bucketed by expiry into wheels of slots, coarser wheels for far deadlines: O(1) insert and cancel for millions of timeouts.›Bootstrap confidence intervalsstatistics: Resampling-based confidence intervals for arbitrary statisticsEvent sourcingfinance: Persist state changes as an append-only stream of immutable events per entity; current state is a fold over them, guarded by expected-version appends.›Largest remainder roundingfinance: Splitting an amount into parts that sum exactly (largest remainder / Hamilton) for allocations, splits and prorationsIdempotency keysfinance: Client-chosen unique key per logical operation, stored with a request fingerprint and the final response, so retries replay the first result instead of acting twice.›Exponential backoff with jittersystems: Retry after delays that grow geometrically and are randomized, so failed clients spread out instead of hammering a recovering service in synchronized waves.›Hierarchical state machinesystems: Nest states so a substate inherits its parent's reactions and only overrides what differs, with ordered entry and exit actions along the path.›Sparse matrices (CSR)numerics: Compressed sparse row stores only nonzeros as row pointers, column indices and values; SpMV streams them once, so it is memory-bandwidth bound.›Linear and logistic regressionmachine-learning: Fit a weighted sum of features to a number (least squares) or a probability (logistic); the baseline every model must beat.›Loss functionsmachine-learning: The scalar a model minimizes: cross-entropy for classes and tokens, MSE or Huber for values, each with a stable form and simple gradient.›+ 23 moreDead-letter queuedistributed: A side queue for messages that keep failing: after N delivery attempts or a permanent error, park them with the reason so the main queue keeps moving.›Write-ahead logstorage: Append each change to a checksummed sequential log and fsync it before touching data pages; the basis of crash durability in nearly every database.›Slab allocatorsystems: Pre-carve pages into equal-size slots per size class with an in-place free list: O(1) alloc and free, no external fragmentation, cache-warm reuse.›Leasesdistributed: A lock that expires on its own: bounded-time ownership that survives crashes and partitions, given bounded clock drift and fencing tokens on writes.›Optimistic concurrency controlstorage: Run transactions without locks, record what they read, and validate at commit that nothing changed; fastest when conflicts are rare.›Cryptographic hashes (SHA-2,BLAKE3)security: Collision-resistant fingerprints of data; SHA-256 for interoperability, BLAKE3 for speed, HMAC/HKDF for keyed uses.›L-BFGSnumerics: Quasi-Newton minimizer that approximates the inverse Hessian from the last m gradient differences via the two-loop recursion; O(m·n) memory and work per step.›+ 9 moreCRC32C checksumshardware-os: The Castagnoli CRC-32 with dedicated instructions on x86 (SSE4.2) and ARMv8. It is the standard fast integrity check for storage blocks, logs and network frames.›fsync, O_DSYNC and O_DIRECThardware-os: What fsync, fdatasync, O_DSYNC, O_DIRECT and F_FULLFSYNC really guarantee on Linux and macOS, and the exact call sequences for crash-safe files.›Fencing tokensdistributed: A number that grows with every lock grant and is checked by the protected resource, so a paused ex-holder's late write is rejected.›+ 5 more+ 2 more

How it is built

Architecture overview

An insurer sells a promise: pay for a defined loss during a defined period. Two systems carry that promise. Underwriting decides whether to offer cover and at what price, before any loss exists. Claims decides what to pay when a loss is reported, and reserving estimates what the company will still have to pay on losses that have happened but are not yet settled or even reported. All three share one thin source of truth, the policy as it was in force on the date of loss, and one ledger, because every payment and every reserve change is money.

The idea that makes the system work is the split of the same data into three clocks. A quote is priced by a statistical model of expected loss. A claim is routed by cheap checks that decide how much human attention it needs, so most small, clear claims are paid fast and a few risky ones get investigated. A reserve is a forecast built from how past claims developed over time. Lemonade's public claims page describes the first-notice flow for its product: the customer files in the app, "dozens of anti-fraud algorithms" run, a claim that is instantly approved is paid automatically, and otherwise it is handed to a human team (source: Lemonade, Claims). That is a vendor's own description, but it shows the shape: automation for the clear cases, people for the rest.

Parts:

 quote request ─► underwriting rules ─► pricing model ─► premium ─► policy store (bitemporal) ◄──────────────┐
                  (Rete)                (GLM / GBDT,                    │                                     │
                                         calibrated)                    │ terms in force on loss date        │ endorsements
                                                                        ▼                                     │
 first notice ─► coverage check ─► triage ─┬─ auto-pay ─────────────────► payment state machine ─► ledger ────┤
 of loss         (rules on policy)   │     ├─ adjuster ◄── evidence (OCR, photos, hashes)                      │
                                     │     └─ SIU ◄──────── fraud score (outliers, links, rings)               │
                                     ▼                                                                        │
                      case workflow (durable, timers, tasks)                                                  │
                                                                                                              │
 ledger ─► paid + case reserves by accident / development period ─► chain ladder ─► IBNR, ultimate ─► Monte Carlo ─► capital view

How the parts fit together

Pricing models

An insurance price starts from a pure premium: expected loss per unit of exposure. It is usually modelled as claim frequency times severity. Generalized linear models (GLMs) are the long-standing tool: a Poisson model with a log link and the policy's exposure (policy-years) as an offset gives claim counts, and a gamma model with a log link gives the average cost of a claim; Tweedie models combine the two. The log link makes effects multiplicative, so a factor reads as "20 percent more likely", which a regulator and a pricing committee can approve line by line. Gradient-boosted decision trees (GBDT) accept the same Poisson and Tweedie losses and find interactions a hand-built GLM misses, at the price of weaker explanation; a common arrangement is a GLM as the filed rating model and a boosted model as challenger or as an input to it.

The contract with the rest is a function from risk facts to expected loss, plus a calibration check that predicted totals match observed totals by segment on recent data. In insurance this balance property matters as much as ranking: a model that ranks well but is a few percent low everywhere underprices the whole book. Some jurisdictions restrict which factors may be used for rating, so the factor list is a governance input, not only a modelling choice. For small segments with thin data, shrinkage toward the portfolio rate (see Bayesian rate estimation) stops a handful of claims from moving a price; the actuarial name for this is credibility (credibility-theory, no page yet).

Underwriting rules

Before the model, rules decide whether the risk is acceptable: property types not offered, locations outside the territory, prior-loss counts, missing information that forces a referral to a person. Rete rules engine fits because facts arrive in pieces during a quote, and each new answer should only re-evaluate the rules it touches. Rules return three outcomes (accept, refer, decline) with the rule ids that fired, so a referred quote shows an underwriter why. The model prices what the rules accept; rules never silently override a price.

Policy store

A claim is judged against the policy as it was on the date of loss, not as it is today. Customers add cover, change addresses and correct mistakes after the fact, so each fact has two dates: when it became true for the cover and when the insurer recorded it (bitemporal-data, no page yet). The first answers "was this item covered on 3 March?"; the second answers "what did we believe on the day we paid?", which an audit or a dispute needs. Coverage checks, premium refunds on backdated endorsements and reserve restatements all query this store with an as-of pair.

Claims workflow

A claim is a long-lived case: report, coverage check, triage, investigation, offer, payment, possible recovery from a third party, close, reopen. Durable workflow execution holds the case across the waiting (for the policyholder's photos, an adjuster's visit, a repairer's invoice) and gives timers for service levels. Activities such as calling the bank or sending a letter run at least once, so each has an idempotency key.

Triage is the key decision: auto-pay, send to an adjuster, or send to the special investigations unit (SIU). It combines the coverage check, the claim size, the fraud score and the evidence confidence. A cautious rule is that automation may only approve, never deny; any denial is made or confirmed by a person, because a wrongful denial is a harm and a regulatory exposure while a slower payment is not.

Payments follow a Payment state machine: approved, instructed, sent, confirmed, with the unknown state after a timeout treated as unknown rather than failed. Partial payments and supplements are normal in claims (a repair estimate is revised after the car is opened up), so a claim holds many payments, each with its own state.

Evidence processing

Documents such as repair estimates, invoices, medical bills and police reports are read by Optical character recognition (text recognition) with per-field confidence, and low-confidence values go to a person. Photos of damage are scored by Convolutional networks that classify damage type and locate the affected area; this supports an adjuster or a fast-path estimate, and is evidence with a confidence, not a verdict. Perceptual hashing gives each photo a fingerprint that survives resizing and re-compression, so the same photo submitted on two claims is found by a lookup. Contract with triage: each item delivers a value, a confidence and a pointer to the source.

Fraud detection

Three tools answer three different questions:

  • Is this claim unusual? Isolation forest scores each claim by how few random splits isolate it among comparable claims (amount, delay between policy start and loss, reporting delay, repairer, region). It needs no fraud labels, which are rare and biased toward what was caught. The score says "look", not "fraud".
  • Who is connected? Entity resolution decides that two records describe the same person, phone, address, vehicle or bank account across claims and policies, despite spelling differences. Transitive closure is the dangerous step: one false link merges two unrelated customers.
  • Is there a ring? The resolved entities form a graph (claims, people, accounts, repairers). Community detection such as the Louvain method (Blondel et al., 2008) finds densely connected groups, which an analyst then inspects (graph-community-detection, no page yet). A dense cluster of unrelated people sharing a repairer and a bank account is worth a look; it can also be a family or a popular legitimate repairer.

The output is a ranked work list for SIU investigators with the reasons visible, not an automatic denial. Review capacity decides the threshold: score only as many claims as the unit can read.

Reserving and capital

At any date the insurer owes money on claims it has not yet fully paid: known claims still open and claims incurred but not yet reported (IBNR). The chain-ladder method (chain-ladder-reserving, no page yet) takes a triangle of cumulative payments by accident period and development period, computes the average growth from each development period to the next, and applies those factors to the latest diagonal to project the ultimate cost. The unpaid part is the reserve. Mack (1993) gave a distribution-free estimate of its standard error, so the reserve comes with a range. The method assumes development patterns stay stable; a change in claims handling speed, in inflation or in the mix of business breaks the assumption, and actuaries adjust by judgement.

Where a distribution rather than a point is needed (capital for a bad year, a catastrophe such as a hailstorm hitting many policies at once, reinsurance pricing), Monte Carlo integration simulates many years: draw the number of claims, draw each claim's size, sum, and read the tail percentile. Error shrinks with the square root of the number of simulations, and a tail percentile needs far more samples than a mean, so variance reduction matters.

Ledger and audit

Double-entry ledger records premium received and earned, claim payments, reserve movements and recoveries as postings that sum to zero, in integer minor units (Money representation). Paid amounts are real cash; reserves are accounting estimates that move with each revision, and keeping both in the same ledger ties the claims system to the financial statements. A Tamper-evident audit log covers decisions: who approved, which model version scored the claim, what the triage reasons were.

Data and control flow

A claim reported through the app

  1. The policyholder files a first notice with a description and photos; the request carries an idempotency key; the workflow starts.
  2. The policy store is queried as of the loss date; coverage rules (Rete) check that the peril, item and period are covered and what excess applies.
  3. Evidence is processed: photos hashed against earlier claims, damage scored, documents read with confidence.
  4. The fraud layer scores the claim: isolation forest on the features, the entity graph for links to other claims.
  5. Triage: clear, small, high-confidence claims with no flags go to auto-pay; unclear ones go to an adjuster; flagged ones go to SIU.
  6. For auto-pay, a payment is created, goes through the state machine, and the ledger posts the payment and releases any case reserve.
  7. The workflow closes the claim with a reopen window; a late supplement reopens it and starts again from step 2.

Time goes to waiting for people and for the bank; the model scoring steps take milliseconds.

A quote

  1. Facts arrive from a form and third-party data; rules accept, refer or decline.
  2. The pricing model returns expected frequency and severity; loadings for expenses and margin are applied outside the model.
  3. The quote is stored with the model version and the facts used, so the price can be explained and replayed.

The quarterly reserve

  1. Build the triangle from ledger data: payments and case reserves by accident and development period, as known at each past date (this is why the bitemporal view matters).
  2. Compute development factors, project to ultimate, and read off the unpaid amount and its error.
  3. Simulate the distribution where capital needs it.
  4. Compare with the booked reserve; actuaries decide on adjustments; the movement is posted to the ledger.

Scaling

In the order you would pull the levers:

  1. Surge after an event. A storm or a flood brings a large share of a year's claims in days. Levers: auto-pay for clear cases, more adjusters by region, queue priorities by severity, and a workflow engine that scales to many open cases (partition by claim id).
  2. Adjuster and SIU time. This is the true capacity limit. Lever: raise the share handled correctly without a person (extraction confidence, photo scoring), and set the fraud threshold to what the unit can review.
  3. Photo and document processing. Image models are the heaviest compute. Levers: batch inference, resize on upload, run damage scoring only when it can change the decision.
  4. Entity graph. Resolution and community detection are recomputed on the whole book; run them incrementally per new claim and fully on a schedule. Blocking quality decides whether the pair space stays tractable.
  5. Simulation. Cost is policies times simulated years; variance reduction and parallel runs help before more hardware does.
  6. Pricing model refresh. Retraining is annual or semi-annual and cheap; the bottleneck is filing, validation and approval.

Failure modes

FailureSymptomCauseFix
Wrong policy versiona covered claim is denied, or the reversecoverage checked against today's policy instead of the loss datebitemporal policy store; always query by loss date and by knowledge date
Double paymentthe same claim paid twiceretried instruction without a key; supplement and original both paidpayment state machine, idempotency key per payment, ledger check on claim total
Reserve inadequacylater years show adverse developmentchain ladder applied to a book whose settlement speed or inflation changedcompare methods, use case reserves as well as paid, add judgement, monitor actual versus expected
Underpricingloss ratio drifts above planmodel out of calibration, new segments with little datacalibrate by segment, shrink small segments, monitor monthly
Fraud false positivehonest customer delayed or deniedoutlier score read as proofinvestigators decide; automation never denies; show reasons; track false positive rate
False ringunrelated customers grouped as a ringentity resolution merged records; a popular repairer links manytwo thresholds, review of merges, down-weight hub nodes
Photo model errorwrong damage estimatelighting, angle, unseen objectconfidence threshold, adjuster fallback, sample audits
Photo reuse missedthe same image pays twicehash too strict or images heavily editedperceptual hashes with a distance threshold, plus review
Catastrophe accumulationlosses concentrate in one placerisk selection ignored geographyaggregate exposure limits by location; simulate event losses
Backdated endorsementpremium or cover wrong after a late changesingle-date model of policybitemporal recompute, adjustment postings rather than edits

Real implementations

namewhat it isrepolicencenotes
Lemonade claimsan insurer's public description of an app-based claims flow with anti-fraud algorithms and instant approvalLemonade, Claimsproprietarydocumented by the vendor; the internals are not public
chainladder-pythonactuarial reserving in Python: triangles, link ratios, IBNR modelscasact/chainladder-pythonMPL-2.0maintained under the Casualty Actuarial Society organisation
ChainLadder (R)statistical methods and models for claims reserving in general insurancemages/ChainLadder, CRANGPL-2.0-or-laterthe CRAN description names reserving methods including those for the Solvency II claims development result
NetworkXgraph analysis library with a Louvain community-detection functionnetworkx/networkxBSD-3-Clausefraud rings on a resolved entity graph; louvain_communities
openIMIS claim modulethe claim reference module of an open health-insurance management systemopenimis/openimis-be-claim_pyAGPL-3.0health financing and social protection; openimis.org
DroolsJava rule engine (PHREAK algorithm)apache/incubator-kie-droolsApache-2.0underwriting and coverage rules
Temporaldurable execution enginetemporalio/temporalMITthe claim case as a workflow

The alternative: buy a policy and claims administration platform and configure rules and workflows in it, keeping only models and the reserving process in-house. This is the common route for established insurers; building the core pays when the product is new or the claims experience is the product.

Sources

  • Lemonade, Claims (app filing, anti-fraud algorithms, instant approval, hand-over to humans; the vendor's own description).
  • T. Mack, Distribution-free Calculation of the Standard Error of Chain Ladder Reserve Estimates, ASTIN Bulletin 23(2), 1993. DOI
  • V. Blondel, J.-L. Guillaume, R. Lambiotte, E. Lefebvre, Fast unfolding of communities in large networks, 2008 (the Louvain method). paper
  • F. T. Liu, K. M. Ting, Z.-H. Zhou, Isolation Forest, ICDM 2008. DOI
  • CRAN, ChainLadder package and chainladder-python repository descriptions.
  • openIMIS, project site.

Similar systems

Share the most building blocks with this one.