Resilient upstreams¶
How-to guideThe steps for one task.
An upstream describes not only where a backend is but how the gateway should treat it when it misbehaves. Every setting has a safe default; this page explains what to turn on and why.
Load balancing¶
| Balancer | Use when |
|---|---|
round_robin (default) |
Targets are equal |
weighted |
Targets differ in capacity (weight per target) |
least_connections |
Requests vary a lot in duration |
consistent_hash |
A caller should stick to one target (by header, cookie or client IP) |
Health¶
health:
active:
enabled: true
interval: 5s
path: /healthz
unhealthy_threshold: 3 # consecutive failures to eject
healthy_threshold: 2 # consecutive successes to re-admit
passive:
enabled: true
failures: 5 # consecutive failed requests to eject
eject_for: 30s
Active checks probe targets on a schedule, at the check path under the target's own base path
(a target https://host/api with path: /healthz is probed at https://host/api/healthz);
passive checks watch real traffic. On Apinx Cloud the plan sets the shortest interval (the Free
plan: one check every 30s or more); a shorter one is refused when the upstream is saved, with a
message naming the plan's minimum. Without an interval an upstream checks every 5s, so set it
when the plan has a minimum. Transport errors
and 502, 503, 504 count as failures; other statuses are application answers. An ejected target
takes no traffic until it recovers. With every target ejected, callers get 503 APX-UP-0001.
Where to see it: the console's Overview and an API's Overview tab show each upstream as healthy
or not and, for a target out of rotation, why (is failing its health check (GET /healthz
answered 500), is ejected after failed requests, has its circuit breaker open). A request
answered APX-UP-0001 shows the same reason in the request inspector, on the backend step,
as it was when the request arrived. The reason never reaches the caller.
Circuit breaker¶
Per target: after the threshold of consecutive failures the breaker opens and the target is
skipped for open_duration; then a probe request is allowed; success closes it. With every
breaker open, callers get 503 APX-UP-0002. Breaker state is visible on the Overview and the
gateway map.
Retries¶
retry:
attempts: 2
conditions: [connect_error, reset, "503"]
methods: [GET, HEAD, OPTIONS, TRACE, PUT, DELETE] # idempotent by default
backoff: 25ms
max_backoff: 250ms
budget_ratio: 0.2 # retries at most 20% of recent requests
max_body_bytes: 65536 # larger bodies are sent once
Retries move to another target when there is one. The budget protects a struggling backend from a retry storm; the trace shows every attempt.
Timeouts¶
| Timeout | Default | Meaning |
|---|---|---|
connect |
5 s | Establishing the connection |
tls_handshake |
5 s | |
response_header |
30 s | Waiting for the first response bytes |
total |
60 s | The whole exchange; 0s for SSE and long polls |
idle |
90 s | Idle keep-alive connections in the pool |
Callers see 504 APX-UP-0004 on a timeout and 502 APX-UP-0003 when the backend cannot be reached, with every attempt in the trace.
Connection pool¶
max_idle_conns_per_target (256) bounds the keep-alive pool per target. A pool smaller than
the number of concurrent callers closes and re-dials connections constantly (about a thousand a
second at 50 concurrent callers with the old default of 32), which costs latency and, on
Windows, exhausts ephemeral ports. Raise it for backends with high concurrency and slow
responses; watch the apinx_upstream_attempts metric.
In Apinx Cloud the plan caps the idle connections an upstream keeps per target on the shared gateway (Free: 8, Enterprise: 64); a larger number in the upstream is brought down to the cap when the configuration is published. An organization that receives no request for ten minutes is parked: its health checks stop and its idle connections close, so a quiet organization costs the gateway nothing but its configuration. The first request wakes it and is served at once (it dials the backend afresh, as the first request after a deploy does); health checks resume with the state they had, and a trace exporter of the organization's own starts again a moment later.
gRPC and HTTP/2 backends¶
A target's scheme says how the backend is reached: http:// (HTTP/1.1; HTTP/2 is not spoken
on cleartext unless asked), https:// (HTTP/2 through ALPN when the backend offers it),
grpc:// (HTTP/2 without TLS, by prior knowledge, what a gRPC server inside a network
expects) and grpcs:// (HTTP/2 over TLS, as https://). Everything on this page applies to
them alike, with one difference: active health checks on a gRPC target use the gRPC health
protocol (grpc.health.v1.Health/Check) instead of a GET, so path and expected_statuses
do not apply to it. gRPC services has the rest.
Mirror traffic to a second upstream¶
A route's mirror block copies a share of its requests to another upstream and throws the
answers away. A backend under construction, or the next version of one, sees real traffic
before it serves any; the caller never knows.
apiVersion: apinx/v1
kind: Gateway
listeners:
- name: http
address: ":8080"
upstreams:
- name: orders-v1
targets:
- url: http://orders-v1.internal:8080
- name: orders-v2
targets:
- url: http://orders-v2.internal:8080
timeouts: { total: 5s }
routes:
- name: orders
path: /orders/{rest...}
upstream: orders-v1
mirror:
upstream: orders-v2 # must exist; may even be the route's own, to double its load
percent: 10 # 1 to 100; default 100
max_body_bytes: 65536 # a request with a larger body is not copied; default 64 KiB
timeout: 2s # one copy; default: the mirror upstream's total timeout
backend_credentials: false # true sends the backend's own token with the copy (below)
In the console the operation editor has a Mirror traffic section with the same five settings; the Operations table shows Mirrored to orders-v2 (10%) on the operation.
What is copied. The request as it would reach the real backend: the method, the path after
strip_prefix, the query, the headers as the policies left them (the gateway's identity
headers included, forward's dropping applied) and the body, held in memory up to
max_body_bytes. The copy carries X-Apinx-Mirror: 1 and Via: 1.1 apinx, so the mirror
backend can tell it apart and must not treat it as a loop. The copy is made after the whole
chain let the request through, so a request a policy refused or answered (a 401, a cache hit,
a mock) is never copied, nor is a WebSocket upgrade.
The backend's token is not copied. When the route fetches a token for its backend
(upstream-auth), the copy leaves without it: the mirror is another host, and that token is the
backend's. For a mirror that is a second copy of the same backend, set
backend_credentials: true (Send the backend's token with the copy in the console).
What is not. The answer: its status is read for the metric, its body drained and dropped.
Nothing of the copy reaches the caller, not a header, not a delay, not an error. The copy runs
on its own goroutine with a detached context, so a caller that disconnects does not cancel it,
and timeout bounds it. The caller waits only for the sampling and, when there is a body, for
the body to be read into memory, which the real dispatch needed anyway.
Writes are copied too. A POST mirrored at 100% creates every record twice. Mirror
read-only routes, or point the mirror at a backend with its own test data.
Bounds. At most 64 copies per route are in flight at once; past that, a copy is dropped and counted, never queued, so a slow mirror cannot pile up memory. The mirror upstream's balancer, health state and timeouts apply to the copies as to any request it receives.
Where to see it. Prometheus counts apinx_proxy_mirrored_total{route, outcome} with
outcome ok, 5xx or error. The request inspector records the decision as a mirror step
in the dispatch phase: sent to orders-v2, sampled_out, body_too_large or dropped.
Canary: a share of the callers on the new version¶
A route's canary block serves a share of its requests from a second upstream and the rest from
its own. Unlike a mirror, the canary's answers reach the callers: a new backend version takes
real traffic a little at a time, and a tester pins themself to it with a header.
routes:
- name: orders
path: /orders/{rest...}
upstream: orders-v1
canary:
upstream: orders-v2 # must exist and differ from the route's own
percent: 10 # 1 to 100 of the requests
pin_header: X-Apinx-Canary # optional: "canary" or "stable" in it picks the side
In the console the operation editor has a Canary release section with the same three
settings (the pin header is prefilled with X-Apinx-Canary; clear it for no pinning); the
Operations table shows Canary orders-v2 (10%) on the operation.
How a side is chosen. Per request, after the whole policy chain let it through, so a request
a policy refused or answered (a 401, a cache hit, a mock) is never counted in the share. A request
whose pin header says canary goes to the canary and one that says stable to the route's own,
whatever the share; any other value, or no header, is sampled at percent. The sample is
per request, not per caller: a client that needs the same version on every call pins itself.
A WebSocket upgrade always goes to the route's own upstream.
A canary never adds an outage. When every target of the canary upstream is out of rotation
(ejected by its passive health check, failed its active one, or behind an open circuit breaker),
the stable side serves the whole route and the trace says stable (unavailable). A canary target
that fails is ejected by the canary upstream's own health rules, as any target is; the first
failures reach the callers that were sampled to it, so give the canary upstream a passive health
check with a low failures count while it is new.
Where to see it. The request inspector, the access log's upstream field and the
OpenTelemetry span's apinx.upstream all name the upstream that answered; the trace records the
decision as a canary step in the dispatch phase: canary (sampled), canary (pinned),
stable (sampled), stable (pinned) or stable (unavailable). A canary answer carries
X-Apinx-Canary: 1, so a pinned tester can tell. Prometheus counts
apinx_proxy_canary_total{route, side, reason}, and apinx_upstream_attempts_total{upstream}
counts the attempts under each of the two upstreams' names.
In Apinx Cloud the canary is an Enterprise feature: a Free organization's deploy with a
canary is refused with APX-SAAS-0066 (the mirror is in every plan). An organization moved to
a smaller plan keeps the canaries its routes already run.
Moving to a new backend¶
- Add the new upstream with health checks and a total timeout; deploy. It takes no traffic yet.
- Set
mirror: { upstream: orders-v2, percent: 10 }on the route; deploy. Watchapinx_proxy_mirrored_total{outcome!="ok"}and the new backend's own logs for a day. - Raise
percentto100; the new backend now carries the full load while the old one still answers every caller. Compare latency and errors on both. - Replace the mirror with
canary: { upstream: orders-v2, percent: 5, pin_header: X-Apinx-Canary }; deploy. Pin yourself withX-Apinx-Canary: canaryand test; watch the canary's share ofapinx_proxy_requests_totaland the errors by status in the console. Raisepercentin steps. - Switch
upstream: orders-v2, removecanary; deploy. Rolling back is rolling the deployment back, as for any change.