Skip to main content

07 - ACORD Standards and Insurance API Integration

How to integrate insurance systems around ACORD: internal model, edge translation, JSON Schema and XSD validation, idempotent retries, with code that was run.

What do you think about this article?

At a Glance

How to integrate insurance systems around ACORD: internal model, edge translation, JSON Schema and XSD validation, idempotent retries, with code that was run.

The problem is not the standard, it is where you let it into your code

An insurer exchanges data with brokers, agencies, reinsurers, comparison sites and repair shops, and each of them has its own format. Standards exist so that every connection does not turn into a custom project; but a standard adopted badly becomes a second problem, because if your services speak the message language everywhere you end up with the partner's field names scattered through the whole codebase. The one rule that holds up over time is this: the standard lives in a single translation layer at the edge, and inside the system you speak your own domain.

The starting point is knowing what ACORD is and what I cannot show you. The ACORD site describes it as a non-profit standards-setting body for insurance and related financial services, active since 1970, with over 36,000 participating organizations in more than 100 countries. The page on data standards lists the families: XML and AL3 for property and casualty, XML for life and annuities, XML and JSON for reinsurance and large commercial risks, and "Next-Generation Digital Standards" designed for APIs, microservices and IoT. The texts of the messages, however, require access to the site (the page shows restricted areas and purchases): I do not reproduce element names, codes or versions, because I cannot verify them and a wrong name in a real integration costs days.

What I can do, and what you need in any case, is build and test the layer around the message: internal model, translation, validation, reliability. The format I use here is a didactic exchange profile, made up for the occasion and declared as such in every listing. It is not the ACORD standard and no message below should be read as an ACORD message.

For the domain context you need the first article of the series and, for the API that exposes the policy, the API-first architecture of Policy Management.

The internal model and the translation layer

The listing defines a RichiestaInterna (the internal request) with the names of your domain and two functions, a_messaggio and da_messaggio (to and from the message), which are the only places where the exchange profile appears. The codes (fuel, coverages) live in data tables and not in a chain of if statements: when the partner changes version you edit a table, not the logic. Three details deserve attention. The class is frozen, because a request does not change after it is sent. The coverages are a frozenset and not a list, because the order is not information: with a list the round trip returned False because of the order. And the message identifier is a type 5 UUID, computed from the request identifier: the same message sent again has the same id, which becomes indispensable in the reliability section.

The identifiers and the field names of the profile (assicurato is the insured, veicolo the vehicle, coperture the coverages, decorrenza the start date, targa the plate) stay in Italian, as in the Italian edition of this article: they belong to the made-up profile, not to the English you read around them.

modello.py: from the internal model to the exchange profile and back
import json
from dataclasses import dataclass
from datetime import date, datetime, timezone
from uuid import NAMESPACE_URL, uuid5

# DIDACTIC exchange profile "scambio-auto/1" (Italian for "auto exchange"): names and codes are mine, they are NOT ACORD.
# In a real integration this table comes from the specification the partner hands you.
CARBURANTE = {"benzina": "GAS", "diesel": "DIE", "elettrico": "ELE", "ibrido": "HYB"}
CARBURANTE_INVERSO = {v: k for k, v in CARBURANTE.items()}
COPERTURE = {"rca": "LIAB", "kasko": "COMP", "cristalli": "GLAS"}


@dataclass(frozen=True)
class RichiestaInterna:
    """MY model: the names follow my domain, not the partner's."""
    id_richiesta: str
    nome: str
    cognome: str
    nascita: date
    data_patente: date
    targa: str
    anno_immatricolazione: int
    alimentazione: str
    km_annui: int
    garanzie: frozenset[str]   # a set: the order of the coverages is not information
    decorrenza: date


def a_messaggio(r: RichiestaInterna, inviato: datetime) -> dict:
    """Translates from the internal model to the exchange profile. The message identifier is
    DETERMINISTIC: same request, same id. A resend does not create a new message."""
    contenuto = {
        "assicurato": {"nome": r.nome, "cognome": r.cognome, "nascita": r.nascita.isoformat(),
                       "patente": r.data_patente.isoformat()},
        "veicolo": {"targa": r.targa, "anno": r.anno_immatricolazione,
                    "carburante": CARBURANTE[r.alimentazione], "km_annui": r.km_annui},
        "coperture": sorted(COPERTURE[g] for g in r.garanzie),
        "decorrenza": r.decorrenza.isoformat(),
    }
    return {
        "profilo": "scambio-auto/1",
        "id_messaggio": str(uuid5(NAMESPACE_URL, "richiesta:" + r.id_richiesta)),
        "inviato_il": inviato.astimezone(timezone.utc).isoformat(timespec="seconds"),
        "richiesta": contenuto,
    }


def da_messaggio(m: dict, id_richiesta: str) -> RichiestaInterna:
    c = m["richiesta"]
    inverso = {v: k for k, v in COPERTURE.items()}
    return RichiestaInterna(
        id_richiesta=id_richiesta, nome=c["assicurato"]["nome"], cognome=c["assicurato"]["cognome"],
        nascita=date.fromisoformat(c["assicurato"]["nascita"]), data_patente=date.fromisoformat(c["assicurato"]["patente"]),
        targa=c["veicolo"]["targa"], anno_immatricolazione=c["veicolo"]["anno"],
        alimentazione=CARBURANTE_INVERSO[c["veicolo"]["carburante"]], km_annui=c["veicolo"]["km_annui"],
        garanzie=frozenset(inverso[x] for x in c["coperture"]), decorrenza=date.fromisoformat(c["decorrenza"]),
    )


if __name__ == "__main__":
    r = RichiestaInterna("RQ-2026-0042", "Marta", "Bianchi", date(1990, 5, 17), date(2008, 9, 3), "FK123RT",
                         2022, "ibrido", 12000, frozenset({"rca", "kasko"}), date(2026, 12, 1))
    ora = datetime(2026, 11, 12, 10, 30, tzinfo=timezone.utc)
    messaggio = a_messaggio(r, ora)
    print(json.dumps(messaggio, indent=2, ensure_ascii=False))
    print("round trip identical:", da_messaggio(messaggio, r.id_richiesta) == r)
    print("same id on resend:", a_messaggio(r, ora.replace(minute=45))["id_messaggio"] == messaggio["id_messaggio"])

# Output:
# {
#   "profilo": "scambio-auto/1",
#   "id_messaggio": "6050e3da-01bb-54a2-93e0-ef7ae7e0cad5",
#   "inviato_il": "2026-11-12T10:30:00+00:00",
#   "richiesta": {
#     "assicurato": {
#       "nome": "Marta",
#       "cognome": "Bianchi",
#       "nascita": "1990-05-17",
#       "patente": "2008-09-03"
#     },
#     "veicolo": {
#       "targa": "FK123RT",
#       "anno": 2022,
#       "carburante": "HYB",
#       "km_annui": 12000
#     },
#     "coperture": [
#       "COMP",
#       "LIAB"
#     ],
#     "decorrenza": "2026-12-01"
#   }
# }
# round trip identical: True
# same id on resend: True

The output shows the message produced: the coverages are sorted (COMP, LIAB) to get a stable result, the sending time is in UTC with an explicit offset, and the fuel "ibrido" (hybrid) became HYB. The last two lines are the two tests that matter: the message, read back, returns the identical request, and a resend at another time has the same id_messaggio. The sending moment enters as an argument instead of being read from the clock: a function that calls datetime.now() is not reproducible, and an identical message would produce two different hashes.

Validating the message: JSON Schema and the format trap

A malformed message is sometimes rejected explicitly and sometimes accepted in silence, and the second case is the one that costs you: a wrong date field enters the recipient's system and resurfaces weeks later. So you validate before sending, with the schema, and after receiving, because you cannot trust whoever writes. The schema below is written for JSON Schema 2020-12 and uses required, enum, pattern, minimum/maximum and uniqueItems. The listing applies it to a message with six deliberate defects, first without and then with the format check.

validazione.py: six defects, two validator configurations
import json

from jsonschema import Draft202012Validator, FormatChecker

SCHEMA = {
    "$schema": "https://json-schema.org/draft/2020-12/schema",
    "type": "object",
    "required": ["profilo", "id_messaggio", "inviato_il", "richiesta"],
    "properties": {
        "profilo": {"const": "scambio-auto/1"},
        "id_messaggio": {"type": "string", "format": "uuid"},
        "inviato_il": {"type": "string", "format": "date-time"},
        "richiesta": {
            "type": "object",
            "required": ["assicurato", "veicolo", "coperture", "decorrenza"],
            "properties": {
                "assicurato": {
                    "type": "object",
                    "required": ["nome", "cognome", "nascita", "patente"],
                    "properties": {
                        "nome": {"type": "string", "minLength": 1},
                        "cognome": {"type": "string", "minLength": 1},
                        "nascita": {"type": "string", "format": "date"},
                        "patente": {"type": "string", "format": "date"},
                    },
                },
                "veicolo": {
                    "type": "object",
                    "required": ["targa", "anno", "carburante", "km_annui"],
                    "properties": {
                        "targa": {"type": "string", "pattern": "^[A-Z]{2}[0-9]{3}[A-Z]{2}$"},
                        "anno": {"type": "integer", "minimum": 1950, "maximum": 2100},
                        "carburante": {"enum": ["GAS", "DIE", "ELE", "HYB"]},
                        "km_annui": {"type": "integer", "minimum": 0, "maximum": 200000},
                    },
                },
                "coperture": {"type": "array", "items": {"enum": ["LIAB", "COMP", "GLAS"]}, "minItems": 1, "uniqueItems": True},
                "decorrenza": {"type": "string", "format": "date"},
            },
        },
    },
}

BUONO = {
    "profilo": "scambio-auto/1", "id_messaggio": "6050e3da-01bb-54a2-93e0-ef7ae7e0cad5",
    "inviato_il": "2026-11-12T10:30:00+00:00",
    "richiesta": {
        "assicurato": {"nome": "Marta", "cognome": "Bianchi", "nascita": "1990-05-17", "patente": "2008-09-03"},
        "veicolo": {"targa": "FK123RT", "anno": 2022, "carburante": "HYB", "km_annui": 12000},
        "coperture": ["COMP", "LIAB"], "decorrenza": "2026-12-01",
    },
}


def errori(validatore, messaggio):
    trovati = sorted(validatore.iter_errors(messaggio), key=lambda e: list(e.absolute_path))
    return [f"/{'/'.join(map(str, e.absolute_path))}: {e.message}" for e in trovati]


rotto = json.loads(json.dumps(BUONO))
rotto["richiesta"]["assicurato"]["nascita"] = "1990-13-45"          # a date that does not exist
rotto["richiesta"]["veicolo"]["carburante"] = "BENZINA"             # code outside the profile
rotto["richiesta"]["veicolo"]["km_annui"] = "12000"                 # a string instead of an integer
rotto["richiesta"]["coperture"] = ["LIAB", "LIAB"]                  # duplicated
del rotto["richiesta"]["decorrenza"]                                # required field missing
rotto["inviato_il"] = "last night"

senza = Draft202012Validator(SCHEMA)
con = Draft202012Validator(SCHEMA, format_checker=FormatChecker())
print("without format_checker:")
for e in errori(senza, rotto):
    print("  ", e)
print("with format_checker:")
for e in errori(con, rotto):
    print("  ", e)
print("good message valid:", not errori(con, BUONO))
print("formats actually checked:", sorted(f for f in ("date", "date-time", "uuid", "email") if f in FormatChecker().checkers))

# Output:
# without format_checker:
#    /richiesta: 'decorrenza' is a required property
#    /richiesta/coperture: ['LIAB', 'LIAB'] has non-unique elements
#    /richiesta/veicolo/carburante: 'BENZINA' is not one of ['GAS', 'DIE', 'ELE', 'HYB']
#    /richiesta/veicolo/km_annui: '12000' is not of type 'integer'
# with format_checker:
#    /richiesta: 'decorrenza' is a required property
#    /richiesta/assicurato/nascita: '1990-13-45' is not a 'date'
#    /richiesta/coperture: ['LIAB', 'LIAB'] has non-unique elements
#    /richiesta/veicolo/carburante: 'BENZINA' is not one of ['GAS', 'DIE', 'ELE', 'HYB']
#    /richiesta/veicolo/km_annui: '12000' is not of type 'integer'
# good message valid: True
# formats actually checked: ['date', 'email', 'uuid']

Now read the difference between the two blocks of output. Without FormatChecker the validator reports four problems and does not see the date "1990-13-45". With the check it reports five, because the impossible date is caught. This is not a defect of the library: the JSON Schema 2020-12 specification defines format as an annotation, and makes the asserting behavior optional. If you do not ask for it, no error.

There is then a second level of deception, the one in the last line: even with the check, only date, email and uuid are really verified in this environment. The inviato_il field (the sending time) with the value "last night" went through undisturbed, because the check for date-time requires an additional package that is not installed here. The defense is twofold: read which formats your validator really checks, and for the critical ones add an explicit check in the code.

The XML case: the order of the elements matters

Many insurance standards were born in XML, where validation uses XSD. The behavior is stricter than JSON Schema: in an xs:sequence the order of the elements is part of the contract. The listing defines a minimal XSD, with a plate constrained by a pattern, a date of type xs:date and a non-negative integer, and applies it with lxml to three documents.

xsd.py: XSD with lxml, three documents
from lxml import etree

XSD = b"""<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="RichiestaAuto">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="Targa">
          <xs:simpleType>
            <xs:restriction base="xs:string"><xs:pattern value="[A-Z]{2}[0-9]{3}[A-Z]{2}"/></xs:restriction>
          </xs:simpleType>
        </xs:element>
        <xs:element name="Decorrenza" type="xs:date"/>
        <xs:element name="KmAnnui" type="xs:nonNegativeInteger"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>"""

schema = etree.XMLSchema(etree.fromstring(XSD))

documenti = {
    "correct": b"<RichiestaAuto><Targa>FK123RT</Targa><Decorrenza>2026-12-01</Decorrenza><KmAnnui>12000</KmAnnui></RichiestaAuto>",
    "wrong order": b"<RichiestaAuto><Decorrenza>2026-12-01</Decorrenza><Targa>FK123RT</Targa><KmAnnui>12000</KmAnnui></RichiestaAuto>",
    "impossible date": b"<RichiestaAuto><Targa>FK123RT</Targa><Decorrenza>2026-02-30</Decorrenza><KmAnnui>12000</KmAnnui></RichiestaAuto>",
}
for nome, xml in documenti.items():
    doc = etree.fromstring(xml)
    if schema.validate(doc):
        print(f"{nome:<17} valid")
    else:
        print(f"{nome:<17} NOT valid: {schema.error_log[0].message}")

# Output:
# correct           valid
# wrong order       NOT valid: Element 'Decorrenza': This element is not expected. Expected is ( Targa ).
# impossible date   NOT valid: Element 'Decorrenza': '2026-02-30' is not a valid value of the atomic type 'xs:date'.

The first is valid. The second has the same data but Decorrenza before Targa, and is rejected with a message that says what it expected: in JSON the same exchange would have been indifferent, in XML it is an error. The third has a date with the right shape and a nonexistent day (30 February), and xs:date rejects it, unlike a plain regular expression. The error messages are those of lxml 6.0.2 with libxml2 2.15.2: they change from one version to another, so in your logs record the text but do not base logic on it; use the fact that validation failed and, if needed, the error code.

Reliability: retrying a send without duplicating the case

Integrations fail halfway: the partner receives the message, creates the case, and the reply is lost on the way. The sender cannot tell this case from the one in which the message never arrived, so it retries. If the receiver is not prepared, the case is born twice. The property that solves the problem is called idempotency: RFC 9110 (section 9.2.2) defines it for HTTP methods as the property by which several identical requests have the same effect on the server as a single one. In HTTP PUT and DELETE are idempotent by definition, POST is not: to make it repeatable you need an identifier and a receiver that recognizes it. There is an IETF draft for an Idempotency-Key header (draft-ietf-httpapi-idempotency-key-header, at the last check still an active Internet-Draft and not an RFC), and many partners adopt similar conventions.

The listing simulates a partner that loses the reply in 60% of cases, after having processed the message, and a sender that retries with exponential backoff and full jitter: the wait is a random number between zero and the minimum of a cap and base * 2^n. Jitter prevents a thousand failed senders from all retrying at the same instant. The waits are reported and not slept, so as not to slow down the test.

ricezione.py: retries with and without idempotency
import random


class Ricevente:
    """The partner's system: sometimes it does not answer, but the message may already have been processed."""

    def __init__(self, p_guasto: float, seme: int, idempotente: bool = True):
        self.rng = random.Random(seme)
        self.p_guasto, self.idempotente = p_guasto, idempotente
        self.elaborati = {}            # id_messaggio -> outcome
        self.effetti = 0               # how many times a case was actually started

    def ricevi(self, id_messaggio: str) -> str:
        if not self.idempotente or id_messaggio not in self.elaborati:   # idempotency: same id, same outcome
            self.effetti += 1
            self.elaborati[id_messaggio] = f"CASE-{self.effetti:03d}"
        if self.rng.random() < self.p_guasto:          # the reply is lost after processing
            raise TimeoutError("no response")
        return self.elaborati[id_messaggio]


def invia_con_ripetizioni(ricevente, id_messaggio, rng, tentativi=6, base=0.2, tetto=5.0):
    """Exponential backoff with 'full jitter': the wait is random between 0 and min(cap, base*2^n).
    Returns (outcome, waits): the waits are reported, not slept, so the test stays fast."""
    attese = []
    for n in range(tentativi):
        try:
            return ricevente.ricevi(id_messaggio), attese
        except TimeoutError:
            attese.append(round(rng.uniform(0, min(tetto, base * 2 ** n)), 2))
    return None, attese


for idempotente in (False, True):
    rng = random.Random(3)
    ricevente = Ricevente(p_guasto=0.6, seme=5, idempotente=idempotente)
    esiti = [invia_con_ripetizioni(ricevente, f"msg-{i}", rng) for i in range(200)]
    risposte = sum(1 for e, _ in esiti if e)
    ripetuti = sum(1 for _, a in esiti if a)
    print(f"idempotent={idempotente!s:<5} messages=200 answered={risposte} retried={ripetuti} "
          f"cases created={ricevente.effetti} duplicates={ricevente.effetti - 200}")

print("waits of the first message that retried:", next(a for _, a in esiti if a))

# Output:
# idempotent=False messages=200 answered=191 retried=119 cases created=464 duplicates=264
# idempotent=True  messages=200 answered=191 retried=119 cases created=200 duplicates=0
# waits of the first message that retried: [0.05, 0.22]

The difference is in the first line. With the same messages (200) and the same retries (119 messages had at least one new attempt), the non-idempotent receiver creates 464 cases, with 264 duplicates; the one that recognizes the id_messaggio creates 200, no duplicates. Even so, 9 messages out of 200 remain without a reply after six attempts, although they were processed: the sender must be able to query the status of a message instead of sending it again, and idempotency is what makes that safe. The numbers come from a simulation with a fixed seed and from the 60% failure rate that I chose: they demonstrate the mechanism, not the behavior of a real partner.

Choosing the integration model

The exchange profile says how a message is built; the integration model says how it travels. The four classic forms differ in coupling and in where the complexity lives.

ModelWhen it makes senseCost
Point to pointfew partners, low volumesgrows with the square of the partners: every new connection is custom
Service bus (ESB)many heterogeneous systems in a large organizationa central node to keep evolving; logic tends to concentrate there
Events (message broker)high volumes, several consumers of the same facteventual consistency and the operational management of the broker
API gateway with adaptersfew entry points toward the outside, versionedone more layer on the path and one more component to size

There is no winning row, and combinations are common: a gateway toward external partners and events inside the company. The criterion that holds is to ask where you want to pay for the complexity: in many direct connections, in a central node or in a messaging infrastructure. The translation layer of this article is needed in all four cases, which is why it is the part to get right first.

Versions, retries, retention and rejections: four points to settle with the partner

Before putting a connection into production, clarify these points in writing, because the worst defects are not in the code but in the agreement:

  • Profile version: every message declares its own, as the profilo field does, and the code tables are versioned data, not constants in the code.
  • Identifier and retries: who generates the message id, and what the receiver answers to a duplicate (the same outcome, not an error).
  • Message retention: for how long the exchanged messages are archived; the period is set by the applicable regulation and by the insurer's compliance, not by this article.
  • Rejection codes: which errors are final (do not retry) and which temporary (retry with backoff).

The fourth point is the one that separates an integration that holds from one that hammers the partner: retrying a final error, such as an invalid field, is useless and noisy. The engine of invia_con_ripetizioni (send with retries) retries only on timeout; a real integration also tells the response codes apart. The retention topic ties in with compliance, which requires being able to reconstruct a figure, and the claims flow of the series is one of the messages that cross this layer.

What you can do now

You can keep the standard at the edge of the system, with an immutable internal model and a translator driven by versioned tables. You can validate a message knowing what your validator really does: the format of JSON Schema is optional, and an XSD is stricter than a JSON schema about order. You can make a resend safe with a deterministic identifier and an idempotent receiver, and you have seen with reproducible numbers that without it a 60% failure rate produces 264 duplicate cases out of 200. For real ACORD messages you need access to the specification: the layer you built is the one that will receive them. The last article of the series brings the same rigor to the data an insurer must produce for the regulator: Solvency II and IFRS 17.

Frequently asked questions

What is ACORD and what is it for, for a developer?

ACORD is a non-profit body that defines data standards for insurance: XML and AL3 families for property and casualty, XML for life and annuities, XML and JSON for reinsurance and large risks, and digital standards for APIs and microservices. You need it to exchange data with brokers, agencies and reinsurers without inventing a format for each; the texts of the messages require access to the specification.

Why does JSON Schema validation accept a wrong date?

Because in the 2020-12 specification the format keyword is an annotation, and checking it as an assertion is optional. With the Python jsonschema library you must pass a FormatChecker, and even so some formats, such as date-time, require additional packages.

How do you avoid duplicates when a send is retried?

By giving every message a stable identifier that stays the same across resends, and by having the receiver recognize that id and answer a duplicate with the same outcome. In the simulation in the article, with 60% of replies lost, the receiver without idempotency creates 264 duplicates out of 200 messages, the one with idempotency zero.

In this series: previous article, Insurance Fraud Detection: Ranking, Leakage and Graphs.

Sources

The listings were run with Python 3.14, jsonschema 4.19.2 and lxml 6.0.2, twice in a row with the same output. The exchange profile is didactic and is not an ACORD message; real ACORD messages must be built from the specification you have access to. The lxml error messages depend on the version of the library.

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