Cloud-native policy management: an API-first architecture
The policy administration system (Policy Administration System, PAS) knows what each customer has bought, since when, at what price and with which changes. In many insurers it still lives on systems designed to process batches overnight, and every integration is a file exchanged at fixed times. Moving it to a service architecture with APIs does not mean breaking a monolith into microservices: it means deciding three things that the nightly batch was hiding, namely how the history of a policy is kept, how two operators are kept from overwriting each other, and how a repeated request is kept from creating two contracts.
The answer of this article is a small, verifiable core: an append-only event log from which the state is rebuilt, optimistic concurrency control, a pro-rata calculation on actual days and an API with an idempotency key. Every listing was run; the premiums are invented data. It assumes the model from the previous article (The insurance domain for developers).
The lifecycle as a contract between services
Before the architecture you need the shared vocabulary: the states of the policy and who can move it from one to another. A policy starts as a quote, becomes an application, is bound (bound: the insurer has committed), comes into force and is then modified, suspended, cancelled or expires. The groups of states that services must know are five:
- Quote and application: the risk is under assessment, no cover is active
- Bound: the commitment is there, formal issuance may follow
- In force: cover is active and claims can be notified
- Suspended: cover is temporarily stopped, typically because of an uncollected premium
- Cancelled or expired: final state, from which there is no return without a new operation
The list serves a single purpose, which the transition table of article 1 makes executable: final states have no exits, and "suspended" is the only state from which you return to in force. If you enforce this in one service only, the others (billing, documents, notifications) can trust the events they receive without revalidating them. Where the rules diverge between products, for example on suspension times, the decision belongs to the product and not to the code: the table must be configurable per product.
State as a sum of events
An UPDATE on a policies row answers the question "what is the policy like now"
and destroys "what was it like in March". In the insurance domain the second question comes up often: a
claim, a dispute, an audit. Event sourcing
solves the problem at the root: instead of the state you keep the events (policy bound, premium changed,
policy cancelled) and the current state is their sum. The history is the data, the state is a view that can
be rebuilt.
The listing creates a log in SQLite (in memory, for the example only) with primary key
(policy_id, seq). The choice that holds up everything else is this: append writes
event number expected_version + 1, and if another writer has already written it the primary key
violates the constraint and the function raises ConcurrencyError. It is an optimistic check: no
lock taken on read, the conflict emerges only if it happens. The fold function is pure and
rebuilds the state; amounts are Decimal serialised as strings, because a float in
JSON brings back the binary errors that accounting does not tolerate.
import json
import sqlite3
from decimal import Decimal as D
class ConcurrencyError(Exception):
pass
class EventStore:
"""Append-only: each policy has events numbered 1, 2, 3... with no gaps."""
def __init__(self):
self.db = sqlite3.connect(":memory:")
self.db.execute("""CREATE TABLE policy_events (
policy_id TEXT NOT NULL, seq INTEGER NOT NULL,
type TEXT NOT NULL, data TEXT NOT NULL,
PRIMARY KEY (policy_id, seq))""")
def append(self, policy_id, expected_version, etype, data):
try:
with self.db:
self.db.execute(
"INSERT INTO policy_events VALUES (?, ?, ?, ?)",
(policy_id, expected_version + 1, etype, json.dumps(data)))
except sqlite3.IntegrityError:
raise ConcurrencyError(
f"{policy_id}: version {expected_version} is no longer the latest")
return expected_version + 1
def history(self, policy_id):
rows = self.db.execute(
"SELECT seq, type, data FROM policy_events WHERE policy_id = ? ORDER BY seq",
(policy_id,))
return [(s, t, json.loads(d)) for s, t, d in rows]
def fold(events):
"""The current state is a pure function of the history."""
state = {"status": None, "premium": D("0"), "version": 0}
for seq, etype, data in events:
state = {**state, "version": seq}
if etype == "Bound":
state = {**state, "status": "IN_FORCE", "premium": D(data["premium"])}
elif etype == "Endorsed":
state = {**state, "premium": state["premium"] + D(data["delta"])}
elif etype == "Cancelled":
state = {**state, "status": "CANCELLED"}
else:
raise ValueError(f"unknown event: {etype}")
return state
store = EventStore()
pid = "POL-1"
v = store.append(pid, 0, "Bound", {"premium": "480.00"})
v = store.append(pid, v, "Endorsed", {"delta": "35.00", "why": "second driver"})
print("state after 2 events:", fold(store.history(pid)))
# Two operators read version 2 and try to write together.
try:
store.append(pid, 2, "Endorsed", {"delta": "-10.00", "why": "discount"})
store.append(pid, 2, "Endorsed", {"delta": "20.00", "why": "extension"})
except ConcurrencyError as e:
print("second writer rejected:", e)
print("final history:", [(s, t) for s, t, _ in store.history(pid)])
print("final premium:", fold(store.history(pid))["premium"])
# Output:
# state after 2 events: {'status': 'IN_FORCE', 'premium': Decimal('515.00'), 'version': 2}
# second writer rejected: POL-1: version 2 is no longer the latest
# final history: [(1, 'Bound'), (2, 'Endorsed'), (3, 'Endorsed')]
# final premium: 505.00
The output shows the case that matters. Two operators both read version 2; the first writes the discount and becomes version 3; the second, who believed they were starting from 2, is rejected and must re-read, decide and retry. Without this check the last write would win silently and an operation would vanish from the history. What the listing does not do: it does not publish the events on a bus, it has no snapshots (after thousands of events a full rebuild is slow) and it uses a single process. In production you add a mechanism (an outbox table or equivalent) to publish the events atomically with the write.
An immutable log also poses a personal-data problem: if you put name and tax code in the events, you could no longer delete them. The simplest way is to keep only party identifiers in the events and store personal details elsewhere, so that they can be deleted when the retention obligation ends. Article 17, paragraph 3, points b and e of the GDPR excludes erasure to the extent that processing serves a legal obligation or the defence of a legal claim: which data fall under that exception and for how long is decided by your legal officer, not by this article.
Endorsements and the pro-rata calculation
An endorsement is a change during the life of the policy: adding a driver, changing the vehicle, raising a limit. It changes the premium for the remaining days only, and a classic error hides here: dividing by 365 without looking at the calendar. On a period that crosses a 29 February the days are 366, and the right ratio is remaining days over days in the period.
The prorata_adjustment function computes both values and rejects an endorsement outside the
period (remaining negative or above the total). The result is rounded to the cent with
ROUND_HALF_UP only once, at the end. The comparison with the fixed-365-day version is in the
listing precisely to show how much it matters.
from datetime import date
from decimal import Decimal as D, ROUND_HALF_UP
CENT = D("0.01")
def prorata_adjustment(old_annual, new_annual, endorsement, expiry, inception):
"""Premium difference for the remaining days only, on the actual days of the period."""
period_days = (expiry - inception).days
remaining = (expiry - endorsement).days
if not (0 <= remaining <= period_days):
raise ValueError("endorsement outside the policy period")
delta = (new_annual - old_annual) * D(remaining) / D(period_days)
return delta.quantize(CENT, ROUND_HALF_UP), remaining, period_days
def prorata_with_365(old_annual, new_annual, endorsement, expiry):
remaining = (expiry - endorsement).days
return ((new_annual - old_annual) * D(remaining) / D(365)).quantize(CENT, ROUND_HALF_UP)
old, new = D("480.00"), D("515.00")
for label, inception, expiry, endo in [
("period 2026-07-01..2027-07-01", date(2026, 7, 1), date(2027, 7, 1), date(2026, 10, 1)),
("period 2027-07-01..2028-07-01", date(2027, 7, 1), date(2028, 7, 1), date(2027, 10, 1)),
]:
exact, remaining, total = prorata_adjustment(old, new, endo, expiry, inception)
approx = prorata_with_365(old, new, endo, expiry)
print(f"{label}: days {total}, remaining {remaining}, "
f"actual {exact} EUR, with fixed 365 {approx} EUR")
# An endorsement on the expiry day costs zero; one after the expiry is an error.
print(prorata_adjustment(old, new, date(2027, 7, 1), date(2027, 7, 1), date(2026, 7, 1))[0])
try:
prorata_adjustment(old, new, date(2027, 7, 2), date(2027, 7, 1), date(2026, 7, 1))
except ValueError as e:
print("expected error:", e)
# Output:
# period 2026-07-01..2027-07-01: days 365, remaining 273, actual 26.18 EUR, with fixed 365 26.18 EUR
# period 2027-07-01..2028-07-01: days 366, remaining 274, actual 26.20 EUR, with fixed 365 26.27 EUR
# 0.00
# expected error: endorsement outside the policy period
In the first period (365 days) the two methods coincide, 26.18 euros; in the second, which includes 29 February 2028, the fixed-365 method gives 26.27 euros against the correct 26.20: seven cents per policy. For a portfolio of hundreds of thousands of contracts the figure is not negligible and, above all, it is a difference that cannot be explained to a customer or to an auditor. The calculation rule (actual days or a commercial year of 360) is a product choice: the listing uses actual days, and your company may have another one written in its terms.
The API: readable errors and repeatable requests
API-first means designing the contract first (an OpenAPI 3.1 document, for example) and then the implementation. The PAS operations are few and read like verbs on the lifecycle: create a quote, turn it into a policy (bind), modify it, cancel it, renew it. Creating the policy must be safe to repeat.
The reason is that a client that gets no response does not know whether the operation happened, and
retries. RFC 9110, section 9.2.2
considers PUT, DELETE and the safe methods idempotent: POST is not, so two identical POSTs can create two
policies. An IETF draft, The Idempotency-Key HTTP Header Field
(draft-ietf-httpapi-idempotency-key-header,
version 08 at the time of consultation, so not yet an RFC), proposes an Idempotency-Key header
for this purpose. In the listing the order of the checks also matters: the response already given is
returned before re-evaluating the quote, because on the second attempt the quote is already used and would
give 409.
from datetime import date, timedelta
from decimal import Decimal
from typing import Annotated
from fastapi import FastAPI, Header, HTTPException
from fastapi.testclient import TestClient
from pydantic import BaseModel, Field, field_validator
TODAY = date(2026, 11, 12) # fixed date, for a repeatable output
app = FastAPI(title="Policy API (demo)")
QUOTES: dict[str, dict] = {}
POLICIES: dict[str, dict] = {}
REPLAYS: dict[str, dict] = {} # Idempotency-Key -> response already given
class QuoteRequest(BaseModel):
product_code: str = Field(pattern=r"^[A-Z_]+$")
effective_date: date
driver_age: int = Field(ge=18, le=100)
@field_validator("effective_date")
@classmethod
def not_in_the_past(cls, v: date) -> date:
if v < TODAY:
raise ValueError("the effective date cannot be in the past")
return v
@app.post("/v1/quotes", status_code=201)
def create_quote(req: QuoteRequest):
premium = Decimal("400.00") if req.driver_age >= 26 else Decimal("540.00")
quote_id = f"Q-{len(QUOTES) + 1:04d}"
QUOTES[quote_id] = {"premium": str(premium), "valid_until": str(TODAY + timedelta(days=3)),
"effective_date": str(req.effective_date), "bound": False}
return {"quote_id": quote_id, **QUOTES[quote_id]}
@app.post("/v1/quotes/{quote_id}/bind", status_code=201)
def bind(quote_id: str, idempotency_key: Annotated[str, Header()]):
if idempotency_key in REPLAYS: # same key: same response
return REPLAYS[idempotency_key]
quote = QUOTES.get(quote_id)
if quote is None:
raise HTTPException(404, "unknown quote")
if date.fromisoformat(quote["valid_until"]) < TODAY:
raise HTTPException(410, "quote expired")
if quote["bound"]:
raise HTTPException(409, "quote already turned into a policy")
quote["bound"] = True
policy = {"policy_number": f"POL-{len(POLICIES) + 1:04d}", "status": "IN_FORCE",
"premium": quote["premium"]}
POLICIES[policy["policy_number"]] = policy
REPLAYS[idempotency_key] = policy
return policy
c = TestClient(app)
body = {"product_code": "AUTO_RC", "effective_date": "2026-12-01", "driver_age": 31}
r = c.post("/v1/quotes", json=body)
print("quote ", r.status_code, r.json())
qid = r.json()["quote_id"]
print("past ", c.post("/v1/quotes", json={**body, "effective_date": "2026-01-01"}).status_code)
print("age 17 ", c.post("/v1/quotes", json={**body, "driver_age": 17}).status_code)
h = {"Idempotency-Key": "abc-123"}
print("bind ", c.post(f"/v1/quotes/{qid}/bind", headers=h).json())
print("bind replay", c.post(f"/v1/quotes/{qid}/bind", headers=h).json())
print("other key ", c.post(f"/v1/quotes/{qid}/bind", headers={"Idempotency-Key": "xyz"}).status_code)
print("no key ", c.post(f"/v1/quotes/{qid}/bind").status_code)
print("policies created:", len(POLICIES))
# Output:
# quote 201 {'quote_id': 'Q-0001', 'premium': '400.00', 'valid_until': '2026-11-15', 'effective_date': '2026-12-01', 'bound': False}
# past 422
# age 17 422
# bind {'policy_number': 'POL-0001', 'status': 'IN_FORCE', 'premium': '400.00'}
# bind replay {'policy_number': 'POL-0001', 'status': 'IN_FORCE', 'premium': '400.00'}
# other key 409
# no key 422
# policies created: 1
The listing uses FastAPI's TestClient, which calls the application in-process without opening
ports (FastAPI testing documentation);
it was run with FastAPI 0.136.3 and Pydantic 2.13.4. The field_validator validator rejects an
effective date in the past, and "today's date" is a constant to make the output repeatable. Read the last
five lines: the same key abc-123 returns the same policy and
policies created: 1 confirms that a second one was not born; a different key on the same quote
answers 409, because the quote has already been used; without a key the request is rejected with 422 (the
IETF draft provides for 400 for a missing key: FastAPI uses 422 for missing headers, and if you want 400
you have to write it).
The listing has limits that matter in production. The keys and the policies live in process dictionaries:
two replicas of the API would share nothing, and you must use a shared store with a uniqueness constraint on
the key. It does not compare the content of the request with that of the first time: the draft recommends
422 if the same key arrives with a different payload. And the "look up, then write" step is not atomic. A
last security note concerns broker portals: an endpoint like
/v1/broker/{code}/portfolio must check that the authenticated broker really is that code.
OWASP API1:2023, Broken Object Level Authorization
describes this flaw, which comes from trusting an identifier that arrives from the client.
Splitting into services without building a distributed monolith
The typical decomposition follows the contexts: quoting, policies, billing, documents, notifications, underwriting. Each service owns its data and talks to the others through events, so billing never reads the policies table, it listens for "policy bound".
| Service | Responsibility | How it talks to the others |
|---|---|---|
| quote-service | Quotes and rating | Synchronous API and events |
| policy-service | Lifecycle and event store | Synchronous API and events |
| billing-service | Collections, instalments, refunds | Events |
| document-service | Policy documents and endorsements | Events, asynchronously |
| underwriting-service | Risk assessment | Synchronous API |
The cost to put on the scale: every service boundary introduces latency, events that arrive out of order and processes spanning several services (issuance = assessment + policy + invoice + document) to be coordinated with compensations when one fails. If the team is small, a modular monolith with these boundaries already carved into the code is a more prudent starting point, and modules are extracted when a boundary really holds. The three mistakes seen most often are these:
- a single
policiestable with hundreds of columns, which flattens all lines of business - in-place updates with no history, which make it impossible to rebuild the state at a date
- bind or cancellation operations without an idempotency key, which double the contracts on retries
All three are the same choice taken at different moments: favouring the simplicity of writing at the expense of being able to explain, afterwards, what happened. The three pieces of this article (log, pro-rata, idempotency) are the minimum countermeasures, and you can adopt them even in a monolith without touching the architecture.
Renewals: a window, not a date
Renewal is a process, not an event: a certain number of days before expiry the renewal premium is calculated, communicated, and the response awaited. The notice windows (how many days before, how many times) are product and regulatory decisions, and I have not verified any of them, so I give you no numbers: in the code they go into configuration. What can be said for sure is how to set up the nightly job so that it is safe to rerun:
- select policies with a query on the expiry date, not with a day counter kept in memory
- record the notice sent as an event, so a second pass does not send another
- compare the renewal premium with the previous one and flag exceptional changes for review
The first item prevents a job outage from losing a day of expiries, the second makes the job idempotent like the API, the third catches table errors before they reach the customer. The criterion of "exceptional" is a threshold the company sets. In the retail space the rules on communicating premiums to the customer depend on the country and the class of business: check them with whoever handles compliance.
What you can do now
You can keep the history of a policy as a sequence of events and rebuild its state; you can make the second of two simultaneous writers fail instead of losing a change; you can compute an endorsement on actual days and explain why a fixed 365 is off by a few cents; you can make the creation of a policy safe to repeat and you know where your implementation stops being sufficient. The next step is to feed the price with real driving data: Telematics pipeline, and after that AI underwriting.
Frequently asked questions
Why use an event log for policies?
Because the question "what was the policy like on a given date" recurs in claims and disputes, and an in-place update destroys it. With events the history is the data and the current state is a sum you can rebuild. The price is more complexity: snapshots, reliable publication of events and handling of personal data.
How do you avoid creating two policies if the client retries?
With an idempotency key sent by the client and stored by the server together with the response: on the second request with the same key the result already produced is returned without re-executing. The IETF draft on the Idempotency-Key header describes the mechanism; the uniqueness constraint must live in the shared store, not in memory.
Why not divide the premium by 365 days?
Because a period that crosses a 29 February lasts 366 days, and the right ratio is between remaining days and days in the period. In the listing the difference is seven cents per policy. If your company uses a commercial year, the rule is in the product terms.
Sources
- RFC 9110, HTTP Semantics, section 9.2.2 Idempotent Methods - which methods are idempotent (PUT, DELETE, safe methods) and hence that POST is not, consulted on 2026-11-12
- The Idempotency-Key HTTP Header Field (Internet-Draft, version 08) - header, payload fingerprint and the 400, 409 and 422 codes; it is an active draft, not an RFC, consulted on 2026-11-12
- Event Sourcing, Martin Fowler - the pattern of state as a sum of events, consulted on 2026-11-12
- OWASP API Security Top 10, API1:2023 Broken Object Level Authorization - the flaw of unverified object identifiers, consulted on 2026-11-12
- FastAPI, Testing - the
TestClientused in the listing, consulted on 2026-11-12 - OpenAPI Specification v3.1.0 - the format for describing the API contract, consulted on 2026-11-12
- Regulation (EU) 2016/679 (GDPR), EUR-Lex - article 17, paragraph 3, points b and e, consulted on 2026-11-12
The listings were run twice with the same output: eventstore.py and proration.py with Python 3 and the standard library, api.py with the repository's ML service environment (FastAPI 0.136.3, Pydantic 2.13.4). The premiums are invented.
Commenti
Caricamento commenti...
Sign in to comment