A motor insurance quote API on the DataPower Nano Gateway: eligibility, rating in Lua and a plain text policy schedule
Draft!!
An insurer’s quote service has two kinds of rule. Appetite rules say whether the company will quote at all. Rating rules say how much. This post builds ins-motorquotes, a motor quote API on the Nano Gateway that does both, with a plain text policy schedule as a second operation.
Read this first
I have not run this API on a Nano Gateway. I had no management login for the cluster, so I could not publish it. Most posts in this series were measured on a live gateway. This one was not.
Checked offline:
apic lintpasses.- Both Lua scripts run under Lua 5.5 and LuaJIT in a test harness, with assertions on the premiums in the pricing table below.
- The JSONata expressions pass a subset check, and the guards have unit tests.
tests/ins-motorquotes.shpasses a bash syntax check and a stub-server smoke run.
The premiums in this post come from running the Lua offline. They are not responses from a gateway. The assumptions are listed at the end.
The API
| Operation | Purpose |
|---|---|
POST /quotes/motor |
Returns a premium, or the reason the insurer will not quote. |
POST /quotes/motor/schedule |
Renders a policy schedule as plain text. |
The quote flow:
- parse-request
- validate-request
- eligibility # Lua: sets X-Eligibility and X-Driver-Age
- guard-dob-invalid # 422
- guard-under-age
- guard-over-age
- guard-licence-history
- guard-convictions
- guard-vehicle-value
- guard-vehicle-age
- cache-quote # rating, quote store, response
The order of the guards is the order of the reasons. When several rules fail, the caller sees the first one. The test sends a 17-year-old with nine convictions and expects not eligible: driver is under 18.
Appetite rules in Lua
The rules need today’s date, which JSONata cannot read, so one script works out the driver’s age and returns one result:
local MIN_AGE, MAX_AGE = 18, 85
local MAX_CONVICTIONS = 3
local MAX_VEHICLE_VALUE = 100000
local MAX_VEHICLE_AGE = 25
local result = 'ok'
if age < 0 then
result = 'dob-invalid'
elseif age < MIN_AGE then
result = 'under-age'
elseif age > MAX_AGE then
result = 'over-age'
elseif num(driver.licenceYears) > age - 17 then
result = 'licence-history'
elseif num(driver.convictions) > MAX_CONVICTIONS then
result = 'convictions'
elseif num(vehicle.value) > MAX_VEHICLE_VALUE then
result = 'vehicle-value'
elseif num(vehicle.year) > 0 and now.year - num(vehicle.year) > MAX_VEHICLE_AGE then
result = 'vehicle-age'
end
req.headers:set('X-Eligibility', result)
req.headers:set('X-Driver-Age', string.format('%d', age))
Seven reasons. Each has an If that reads X-Eligibility and a Throw that returns 422 with a sentence:
kind: If
spec:
condition: $header('request', 'X-Eligibility') = 'under-age'
execute:
- $ref: ins-motorquotes:ins-motorquotes-guard-under-age-throw:1.0.0
---
kind: Throw
spec:
error:
CustomError:
message: "not eligible: driver is under 18"
messageType: plain
status: 422
A date of birth that does not exist, such as 31 February, is caught by a round trip through os.time and os.date, the same trick as in the open banking post.
The licence rule is an example of a rule the schema cannot express. A licence held for more years than the driver has been 17 is nonsense. The test checks the boundary: age 30 with a licence of 14 years is refused, and 13 years is accepted.
Every boundary has a test on both sides: 17 and 18, 85 and 86, three and four convictions, a vehicle worth 100,000 and 100,001, a vehicle 25 and 26 years old.
The script always sets X-Eligibility, so a caller who sends their own header gets it overwritten. The test sends a forged X-Eligibility: ok with an under-age driver and expects 422.
Rating in a second script
Rating is arithmetic: a base premium for the cover, a loading on the vehicle value, a risk factor from the driver, and a discount for the voluntary excess.
local BASE = { comprehensive = 420, tpft = 310, tpo = 240 }
local LOADING = { comprehensive = 0.008, tpft = 0.005, tpo = 0 }
local DISCOUNT = { [0] = 0, [100] = 3, [250] = 6, [500] = 10 }
-- factor is a whole-number percentage so the sums stay exact
if age < 21 then factor = 220
elseif age < 25 then factor = 180
elseif age < 30 then factor = 130
elseif age <= 65 then factor = 100
else factor = 125 end
factor = factor + 20 * num(driver.convictions) + 12 * num(driver.claimsLast5Years)
if num(driver.licenceYears) < 2 then factor = factor + 30 end
local subtotal = BASE[cover] + num(vehicle.value) * LOADING[cover]
local discount = DISCOUNT[num(body.voluntaryExcess)] or 0
local annual = subtotal * factor / 100 * (100 - discount) / 100
The monthly figure is the annual premium plus a 10% finance charge, in twelve parts. A premium over 2,500 a year gets the status REFERRED instead of QUOTED, which would send it to an underwriter.
The reference quote: a 35-year-old, comprehensive, a vehicle worth 10,000 and a 250 excess.
- Base 420 plus 80 for the vehicle gives 500.
- Factor 100%, discount 6%, so 500 × 0.94 = 470.00 a year.
- Monthly: 470 × 1.1 / 12 = 43.08.
The test script asserts a table of these. They are the values my offline run produces, and a gateway run should produce the same:
| Change from the reference quote | Annual premium |
|---|---|
| Age 22, licence 5 years | 846.00 |
| Age 27 | 611.00 |
| Age 70 | 587.50 |
| One conviction | 564.00 |
| Two claims | 582.80 |
| Licence under two years | 611.00 |
| Third party, fire and theft | 338.40 |
| Third party only | 225.60 |
| No excess | 500.00 |
| 100 excess | 485.00 |
| 500 excess | 450.00 |
The factor is a whole-number percentage, which keeps the arithmetic simple. Lua numbers are doubles, and the offline run uses doubles too, but I have not checked the gateway’s rounding.
Cache the quote for a minute
Quoting the same risk twice in a minute should give the same answer and the same quote ID. The cache key is every field that affects the price, plus the client:
kind: Cache
spec:
inputs:
- custom:
expression: $telemetry('client_id') & '|' & $body('request').driver.dateOfBirth & '|' & $string($body('request').driver.licenceYears) & ...
outputs:
- messageBody:
name: response
expire:
static:
seconds: 60
execute:
- $ref: ins-motorquotes:ins-motorquotes-rating:1.0.0
- $ref: ins-motorquotes:ins-motorquotes-store-try:1.0.0
- $ref: ins-motorquotes:ins-motorquotes-quote-response:1.0.0
The eligibility checks sit outside the cache, so an ineligible risk is refused on every call. The test sends the same request twice and expects the same quoteId. It sends the same request with a 500 excess and expects a new one. It sends a new vehicle registration and expects a new one.
A quote store behind a load balancer
After pricing, the quote is “stored”. In this sample that means a call to one of two echo instances, behind a LoadBalancer, to prove the pool is used and the instance is recorded:
kind: LoadBalancer
spec:
input: request
output: core
roundRobinHttp:
verb: GET
endpoints:
- endpoint:
url: http://echo.pi-sample.svc.cluster.local/instance
urlType: plain
version: HTTP/1.1
timeout: 10
persistentConnections: true
suspendTimeout: 60
- endpoint:
url: http://echo2.pi-sample.svc.cluster.local/instance
...
A Set records storedBy from the answer’s instance. The test makes six quotes with different vehicles and expects at least two different values of storedBy. The earlier resilience post measured round robin on a real gateway. This one uses output: core on a LoadBalancer in a project I have not published.
The store is wrapped in Try. If it fails, the quote is still returned:
kind: Try
spec:
execute:
- $ref: ins-motorquotes:ins-motorquotes-store-switch:1.0.0
- $ref: ins-motorquotes:ins-motorquotes-parse-store:1.0.0
- $ref: ins-motorquotes:ins-motorquotes-set-stored-by:1.0.0
catch:
- errors:
- InternalError
- ConnectionError
- TimeoutError
execute:
- $ref: ins-motorquotes:ins-motorquotes-set-stored-none:1.0.0
The catch sets storedBy to unavailable. The premium and everything else are unaffected. A quote that cannot be recorded can be recomputed later, so I would rather answer the customer. For a bound policy you would not make that choice.
To test the failure there is a hook: X-Test-Store: down makes a Switch call /fail instead of the pool. It is a test aid. Anyone who sends the header can force the fallback, and it should not exist in anything real. The test expects 200, storedBy of unavailable and a premium of 470.
The policy schedule: Handlebars
The second operation takes a JSON body and returns a plain text document:
POLICY SCHEDULE
Quote: Q-1
Policyholder: Ada Lovelace
Vehicle: AB12CDE
Cover: comprehensive
Annual premium: GBP 470
Starts: 2027-01-01
ValidateAPISpecification checks the body first. A missing holder or a premium that is not a number returns 400. Then a HandlebarsTemplate writes the response body. The template uses three braces:
kind: HandlebarsTemplate
spec:
input:
- message: request
template: "POLICY SCHEDULE\nQuote: {{{message.body.quoteId}}}\nPolicyholder: {{{message.body.holder.name}}}\nVehicle: {{{message.body.vehicle.registration}}}\nCover: {{{message.body.cover}}}\nAnnual premium: GBP {{{message.body.annualPremium}}}\nStarts: {{{message.body.startDate}}}\n"
destination:
messageBody:
message: response
Three braces switch off HTML escaping. A plain text document should show O'Brien & Sons <Ltd> as typed, not O'Brien & Sons <Ltd>. The test sends that name and expects it back unchanged. See the Handlebars post for how the policy works. Whether the gateway’s Handlebars supports triple braces is an assumption.
A Set then writes Content-Type: text/plain; charset=utf-8 on the response. The test checks the header.
Running the tests
export NANOGW_CLIENT_ID=<client-id>
export NANOGW_CLIENT_SECRET=<client-secret>
export NANOGW_DOMAIN=<gateway-ingress-domain>
./tests/ins-motorquotes.sh
41 assertions covering access, the happy path, the pricing table, every appetite boundary, the cache, the load balancer, the outage, validation and the schedule. Set NANOGW_SLOW_TESTS=1 to include the 61-second wait that proves the cache expires.
Summary
- Appetite rules and rating rules are different jobs. Do the appetite rules first, outside the cache, in an order you can explain to a customer.
- Express a rule the schema cannot hold, such as a licence history longer than the driver’s age, as Lua that writes a header and a guard that reads it.
- Put every field that changes the price in the cache key, and nothing else.
- Use
Trywhere losing a side effect is better than losing the answer. - Use triple braces in a Handlebars template for plain text.
Limitations and Notes
- Not run on a gateway. The pricing table is the output of an offline run.
- Assumptions to confirm on the first run:
- A Lua-set request header is visible to a later JSONata
If, and to a second Lua script. The rating script readsX-Driver-Agethat the first script set. LoadBalanceracceptsoutput: coreand the body can be parsed after it.Handlebarstriple braces switch off HTML escaping.Trycatches a failed invoke inside it, and theSetin the catch runs.$telemetry('client_id')works in aCachekey.
- A Lua-set request header is visible to a later JSONata
- The rating tables are invented for the demonstration. They are not an actuarial model.
- The cache is per gateway and the key has to match exactly. A change in a field that does not affect price still needs to be in the key if it can change the response.
- The date and clock are the gateway’s. A quote near midnight could be priced for the wrong age.
- The “quote store” is a call to a service that returns an instance name. It does not store anything.
