Skip to main content

01 - Insurance Domain for Developers: Policies, Claims, Rating

Products, actors and data of insurance for people who write software: a versioned policy, the claim, rating with dated tables and verified regulations.

What do you think about this article?

At a Glance

Products, actors and data of insurance for people who write software: a versioned policy, the claim, rating with dated tables and verified regulations.

The insurance domain for developers: products, actors and data model

You have been assigned a ticket on an insurance system and the description mentions endorsement, FNOL, bordereaux. Before any code, you need the map: what a company sells, who takes part in the contract, which data change over time and which do not. The short answer is that an insurer sells a promise to pay, conditional on an uncertain event, and that almost all the complexity of the software comes from this: the contract lives for years, it is changed halfway through, and every amount must be reconstructible exactly as it was on the day it was decided.

This article opens the series. It gives you the vocabulary, a data model that withstands changes over time, two state machines (policy and claim), a rating engine with dated tables and an honest reading of the regulations that touch the software. The listings were run; the figures in the calculations come from synthetic data and serve to understand the mechanism, not to price a real risk.

Why it works: the mutuality of risk

A single person cannot afford to cover a rare, large loss alone: if the yearly probability of a claim is 5% and it costs 2,000 euros on average, the expected loss is 100 euros a year, but in the wrong year you would pay 2,000 all at once. A large group shares the cost: each member pays a premium close to the expected loss and the common fund compensates the few who are hit. The advantage for the insurer is statistical, and you can see it by simulating it.

The listing simulates a portfolio with those parameters (a claim with probability 0.05, a cost with a Gamma distribution of mean 2,000 euros, all synthetic, fixed seed) for 2,000 years and for five different sizes. The std dev column measures how much the loss per policy would swing from one year to the next; the q99.5 column is the 99.5% quantile of the loss per policy, that is, the bad year that happens once in two hundred. The q99.5/mean ratio tells you how much capital is needed on top of the expected loss.

Pooling simulation: dispersion falls as the portfolio grows
import numpy as np

SEED = 642
P_CLAIM = 0.05           # probability of a claim in one year (synthetic data)
MEAN_COST = 2000.0       # average cost of a claim in euro (synthetic data)
SHAPE = 2.0              # Gamma shape: severity has a long tail
YEARS = 2000             # simulated years for each portfolio size

rng = np.random.default_rng(SEED)
expected = P_CLAIM * MEAN_COST
print(f"expected loss per policy: {expected:.2f} EUR")
print(f"{'policies':>8} {'mean':>9} {'std dev':>9} {'q99.5':>9} {'q99.5/mean':>12}")

for n in (10, 100, 1_000, 10_000, 100_000):
    totals = np.empty(YEARS)
    for y in range(YEARS):
        n_claims = rng.binomial(n, P_CLAIM)
        totals[y] = rng.gamma(SHAPE, MEAN_COST / SHAPE, n_claims).sum()
    per_policy = totals / n
    q = np.quantile(per_policy, 0.995)
    print(f"{n:>8} {per_policy.mean():>9.2f} {per_policy.std():>9.2f} {q:>9.2f} {q / per_policy.mean():>12.2f}")

# Output:
# expected loss per policy: 100.00 EUR
# policies      mean   std dev     q99.5   q99.5/mean
#       10    100.35    170.30    822.67         8.20
#      100     98.69     54.88    270.60         2.74
#     1000     99.44     17.03    149.40         1.50
#    10000    100.16      5.35    113.74         1.14
#   100000    100.06      1.72    104.68         1.05

With 10 policies the bad year costs 8.2 times the expected loss; with 100,000 only 1.05 times. The mean does not change, the uncertainty does: it falls roughly with the square root of the size (from 170 to 5.35 euros going from 10 to 10,000 policies, a factor of 31.8 against the 31.6 that the square root of 1,000 would give). This is why the portfolio, not the single policy, is the object of the actuarial calculation. The limit of the model: it assumes independent claims. A hailstorm or a flood hits many policies together, and then the dispersion does not fall that way; this is why reinsurance and catastrophe models exist.

I did not choose the 99.5% quantile at random: it is the confidence level with which the Solvency II directive defines the solvency capital requirement, as you will see in the section on regulations.

Four product families, four data models

There is no universal insurance data model, because product families differ greatly in duration, risk and data. The table is an orientation map, not a classification set by law: the official classifications by class of business are different and finer.

FamilyExamplesTypical durationWhat weighs on the data model
LifeTerm life, endowment, pensionMulti-year, even decadesMortality tables, mathematical reserves, beneficiaries
Non-life (P&C)Motor liability, home, third-party liabilityOften annual, renewableClaim frequency and cost, deductibles, limits
HealthMedical expense reimbursement, accidentAnnual or multi-yearMedical coding, provider networks, waiting periods
Special risksTransport, cyber, directors' liabilityVariableUnique or accumulation risks, terms negotiated case by case

The practical consequence is an architecture choice that sooner or later falls to you: a single model that tries to contain everything, with optional fields everywhere, or models per line of business with a common core (parties, amounts, documents). The single model is quicker at the start and you pay for it when the Life branch asks for fields that the Non-life branch does not know; separate models cost duplication but leave each branch its own language. Here we build the common core and take motor liability as the example.

The actors and the policyholder, insured, beneficiary trio

The domain features the policyholder who signs and pays, the insured whose person or property is covered, the insurer who takes on the risk, the agent who represents the insurer, the broker who represents the customer, the reinsurer who insures the insurer, the loss adjuster who estimates the damage and the regulator. Each becomes an entity, and often a separate context, in your system.

ActorRepresentsTypical entities
AgentThe insurerAgency, mandate, commission
BrokerThe customerEngagement, placement, negotiated terms
ReinsurerTakes on part of the insurer's riskTreaty, cession, recovery
Loss adjusterEstimates the damageSurvey, estimate, report

The point that most often breaks naive models is that policyholder, insured and beneficiary are three roles, not three people. In an individual motor policy they coincide. In a company life policy the policyholder is the company, the insured are the employees and the beneficiaries are the family members each one has designated. Modeling a single customer_id field on the policy means being unable to represent this case: you need many-to-many relations between policy and parties, each with its own role.

The value chain, seen from the code

From first contact to the claim, the flow crosses five areas: distribution (channels, quotes), underwriting, policy administration, claims handling, investments and reserves. Each area has its own language and usually corresponds to a domain context. The area where a developer meets the most rules is underwriting, which breaks down like this:

  1. Assessment: the characteristics of the risk are read (age, asset to be covered, claims history)
  2. Rating: a rating engine turns those characteristics into a premium
  3. Selection: the risk is accepted, declined or accepted with different terms (exclusions, deductible, surcharge)
  4. Referral: cases outside the automatic parameters go to a human underwriter

The order here is not decorative: selection depends on the calculated premium, and referral exists because the first three steps do not cover every case. If you automate, the most delicate piece is precisely the referral: a system that decides alone even when it should not, or that does not explain why it referred a case, is what inspectors and customers challenge first. Real driving data, when available, comes from telematics, described in article 3 (Telematics pipeline). Article 4 of this series (AI underwriting: feature engineering and risk scoring) goes into the details.

The data model: an immutable, versioned policy

The policy is not modified, it is versioned: every contractual change (a second driver, a new limit, a change of address) produces a new version and leaves the previous one readable. The reason is practical before it is regulatory: a claim that happened in March must be settled with the terms in force in March, even if the policy was changed in June. With an in-place UPDATE that information is lost.

The listing models the policy with readonly types and a transition table: the key is the current state, the value is the map from action to target state. The apply and endorse functions do not touch the object they receive, they return a new one with version incremented and a row in history. Amounts are integers in cents, because with floating-point number values sums of amounts accumulate rounding errors (0.1 + 0.2 is not 0.3), and in a system that reconciles payments this is not tolerable. The run also prints two illegal transitions, which the table rejects.

TypeScript: immutable policy and state machine
type Status = 'QUOTE' | 'APPLICATION' | 'BOUND' | 'IN_FORCE' | 'SUSPENDED' | 'CANCELLED' | 'EXPIRED';
type Action = 'SUBMIT' | 'BIND' | 'ACTIVATE' | 'SUSPEND' | 'REINSTATE' | 'CANCEL' | 'EXPIRE' | 'DECLINE';

// Amounts in whole cents: 0.1 + 0.2 is not 0.3 in floating point.
interface Money { readonly cents: number; readonly currency: 'EUR' }

interface Policy {
  readonly number: string;
  readonly version: number;
  readonly status: Status;
  readonly premium: Money;
  readonly history: readonly string[];
}

// A single table: current state -> action -> target state.
const TRANSITIONS: Record<Status, Partial<Record<Action, Status>>> = {
  QUOTE:       { SUBMIT: 'APPLICATION', DECLINE: 'CANCELLED' },
  APPLICATION: { BIND: 'BOUND', DECLINE: 'CANCELLED' },
  BOUND:       { ACTIVATE: 'IN_FORCE', CANCEL: 'CANCELLED' },
  IN_FORCE:    { SUSPEND: 'SUSPENDED', CANCEL: 'CANCELLED', EXPIRE: 'EXPIRED' },
  SUSPENDED:   { REINSTATE: 'IN_FORCE', CANCEL: 'CANCELLED' },
  CANCELLED:   {},
  EXPIRED:     {},
};

function apply(policy: Policy, action: Action): Policy {
  const next = TRANSITIONS[policy.status][action];
  if (next === undefined) {
    throw new Error(`${action} not allowed from ${policy.status}`);
  }
  return {
    ...policy,
    status: next,
    version: policy.version + 1,
    history: [...policy.history, `${policy.status} -(${action})-> ${next}`],
  };
}

function endorse(policy: Policy, deltaCents: number, why: string): Policy {
  if (policy.status !== 'IN_FORCE') throw new Error(`endorsement on a ${policy.status} policy`);
  return {
    ...policy,
    version: policy.version + 1,
    premium: { ...policy.premium, cents: policy.premium.cents + deltaCents },
    history: [...policy.history, `ENDORSE ${why} (${deltaCents} cents)`],
  };
}

let p: Policy = { number: 'DEMO-0001', version: 1, status: 'QUOTE',
  premium: { cents: 48000, currency: 'EUR' }, history: [] };
for (const a of ['SUBMIT', 'BIND', 'ACTIVATE'] as Action[]) p = apply(p, a);
const v4 = p;
p = endorse(p, 3500, 'second driver');
console.log(`v${v4.version} premium ${v4.premium.cents} -> v${p.version} premium ${p.premium.cents}`);
console.log(p.history.join('\n'));
try { apply(v4, 'REINSTATE'); } catch (e) { console.log('expected error:', (e as Error).message); }
try { apply(apply(v4, 'CANCEL'), 'ACTIVATE'); } catch (e) { console.log('expected error:', (e as Error).message); }

// Output:
// v4 premium 48000 -> v5 premium 51500
// QUOTE -(SUBMIT)-> APPLICATION
// APPLICATION -(BIND)-> BOUND
// BOUND -(ACTIVATE)-> IN_FORCE
// ENDORSE second driver (3500 cents)
// expected error: REINSTATE not allowed from IN_FORCE
// expected error: ACTIVATE not allowed from CANCELLED

Compiled with tsc --strict with no errors and run with Node 24. The value of the table is that the list of allowed transitions lives in one place: to know whether you can go from SUSPENDED back to in force you do not read ten if statements, you read one row. Where it is easy to go wrong: a partial table. If you forget a state, the function answers "transition not allowed" for a perfectly legitimate policy, and you find out in production. The Record<Status, ...> type forces the compiler to ask you for every state. Document issuance phases and renewals are not included: in the next article (Cloud-native policy management) the lifecycle becomes an event store with concurrency control.

The claim and its invariants

The claim has a lifecycle of its own: notification (FNOL, first notice of loss), registration, assessment, decision, settlement, and possible recovery from a liable third party (subrogation). Three amounts accompany it: the reserve, that is, the estimate of what is still to be paid, the amount paid and the limit of the cover that was hit. A well-built aggregate does not let these numbers become inconsistent, and guarantees this with rules that the code enforces. The most important are these:

  • the date of the loss must fall within the policy's coverage period
  • the reserve cannot be negative
  • the amount paid cannot exceed the limit
  • a closed claim receives no payments, it must be reopened
  • at least one assessment must be on record before a decision

These are invariants, not interface validations: they hold whoever the caller is (an API, a batch, a data-fix script) and for this reason they live inside the aggregate. Other rules depend on the company: the authority threshold to approve a payment, for example, changes from one insurer to another and does not appear in the code below, which implements only the five listed.

TypeScript: the claim's invariants enforced by the aggregate
interface Claim {
  readonly id: string;
  readonly status: 'OPEN' | 'ASSESSED' | 'SETTLED' | 'CLOSED';
  readonly limitCents: number;      // limit of the cover that was hit
  readonly reserveCents: number;    // estimate of the cost still to be paid
  readonly paidCents: number;
  readonly assessments: number;     // assessments on record
}

function openClaim(lossDate: string, from: string, to: string, limitCents: number): Claim {
  // ISO 8601: comparing strings gives the same result as comparing dates
  if (lossDate < from || lossDate > to) {
    throw new Error(`loss of ${lossDate} outside period ${from}..${to}`);
  }
  return { id: 'C-1', status: 'OPEN', limitCents, reserveCents: 0, paidCents: 0, assessments: 0 };
}

function setReserve(c: Claim, cents: number): Claim {
  if (cents < 0) throw new Error('the reserve cannot be negative');
  return { ...c, reserveCents: cents };
}

function assess(c: Claim): Claim {
  return { ...c, status: 'ASSESSED', assessments: c.assessments + 1 };
}

function pay(c: Claim, cents: number): Claim {
  if (c.status === 'CLOSED') throw new Error('claim closed: reopen it before paying');
  if (c.assessments === 0) throw new Error('no assessment on record');
  if (c.paidCents + cents > c.limitCents) {
    throw new Error(`paid ${c.paidCents + cents} above the limit ${c.limitCents}`);
  }
  return { ...c, status: 'SETTLED', paidCents: c.paidCents + cents,
           reserveCents: Math.max(0, c.reserveCents - cents) };
}

const attempt = (label: string, f: () => Claim): Claim | undefined => {
  try { const r = f(); console.log(`ok       ${label}`); return r; }
  catch (e) { console.log(`rejected ${label}: ${(e as Error).message}`); return undefined; }
};

attempt('opening outside the period', () => openClaim('2027-03-01', '2026-01-01', '2026-12-31', 500000));
const c0 = openClaim('2026-06-10', '2026-01-01', '2026-12-31', 500000);
const c1 = setReserve(c0, 300000);
attempt('payment without assessment', () => pay(c1, 100000));
const c2 = assess(c1);
const c3 = attempt('payment of 2000 EUR', () => pay(c2, 200000))!;
attempt('payment above the limit', () => pay(c3, 400000));
console.log(`remaining reserve ${c3.reserveCents} cents, paid ${c3.paidCents} cents`);

// Output:
// rejected opening outside the period: loss of 2027-03-01 outside period 2026-01-01..2026-12-31
// rejected payment without assessment: no assessment on record
// ok       payment of 2000 EUR
// rejected payment above the limit: paid 600000 above the limit 500000
// remaining reserve 100000 cents, paid 200000 cents

The first two lines of the output are rejections for period and for lack of an assessment; then a payment of 2,000 euros goes through and lowers the reserve from 3,000 to 1,000; the last attempt exceeds the limit (600,000 cents against 500,000) and is rejected. The pay function returns a new Claim instead of modifying it: if validation fails halfway, there is no partially updated state to clean up. The code is compiled with tsc --strict and run with Node 24; the date checks compare ISO 8601 strings, which for this format coincides with chronological order.

The rating engine: tables have a date

The rating engine turns risk data into a premium. The idea is the same as in actuarial work: a base amount for the area, multiplied by factors (age band, merit class, vehicle use), then loaded for expenses, commissions, margin and taxes. The costliest error in this component is not mathematical: it is applying the wrong table. A policy that starts on 31 December is calculated with the table in force that day, not with today's, and the calculation must be repeatable identically years later, for a dispute.

The listing uses Decimal (never float for money) and finds the table with a binary search on the effective date. The tables and rates are invented for the example, and I say so because you must not read them as real rates: the pattern is what matters. Every answer carries an audit that says which version it used and which product it calculated; the last call shows that a date before the first table gives an error instead of an invented price.

Python: rating with dated tables and an audit trail
from bisect import bisect_right
from datetime import date
from decimal import Decimal as D, ROUND_HALF_UP

# SYNTHETIC tables: they are not any insurer's rates.
# Each version applies from the effective date shown.
RATE_TABLES = [
    (date(2025, 1, 1), "T-2025", {"base": D("300.00"), "young": D("1.40"), "mid": D("1.00"), "senior": D("1.10")}),
    (date(2026, 1, 1), "T-2026", {"base": D("318.00"), "young": D("1.35"), "mid": D("1.00"), "senior": D("1.12")}),
]
LOADINGS = {"expenses": D("0.15"), "commissions": D("0.12"), "margin": D("0.05")}
TAX_RATE = D("0.20")   # fictitious rate, for the example only

def table_for(effective: date):
    starts = [t[0] for t in RATE_TABLES]
    i = bisect_right(starts, effective) - 1
    if i < 0:
        raise ValueError(f"no table in force on {effective}")
    return RATE_TABLES[i]

def band(age: int) -> str:
    return "young" if age < 26 else ("mid" if age < 65 else "senior")

def quote(age: int, effective: date) -> dict:
    _, version, t = table_for(effective)
    audit = [f"table {version} (policy effective date {effective})"]
    technical = t["base"] * t[band(age)]
    audit.append(f"technical = {t['base']} x {t[band(age)]} = {technical}")
    gross = technical * (1 + sum(LOADINGS.values()))
    total = gross * (1 + TAX_RATE)
    cents = D("0.01")
    return {"version": version, "technical": technical.quantize(cents, ROUND_HALF_UP),
            "gross": gross.quantize(cents, ROUND_HALF_UP),
            "total": total.quantize(cents, ROUND_HALF_UP), "audit": audit}

for label, age, eff in [("age 22, effective 2025-12-31", 22, date(2025, 12, 31)),
                        ("age 22, effective 2026-01-01", 22, date(2026, 1, 1)),
                        ("age 40, effective 2026-03-15", 40, date(2026, 3, 15))]:
    r = quote(age, eff)
    print(f"{label}: {r['version']} technical {r['technical']} gross {r['gross']} total {r['total']}")
    print("   ", "; ".join(r["audit"]))
try:
    quote(30, date(2024, 6, 1))
except ValueError as e:
    print("expected error:", e)

# Output:
# age 22, effective 2025-12-31: T-2025 technical 420.00 gross 554.40 total 665.28
#     table T-2025 (policy effective date 2025-12-31); technical = 300.00 x 1.40 = 420.0000
# age 22, effective 2026-01-01: T-2026 technical 429.30 gross 566.68 total 680.01
#     table T-2026 (policy effective date 2026-01-01); technical = 318.00 x 1.35 = 429.3000
# age 40, effective 2026-03-15: T-2026 technical 318.00 gross 419.76 total 503.71
#     table T-2026 (policy effective date 2026-03-15); technical = 318.00 x 1.00 = 318.0000
# expected error: no table in force on 2024-06-01

Look at the first two lines: the same 22-year-old insured, a single day of difference in the effective date, a total that goes from 665.28 to 680.01 euros because the table changes. Rounding to the cent happens only at the end, with ROUND_HALF_UP, because rounding at every step would accumulate discrepancies. In production the tables live in an archive together with their validity, not in a list in the code, and the factors are in general estimated with statistical models (article 4 shows how); discount and exclusion rules often live in a separate rules engine, so that whoever manages the product can change them without a software release.

Contexts, aggregates and events

Domain-Driven Design is the most widely used framework for this domain, because the word "policy" means different things to whoever assesses the risk (a proposal to be judged) and to whoever administers the contracts (an issued contract). A bounded context draws the boundary within which a word has a single meaning, and the relations between contexts decide who adapts to whom. A reasonable map for a non-life company is the following:

  • Distribution to underwriting: distribution adapts to the underwriting model (conformist)
  • Underwriting to policy administration: a published, stable language that administration consumes
  • Administration to claims: customer and supplier, with the contract that the second respects
  • Claims to anti-fraud: an anti-corruption layer that translates between two different models

It is a proposal, not a truth: two different companies draw the boundaries in different places, and the criterion for choosing them is who changes, and how often. The value of naming the relation is that it makes explicit a decision that would otherwise stay implicit in the code: if two contexts share a table, someone has already decided that they form a shared kernel, and it is worth knowing. Between contexts, communication typically goes through domain events (policy issued, claim notified, claim settled): whoever emits does not know who listens, and billing, reinsurance and anti-fraud each react on their own.

What the regulations say, with the article

Insurance software is conditioned by European regulations. Below you will find only what I verified on the official text in its Italian version (articles and recitals are numbered identically in every language version, and the links point to the English one); for every compliance choice in your case you need legal advice, not this page.

RegulationWhat it establishes (verified)Effect on the software
Directive 2009/138/EC (Solvency II), arts. 100-101Undertakings hold eligible own funds to cover the solvency capital requirement, calibrated as the value-at-risk of basic own funds with a 99.5% confidence level over one yearData and risk models from which the requirement is derived, with traceability of the calculation
Directive (EU) 2016/97 (IDD), art. 20Before the contract the distributor specifies the customer's demands and needs, and the proposed contract must be consistent with them; with advice, it provides a personalised, reasoned recommendationRecord the needs that emerged, the reasons for the recommendation and the information given
Regulation (EU) 2016/679 (GDPR), art. 17The right to erasure does not apply to the extent that processing is necessary for compliance with a legal obligation or for the establishment, exercise or defence of legal claims (art. 17, para. 3, points b and e)Erasure is not always due: identifying data must be separated from data that an obligation requires you to keep
Regulation (EU) 2022/2554 (DORA), art. 64Applies from 17 January 2025Management of ICT risk and of technology providers by that date
IFRS 17 (Regulation (EU) 2021/2036)Published by the IASB on 18 May 2017 and amended on 25 June 2020; adopted in the Union by Regulation 2021/2036Contract data that can be grouped for accounting: discussed in article 8

Read the GDPR row carefully, because it is the one where teams most often go wrong: "right to be forgotten" and "retention obligation" seem to conflict, but article 17 itself provides the exception for legal obligations. How long which data must be kept is set by national and sector rules, and I have not verified it here: ask your legal officer before writing the deletion job. In design terms, the usual choice is to split identifying data from transactional data, so that you can delete the former when the obligation ends without losing the latter.

Exchange standards: ACORD

Insurers and their intermediaries exchange data using shared formats. ACORD is the organisation that publishes them: on its site it lists XML and AL3 standards for Property & Casualty, XML for Life and annuities, XML and JSON for reinsurance and large commercial risks, and a family called "Next-Generation Digital Standards" designed for APIs and microservices. Access to the documents is reserved to members, so I have not read the schemas and I do not describe their fields; how to use an exchange standard in an API we see in the article ACORD standards and API integration.

What you can do now

You can tell the product families apart and choose whether your data model will be single or per line; you know that policyholder, insured and beneficiary are many-to-many roles; you can write a policy that is versioned instead of overwritten, with a transition table that reads in one row; you can enforce a claim's invariants inside the aggregate; you know why the rate table has a date and how a calculation is traced; and you know which regulations to cite, with the article, and where you need a lawyer. The next step is the system that holds it all together, described in article 2 of the series. For the consequences of the supervisory rules, article 8 (Compliance engineering: Solvency II and IFRS 17) takes up the same references in more detail.

Frequently asked questions

What is the difference between policyholder, insured and beneficiary?

The policyholder takes out and pays for the policy, the insured is the person or thing covered, the beneficiary receives the benefit. They can coincide, as in an individual motor policy, or be three different parties, as in a company life policy. This is why the data model needs relations with a role, not a single customer field.

Why is a policy versioned instead of updated?

Because a claim is settled with the terms in force on the date of the loss, not with today's. If you update in place, you lose those terms. With a new version for every change you can reconstruct the state at any date and explain an amount years later.

Why not use floating-point decimal numbers for premiums?

Because values such as 0.1 have no exact binary representation and sums accumulate discrepancies. You use integers in cents, as in the TypeScript listing, or decimal types such as Decimal in Python, rounding only at the last step.

Sources

The listings were run: pooling.py and rating.py with Python 3 (NumPy 2.3.5), policy.ts and claim.ts with Node 24.11 and compiled with tsc --strict. The data are synthetic; no market figure is reported. The regulations were checked on the Italian text on EUR-Lex.

Try These Tools

Free developer tools related to this topic.

Commenti

Caricamento commenti...

Sign in to comment

New articles and tools on Telegram too

The Telegram channel flags the site's new articles and tools.

Did you like this article?

Explore other content on the blog or discover my projects