System Design, DDD, Agenticby Michael Wybraniec

MutuelleFit: contracts from a payroll-native insurance vertical

Enrolment aggregate, transactional outbox, InsurerGateway ACL, ANI cents, command vs event, at-least-once buses, webhook edge, Spec Kit agentic delivery — a DDD vertical you can demo.

MutuelleFit is a thin Insurance bounded context POC: multi-tenant enrol / dispense → carrier affiliation behind an anti-corruption layer → Santé premium instructions for a payroll stub. Design sources: constitution, docs/base.md, Spec Kit feature 001-mutuelle-enrolment-cotisations.

One breath: DDD decides the walls (who owns enrolment vs payroll vs employee). System design decides the pipes and failure modes (api / worker / outbox / queue / retries). They nest — they are not competitors.

Figures use seed data only (Company 1 / Employee 1). No live credentials. Carrier names are ACL stubs. Hover or focus a figure to blur it and read the contract.

Live guided demo on GitHub Pages — a cursor walks Docs → enrol until Covered → Architecture play → Cards. It loads only when you click below (so the auto-tour cannot yank page scroll). Full screen: MutuelleFit demo.

MutuelleFit — insurance vertical guided demo

Guided demo — Play demo or Play demo with music (Bensound).

What the vertical proves — constitution principles I–VII plus Spec Kit clarifications:

#ContractEvidence
1Enrol is async202 + PendingExternal; Active only after ACL confirm
2Bounded writesInsurance never writes Payroll tables; ids + cents on the bus
3ACL, not productsSame EnrolEmployee; InsurerGateway → AlanStub | AxaStub
4Outbox + idempotency in PostgresSame TX as aggregate; (companyId, route, key) store
5ANI moneyInteger EUR cents; employer ≥ 50%; half-up + remainder
6Tenant isolationX-Company-Id mismatch → 403
7Honest failureRetry ×3 → Failed + DLQ counter — never silent Active
8Agentic railsSpec Kit + domain skills block illegal transitions

Target pain: double entry between HRIS and insurer, wrong cotisations on the bulletin, leavers still “covered.” The POC is the smallest vertical that still has real architecture — not claims, marketplace, or DSN/URSSAF.

Pitch: for many client companies, turn employee lifecycle into mutuelle affiliation and payroll-ready cotisations — DDD vertical + events + outbox + swappable carrier ACLs.

Docs overview — Insurance as bounded context
Docs · Start

Five ownership zones. Write authority is the cut that matters — not how many containers you deploy. Walls first (Insurance vs Employee vs Payroll); then pipes (HTTPS commands, outbox → bus, ACL HTTPS, webhooks).

Five ownership zones diagram
Ownership zones

Hexagonal / ports-and-adapters. Driving adapters: HTTP domain API + worker. Driven adapters: Postgres, in-process bus (prod-shaped → SQS / SNS / EventBridge), AlanStub / AxaStub. Domain aggregates contain zero carrier DTOs — only InsurerGateway. That is the anti-corruption layer.

Context map. Employee / Company are upstream. Payroll is downstream customer/supplier via PremiumInstructionIssued. Carriers are conformist at the ACL, not in the core model. Identity is stub headers (X-Role, X-Company-Id) in the POC.

flowchart TB
  subgraph Upstream["Upstream"]
    EMP[Employee]
    CO[Company]
    ID[Identity stub]
  end
  subgraph InsuranceBC["Insurance BC"]
    API["Domain API /v1"]
    AGG["Enrolment aggregate + FSM"]
    OB[(outbox · idempotency · audit)]
    W[Activation worker]
    GW["InsurerGateway"]
  end
  subgraph Downstream["Downstream / edge"]
    PAY[Payroll stub]
    ALAN[AlanStub]
    AXA[AxaStub]
  end
  EMP -->|Terminated| W
  CO -->|carrier config| AGG
  ID -->|authZ| API
  API --> AGG
  AGG --> OB
  W --> OB
  W --> GW
  GW --> ALAN
  GW --> AXA
  W -->|PremiumInstructionIssued| PAY
Cover UI beside live architecture graph
Cover · Architecture tab

Command → same-TX outbox → worker → ACL → Active → premium instruction → payroll stub.

Sequence diagram enrol async path
Sequence · enrol

Same ACID transaction:

  1. Enforce invariants — ≤1 open PendingExternal|Active per (companyId, employeeId); plan exists; insurance enabled; coverage = collective.
  2. Persist Enrolment as PendingExternal.
  3. Insert outbox row (event_type + jsonb payload).
  4. Upsert idempotency_keys (company_id, route, key) → cached 202 body.

Worker drains Pending / outbox → createMember → on success FSM → Active + EmployeeEnrolledInInsurance + PremiumInstructionIssued. Timeout increments attempt_count; after 3 → Failed + dead_letter_counters.

Example · enrol (Company A / Alan)

enrol-company-a.sh
curl -sS \
  -H "X-Role: company.admin" \
  -H "X-Company-Id: company-a" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: demo-enrol-a-1" \
  -X POST "http://localhost:3810/v1/companies/company-a/enrolments" \
  -d '{
    "employeeId": "emp-a1",
    "planId": "sante-base",
    "coverage": "collective",
    "effectiveFrom": "2026-04-01"
  }'
# → 202 { enrolmentId, status: "PendingExternal" }

Example · dual carrier (Company B / AXA)

enrol-company-b.sh
curl -sS \
  -H "X-Role: company.admin" \
  -H "X-Company-Id: company-b" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: demo-enrol-b-1" \
  -X POST "http://localhost:3810/v1/companies/company-b/enrolments" \
  -d '{
    "employeeId": "emp-b1",
    "planId": "sante-base",
    "coverage": "collective",
    "effectiveFrom": "2026-04-01"
  }'
# ACL log differs; PremiumInstruction shape identical

Example · published language

premium-instruction.ts
PremiumInstructionIssued {
  eventId, occurredAt, companyId, employeeId, enrolmentId,
  periodFrom, periodTo,   // Europe/Paris month of effectiveFrom
  employerShareCents,     // half-up from plan.employerSharePct
  employeeShareCents,     // remainder so sum === premium
  currency: "EUR"
}

Command vs event. EnrolEmployee is a command — please do X; it can be refused (400 / 403 / 409). EmployeeEnrolledInInsurance and PremiumInstructionIssued are domain events — past-tense facts others react to. Never name an event UpdateEnrolment (a DB verb); consumers need a business fact. One aggregate TX in Insurance; Payroll must not join that TX.

Money: splitShares(monthlyPremiumCents, employerSharePct) rejects employerSharePct < 50, half-up on employer cents, employee gets remainder. Seed plan → 60 / 40 EUR on the bulletin preview.

Effective dating & proration. Cover and premium instructions carry a validity interval, not only a “current” flag. Spec Kit locked period = whole calendar month of effectiveFrom in Europe/Paris (full_month — no mid-month pro-rata engine in v1). Say the rule aloud, then stick to it; fixing a wrong premium means a new/changed instruction + audit, not a silent rewrite of history.

Illegal transitions are rejected in the aggregate. UI labels map 1:1 to engine names.

Enrolment finite state machine
Docs · Statuses

Spec Kit defaults that stop invention: missing Idempotency-Key → 400; replay → 202 same body; terminate vs activate → terminate wins; webhook already Active → 200 no-op; Cancel on Dispensed / Failed → 409.

Saga vs FSM. Enrolment is multi-step in life (accept → insurer → Active → Payroll), but the MVP keeps an Enrolment FSM + worker retries — not a saga framework. Introduce an explicit saga (with compensations as first-class steps) only when branching gets heavy. Pending + leave already compensates locally and at the ACL without a workflow engine.

Reliability tables are the design. Domain refs stay boring on purpose.

Postgres ER diagram
ER · insurance_poc
TablePatternKey columns
enrollmentsAggregate write modelstatus, attempt_count, insurer_member_id, carrier
outboxTransactional outboxevent_type, payload, published_at
idempotency_keysCommand dedupe(company_id, route, key) → response_body
audit_logAppend-only trailcorrelation_id, action, detail
dead_letter_countersOps signalcount, last_enrollment_id
payroll_linesDownstream stubWritten from events — not from enrol commands

Insurance’s own HTTP API — not the insurer’s, not Payroll’s. Command / query style; server enforces invariants + authZ.

MethodPathRoleIntent
POST/v1/companies/:id/enrolmentscompany.adminEnrolEmployee + Idempotency-Key
POST/v1/companies/:id/dispensescompany.adminDispenseEmployee
POST/v1/enrolments/:id/cancellationscompany.adminCancelEnrolment → Ended
GET/v1/companies/:id/enrolmentscompany.adminList cover
GET/v1/enrolments/:idcompany.adminDetail
GET/v1/me/coveremployee.selfMy cover
POST/v1/webhooks/carriers/:carriercarrier sigConfirm / reject
POST/v1/dev/platform-eventssystem.workerTerminate ingress
GET/v1/companies/:id/payroll-linescompany.adminBulletin preview
GET/v1/companies/:id/auditcompany.adminAudit tail

Webhook path (carrier → us). Never trust the body blindly: verify signature (X-Carrier-Signature stub secret in POC → 401 if wrong) → dedupe insurerEventId (inbox) → match/upsert on insurerMemberId / enrolmentId → drive the FSM via a domain command → emit our events on the outbox (not raw insurer JSON). Out-of-order is OK if upsert is idempotent. Demo gate may activate sync via stubs; the webhook contract still exists so duplicate notify is a no-op, not a second Active.

Happy path is cheap. This table is the review gate:

CaseExpected
Double-click enrolSame Idempotency-Key → same enrolment
Insurer timeoutPending → retry → Failed@3 + DLQ counter
Duplicate webhookinsurerEventId inbox → no-op
Terminate while PendingCancel local + compensate stub
Dispense instead of enrolDispensed; no PremiumInstruction
Wrong company403
Dispense while Active / Pending409
Missing Idempotency-Key400

Example · tenancy 403

tenancy-403.sh
curl -sS -o /dev/null -w "%{http_code}\n" \
  -H "X-Role: company.admin" \
  -H "X-Company-Id: company-a" \
  -H "Idempotency-Key: x" \
  -H "Content-Type: application/json" \
  -X POST "http://localhost:3810/v1/companies/company-b/enrolments" \
  -d '{"employeeId":"emp-b1","planId":"sante-base","coverage":"collective","effectiveFrom":"2026-04-01"}'
# → 403

Example · terminate

terminate.sh
curl -sS \
  -H "X-Role: system.worker" \
  -H "Content-Type: application/json" \
  -X POST "http://localhost:3810/v1/dev/platform-events" \
  -d @fixtures/employee-terminated.json
# → Ended + compensate + PremiumInstruction Stop

Thin client: commands + projections. Never calls the carrier. Never writes payslip lines.

MutuelleFit Cover admin UI
Cover
Payslip preview patronale and salariale
Cover · payslip

Prove domain + events + multi-company + two carriers. Everything else is seed, fixture, or stub.

Must codeSeedMock / defer
Enrolment aggregate + FSM testscompanies A/B, employees, plan, reasons, adminsReal Alan / AXA HTTP
Domain API enrol / list / getemployerSharePct ≥ 50SSO
Outbox same TX + publisherdispense reason codesSQS / K8s / Terraform
Worker + AlanStub + AxaStubAXA setup-sheet fixtureDSN / URSSAF
Idempotency + 403 tests—Marketplace, claims
Terminate handleremployee-terminated fixtureChangeCoverage

Ship order: seed → aggregate + tests → API → outbox → worker + stubs → idempotency → tenancy → terminate → demo curls / thin React.

Local: API :3810, worker, Postgres :5433, UI :5810 (hub.yaml). Cloud is transport — not a redesign:

POCProduction-shapedConcern
SQL outbox + publisherOutbox → SQS / SNS / EventBridgeFan-out, retry, DLQ
Activation workerEKS / ECS / Lambda consumerScale consumers ≠ API
Idempotency + inboxExactly-once effectBlips, webhook dupes
InsurerGateway stubsReal partner HTTP, same portAdapter swap
X-Correlation-Id + DLQ countersTraces, metrics, alarmsOperability

At-least-once is the default. SQS (and webhooks) can deliver more than once. Visibility timeout: while a worker processes a message, others don’t see it; if the process dies before delete/ack, the message reappears — that is the duplicate. Design for at-least-once delivery + idempotent handlers (outbox publish once logically; inbox / eventId / Idempotency-Key for effects). SNS = publish once, fan-out to many queues; SQS = competing consumers on one queue. DLQ = park poison after N fails and alert — don’t retry forever. Don’t bet on exactly-once delivery; aim for exactly-once effect.

Scale target: thousands of companies × employees × monthly payroll runs without leave-drift — not enrol QPS theatre.

What kept velocity from deleting the design:

  1. Spec Kit — constitution → specify → plan → tasks → implement.
  2. Domain skills — insurance-domain, insurer-acl, insurance-demo.
  3. hub.yaml — shared ports for humans and agents.
  4. Subagents + browser — explore in parallel, verify Cover / Docs on localhost.

Clarifications locked ~30 POC defaults (Europe/Paris month, cents canonical, Failed re-enrolable, terminate wins races, …). That is why agents did not invent a synchronous Active shortcut.

flowchart LR
  subgraph Spec["Spec Kit"]
    C[Constitution]
    S[Spec + clarifications]
    P[Plan / tasks]
    I[Implement]
  end
  subgraph Skills["Skills"]
    D[insurance-domain]
    A[insurer-acl]
    M[insurance-demo]
  end
  C --> S --> P --> I
  D --> I
  A --> I
  M --> I
  I --> Demo[Cover + curls + tests]
  • Walls then pipes — DDD ownership first; api/worker/queue second.
  • Aggregate + FSM honesty — Waiting is a product feature; saga only if branching demands it.
  • Command ≠ event — refuseable intent vs past-tense facts.
  • Transactional outbox + idempotency — in the schema; at-least-once on the bus.
  • ACL + signed webhooks — partner JSON stays at the edge.
  • Tenant authZ — 403 is a demo step.
  • Integer money + explicit period rule — ANI cents; full_month / Europe/Paris.
  • Edge matrix — Spec Kit clarifications beat vibes.
  • Agentic speed with a constitution — otherwise the UI lies.

MutuelleFit stays a POC: stubs, seed companies, thin admin. The contracts above are what transfer — whether the bus is in-process or EventBridge.

Michael Wybraniec

Michael Wybraniec

System Design, GenAI Automation & Architecture