Load balancing, retry and circuit breaking in API Studio for the DataPower Nano Gateway: worked examples
Draft!!
Three policies handle a backend that misbehaves: LoadBalancer spreads the load, Retry hides a transient failure and EnforceCircuitBreaker stops calling a backend that is down. This post runs each against a real gateway, with the YAML from API Studio code view and the response that came back.
The companion post on control flow covers Or and Try, which handle a failure inside one request. These three policies deal with failures across requests.
The test project
One API Studio project, one API called nano-resilience, one operation per example. The backend is two small pods, echo and echo2. Each answers {"instance": "<pod>"} on /instance. /fail always returns 500. /flaky returns 500 on the first call for a given key, then 200.
ExtractIdentity, Authenticate and Authorize check client credentials, then an OperationSwitch sends each operation to its own policies.
Every call goes to the published product URL with the client credentials of a subscribed application:
curl -s \
-H "X-IBM-Client-Id: <client-id>" \
-H "X-IBM-Client-Secret: <client-secret>" \
"https://<product>-<catalog>-<org>.nanogw.<ingress-domain>/1.0.0/nano-resilience/lb/round-robin"
Order matters when you combine them. A Retry outside a circuit breaker pays the retry cost on every request, even while the circuit is open. A circuit breaker outside a Retry breaks on the first failure and never retries. Decide which one owns the retry budget.
Example 1: round robin
LoadBalancer is an invoke with a pool instead of a URL. Each endpoint is a full invoke target, plus its own suspendTimeout:
kind: LoadBalancer
spec:
input: request
output: response
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
urlType: plain
version: HTTP/1.1
timeout: 10
persistentConnections: true
suspendTimeout: 60
Four calls in a row:
{"instance": "echo-2"}
{"instance": "echo-1"}
{"instance": "echo-2"}
{"instance": "echo-1"}
The calls alternate. The first one landed on echo-2 because earlier traffic had already moved the rotation on. Round robin is strictly sequential. It does not look at how busy or healthy an endpoint is. One call cannot tell a load balancer from an invoke, so test with at least four.
suspendTimeout takes an endpoint out of rotation for that many seconds after a failure. The failure itself still reaches the caller. The load balancer does not try the next endpoint within the same request, which is what separates it from Or. I did not trigger a suspension for this post.
statusException is set on roundRobinHttp, not on the policy. Without it, a 500 from a member is just a response and nothing counts as a failure.
Example 2: weighted random
weightedRandomHttp is the same pool with a weight on each endpoint and a random choice:
kind: LoadBalancer
spec:
input: request
output: response
weightedRandomHttp:
verb: GET
endpoints:
- endpoint:
url: http://echo.pi-sample.svc.cluster.local/instance
urlType: plain
version: HTTP/1.1
timeout: 10
suspendTimeout: 60
weight: 9
- endpoint:
url: http://echo2.pi-sample.svc.cluster.local/instance
urlType: plain
version: HTTP/1.1
timeout: 10
suspendTimeout: 60
weight: 1
Weights are relative, so 9 and 1 behave like 90 and 10. Twenty calls:
| Instance | Calls |
|---|---|
echo-1 |
16 |
echo-2 |
4 |
I expected about 18 and 2. A single call proves nothing, and twenty is a small sample, so I would not read this as a fault. The point is that both members were used and the heavy one won.
Use weighted random for a canary, with 99 on the stable endpoint and 1 on the new one. Use it too when the pool members are different sizes. Use round robin when the members are interchangeable and you want a sequence you can reproduce.
Example 3: retry hides a transient failure
Retry runs its execute block. If it raises one of the retryOn errors, Retry waits delay milliseconds and tries again, up to maxRetries times:
kind: Retry
spec:
delay: 300
maxRetries: 2
retryOn:
- InternalError
execute:
- $ref: nanogw-policy-samples:nano-resilience-invoke-flaky:1.0.0
The invoke inside needs statusException, or a 500 is only a response and Retry has nothing to catch:
kind: Invoke
spec:
endpoint:
http:
statusException:
- pattern: '500'
target:
url: "'http://echo.pi-sample.svc.cluster.local/flaky?fail=1&key=' & $queryParameter('request', 'key')"
urlType: jsonata
timeout: 10
version: HTTP/1.1
verb: GET
The backend fails the first call for a given key. A fresh key each time makes the demo repeatable:
curl ... "https://<gateway-host>/1.0.0/nano-resilience/retry/flaky?key=test1"
HTTP/2 200
content-type: application/json
{"instance": "echo-1", "call": 2, "outcome": "success"}
"call": 2 is the proof. The first attempt got a 500, the runtime retried and the second attempt got a 200. The caller never saw the failure. The call took 0.5 seconds. Calling the same key again gives "call": 3, because the backend counts every request.
retryOn takes error types, not status codes. The reference lists a long set, including ConnectionError, TimeoutError, InternalError, CustomError, ValidateError and LuaScriptError. Retry on ConnectionError, TimeoutError and InternalError. The others are deterministic. A second attempt will fail the same way and cost you delay for nothing.
There is no backoff. delay is a fixed sleep. With maxRetries: 2 and delay: 300, the worst case adds 600 ms. In a synchronous API, keep both numbers small.
Example 4: retry gives up
The same policy against a backend that always fails:
kind: Retry
spec:
delay: 300
maxRetries: 2
retryOn:
- InternalError
- ConnectionError
execute:
- $ref: nanogw-policy-samples:nano-resilience-invoke-fail:1.0.0
HTTP/2 500
Internal Server Error
This took about 1.2 seconds. maxRetries: 2 means three attempts: the first try plus two retries. After the last one the runtime re-raises the error. The caller gets the gateway’s generic 500, with no retry count and no sign of the backend’s own body.
Two things to design around:
- The
500is not the backend’s. A client that looks for the backend’s error payload will not find it. Wrapping the invoke in aTryto keep it turns the failure into a handled one, and thenRetrystops retrying. - Latency multiplies. Three attempts with a 10 second timeout, plus two 300 ms delays, is a 30.6 second request.
Retry does not turn a dead backend into a live one. For a persistent failure use the circuit breaker.
Example 5: circuit breaker
EnforceCircuitBreaker counts failures of its execute block. When the count crosses a threshold inside a window, it stops running that block and runs fallbackExecute instead:
kind: EnforceCircuitBreaker
spec:
preventHalfOpen: true
recoveryDuration: 10
breakConditions:
reportedFailures:
failureCount: 3
failureDuration: 30
execute:
- $ref: nanogw-policy-samples:nano-resilience-invoke-fail:1.0.0
fallbackExecute:
- $ref: nanogw-policy-samples:nano-resilience-throw-circuit-open:1.0.0
The invoke is the /fail one with statusException for 500. Without that, a 500 is not a failure and the circuit never opens. The fallback throws a 503 from the gateway, so it needs no backend:
kind: Throw
spec:
error:
CustomError:
message: 'circuit open: backend reported 3 failures in 30s'
messageType: plain
status: 503
Five calls in a row:
| Call | Status | Body |
|---|---|---|
| 1 | 500 | Internal Server Error |
| 2 | 500 | Internal Server Error |
| 3 | 500 | Internal Server Error |
| 4 | 503 | circuit open: backend reported 3 failures in 30s |
| 5 | 503 | circuit open: backend reported 3 failures in 30s |
Three failures opened the circuit. From call 4 the backend was not called.
I waited 40 seconds and called again. The circuit had closed, so the call reached the backend and failed with a 500. Three more calls over the next 7 seconds all returned 500.
recoveryDuration: 10 is a minimum, not a deadline. In my earlier testing of this project the backend was called again 20 to 32 seconds after opening, not 10. I did not re-measure that for this post. Poll with a deadline instead of sleeping.
There are three breakConditions variants: reportedFailures, concurrency and reportedFailuresAndConcurrency. I used the first. With preventHalfOpen: false, the reference says some requests are let through for half of recoveryDuration to test the backend. I used true, so no live traffic probes the backend.
The fallback should be cheaper than the call it replaces and must not depend on the broken backend. A fallback that calls the sick backend keeps hammering it.
Summary
- Use round robin for interchangeable members and weighted random for a canary.
statusExceptionon the invoke is what makes a500a failure. Without it,Retryand the circuit breaker never fire.- Retry on connection, timeout and internal errors only, and keep
delay × maxRetriessmall. - Use
Retryfor a transient failure and the circuit breaker for a persistent one. Do not stack them without deciding which one owns the retries.
Limitations and Notes
- Tested on a DataPower Nano Gateway with the API Connect 12.1 documentation set. Check the version you run.
- The load balancer and circuit breaker keep their state in the gateway datastore. My earlier project notes say a local runtime cannot demonstrate them. I tested on the cluster.
- The breaker and balancer state is per gateway. I did not test more than one replica, so I cannot say whether a rotation is shared.
- Not tested:
suspendTimeoutafter a real endpoint failure,statusExceptionon a load balancer, theconcurrencybreak condition, half-open behaviour withpreventHalfOpen: false, andretryOnwith error types other thanInternalErrorandConnectionError. - The retry timings are single measurements from my lab cluster.
