A price feed is expensive, slow to recover and easy to overload. A good gateway in front of it charges heavy requests more, serves repeats from memory, stops calling a feed that is failing and falls back to a second one. This post builds fin-marketdata, a market data API that does all four on the Nano Gateway, with a small FX conversion operation alongside.

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 lint passes.
  • The Lua conversion script runs under Lua 5.5 and LuaJIT in a test harness.
  • The JSONata expressions pass a subset check, and the guards have unit tests (42 assertions for this API).
  • tests/fin-marketdata.sh passes a bash syntax check and a stub-server smoke run.

The assumptions are listed at the end.

The API

Operation Purpose
GET /prices/{symbol}?depth=top\|full A price snapshot. full depth is heavier.
POST /fx/convert Converts an amount between GBP, EUR, USD and JPY.

CORS allows one origin, https://dashboard.example.test, and denies the rest with a catch-all deny rule. The open banking post has the same shape and explains the limits of CORS.

Validate, then guard

ValidateAPISpecification with query: true checks that depth is top or full. A bad value returns 400.

kind: ValidateAPISpecification
spec:
  input: request
  validate:
    request:
      query: true

The symbol is a path parameter, and a guard checks it is one to five upper-case characters:

condition: $length($pathParameter('symbol')) > 5 or $uppercase($pathParameter('symbol')) != $pathParameter('symbol')

This guard uses !=. In the payments post I argued against it for headers. A path parameter is always present once the operation has matched, so there is nothing missing to compare. The test sends a lower-case symbol, a six character symbol and a mixed-case one, and expects 400 for each with symbol must be 1 to 5 upper-case characters.

Charge heavy requests more

A Switch sets a request header from the query. depth=full costs 5, anything else costs 1:

kind: Switch
spec:
  cases:
    - condition: $queryParameter('request', 'depth') = 'full'
      execute:
        - $ref: fin-marketdata:fin-marketdata-set-weight-full:1.0.0
  otherwise:
    - $ref: fin-marketdata:fin-marketdata-set-weight-top:1.0.0
---
kind: Set
spec:
  messageHeader:
    messageName: request
    action: set
    headerName: X-Request-Weight
    value: "5"

The value is a quoted string. A numeric-looking value in a header Set must be quoted, or apic lint complains. The action is set, so a client who sends its own X-Request-Weight: 0 is overwritten.

The rate limit uses the weight:

kind: RateLimitDef
spec:
  max: 5
  intervalLen: 1
  intervalUnit: minute
  extensions:
    dp-nano-gateway:
      apiVersion: api.ibm.com/v1
      spec:
        weightExpr: $number($header('request', 'X-Request-Weight'))
        dynamicValue: $telemetry('client_id') & '|' & $pathParameter('symbol')

Five units a minute per client and symbol. A full-depth call uses all five. This is the same weightExpr mechanism as in the rate limit post, where X-Weight was a header the test set. Here the gateway sets it.

A five second cache around the limit

The RateLimit is the first policy inside the cache:

kind: Cache
spec:
  inputs:
    - custom:
        expression: $telemetry('client_id') & '|' & $pathParameter('symbol') & '|' & $header('request', 'X-Request-Weight')
  outputs:
    - messageBody:
        name: response
  expire:
    static:
      seconds: 5
  execute:
    - $ref: fin-marketdata:fin-marketdata-feed-allowance:1.0.0
    - $ref: fin-marketdata:fin-marketdata-feed-try:1.0.0
    - $ref: fin-marketdata:fin-marketdata-price-response:1.0.0

The weight is in the key, so a top answer and a full answer are cached separately. A hit skips the list, so it spends nothing from the allowance. The traffic post measured that a hit skips the execute list.

The test depends on that. One full-depth call takes the whole allowance. Five repeats of the same call all return 200, because they are cache hits. A depth=top call for the same symbol is a different cache key, so it misses, tries to spend one unit and gets 429 with the plain Too Many Requests text. Another symbol has its own allowance and returns 200.

That means the limit protects the feed, not the client. A client can ask for the same snapshot as often as it likes for five seconds. This is deliberate.

Failover with a circuit breaker

The primary feed sits behind a circuit breaker. The secondary sits behind it in an Or. A Try around both turns a total failure into one message:

kind: Or
spec:
  options:
    - - $ref: fin-marketdata:fin-marketdata-primary-breaker:1.0.0
      - $ref: fin-marketdata:fin-marketdata-set-feed-primary:1.0.0
    - - $ref: fin-marketdata:fin-marketdata-secondary-switch:1.0.0
      - $ref: fin-marketdata:fin-marketdata-set-feed-secondary:1.0.0
---
kind: EnforceCircuitBreaker
spec:
  preventHalfOpen: true
  recoveryDuration: 10
  breakConditions:
    reportedFailures:
      failureCount: 3
      failureDuration: 30
  execute:
    - $ref: fin-marketdata:fin-marketdata-primary-switch:1.0.0
  fallbackExecute:
    - $ref: fin-marketdata:fin-marketdata-throw-circuit-open:1.0.0
---
kind: Try
spec:
  execute:
    - $ref: fin-marketdata:fin-marketdata-feed-failover:1.0.0
  catch:
    - errors:
        - InternalError
        - ConnectionError
        - TimeoutError
        - CustomError
      execute:
        - $ref: fin-marketdata:fin-marketdata-throw-feeds-down:1.0.0

Or tries each option in turn and stops at the first that works. The primary option is a breaker call followed by a Set that records feed as primary. If the primary fails, Or moves to the second option. If both fail, the Try returns 503 market data unavailable.

Three failures in 30 seconds open the breaker. While it is open, the breaker runs fallbackExecute, which throws a custom 503 primary feed circuit is open. The Or treats that as a failure of the first option and moves on to the secondary. The primary is not called at all.

The resilience post measured the breaker opening after three failures and the fallback body being returned. It did not put the breaker inside an Or. The Or moving on after a Throw is the main assumption of this API.

The test uses a header, X-Test-Feed, to simulate failures. Each value picks a different invoke:

Call Header Expected
1 both-down 503 market data unavailable (a primary failure is counted)
2 primary-down 200 from the secondary (second failure)
3 primary-down 200 from the secondary (third failure, the breaker opens)
4 none 200 from the secondary, without trying the primary
5 none, after waiting 200 from the primary again

Every call uses a new symbol, so the cache never answers. Call 5 is the slow one. recoveryDuration is 10 seconds, but the resilience post saw the backend called again 20 to 32 seconds after the breaker opened. So the test script polls for up to 45 seconds instead of sleeping for 12. It only runs with NANOGW_SLOW_TESTS=1.

The X-Test-Feed header is a test aid, as in the other samples. Anyone who sends it chooses which feed breaks. Delete it before real use. Because the breaker count is shared, the test also opens the breaker for every other user of the gateway, so run it on a test gateway and wait a minute between runs.

FX conversion in Lua

POST /fx/convert is a POST, and not a GET with a query string, because I did not verify that Lua can read a query string. The body carries from, to and amount.

A Lua script holds the rate table, as units per US dollar, and converts through the dollar:

local PER_USD = { USD = 1, GBP = 0.79, EUR = 0.92, JPY = 150 }

local from, to = PER_USD[tostring(body.from)], PER_USD[tostring(body.to)]
local amount = tonumber(body.amount)

if from and to and amount then
  local rate = to / from
  local converted = math.floor(amount * rate * 100 + 0.5) / 100
  req.headers:set('X-Fx-Supported', 'true')
  req.headers:set('X-Fx-Rate', string.format('%.6f', rate))
  req.headers:set('X-Fx-Converted', string.format('%.2f', converted))
else
  req.headers:set('X-Fx-Supported', 'false')
  ...
end

JSONata has no table lookup, and the rounding needs arithmetic I would rather not trust to a subset. A guard returns 422 unsupported currency when X-Fx-Supported is not true. The response is a Set that reads the headers.

The test asserts values the Lua gives offline:

Request Result
100 GBP to EUR rate 1.164557, converted 116.46
100 USD to JPY 15000
100 JPY to USD 0.67
10 EUR to GBP 8.59
12.34 GBP to GBP 12.34

An unsupported target or source currency returns 422. A forged X-Fx-Converted: 999 header is ignored, because the script overwrites it. The rate table is fixed and invented. A real service would load rates from somewhere.

The conversion is wrapped in a 30-second cache keyed on client, both currencies and the amount. The guard sits inside the cache. An unsupported conversion fails with 422 and is not cached, because the error ends the request before the cache stores anything. I have not verified that a Throw inside a cache leaves no entry.

Running the tests

export NANOGW_CLIENT_ID=<client-id>
export NANOGW_CLIENT_SECRET=<client-secret>
export NANOGW_DOMAIN=<gateway-ingress-domain>
./tests/fin-marketdata.sh

48 assertions. The failover section opens a breaker. Wait a minute before running it a second time.

Summary

  • Let the request say what it costs. A Switch that sets a weight header turns a rate limit into a budget.
  • Put the rate limit inside the cache. Repeats are free, and the limit protects the thing that is expensive.
  • Put the breaker inside an Or, so an open circuit means “use the other feed” and not an error.
  • Treat recovery time as a minimum. Poll with a deadline.
  • Use Lua for tables and money rounding.

Limitations and Notes

  • Not run on a gateway. The checks above are offline.
  • Assumptions to confirm on the first run:
    • A Throw in a breaker’s fallbackExecute makes Or move to the next option.
    • Try with CustomError in its catch list catches a Throw.
    • $telemetry('client_id') works in a Cache key and in dynamicValue.
    • ValidateAPISpecification with query: true enforces the depth enum.
    • A header set by Lua is visible to a later JSONata If and Set.
    • A catch-all deny CORS rule stops unlisted origins getting CORS headers.
  • The breaker state is per gateway. I did not test more than one replica.
  • The rate table is invented. Rounding is half up to two places, on doubles.
  • X-Test-Feed is a test hook.
  • The feeds are the echo service. They prove which feed the gateway called, not that a price is right.