Skip to content

High availability

How-to guideThe steps for one task.

One instance of Apinx is the default and the simplest thing to run: one binary, one SQLite file, nothing else. It survives a restart in a few seconds and a store outage without dropping traffic. When a few seconds is too long, or one server is not enough, run several instances of the same binary over one PostgreSQL database, behind your load balancer. This page is how.

Two modes

cluster.mode: single (default) cluster.mode: ha
Instances One Two or more, identical configuration
Store SQLite file or PostgreSQL PostgreSQL, shared by every instance
Master key Any, a generated key file included The same configured key on every instance; a generated key is refused
Configuration changes Applied in the process that made them Made on any instance, applied by every instance within cluster.watch_interval (2 s)
Consumers and keys In memory, reloaded on change Reloaded on every instance when any instance changes them
Data key rotation (Admin → Encryption keys) In the process that made it Made on any instance; every instance seals under the new key from its next save, and the old key is kept for a day
Sign-in through an identity provider In memory In the database, so the callback may land on any instance
Background jobs (analytics roll-ups, retention, session sweep) This instance One instance at a time, elected through the database
Rate limits, plan quotas, concurrency limits Per instance (or shared through Redis, if you want them to survive a restart); a deploy keeps the counts of an unchanged binding Shared through Redis (redis.address): one count for the whole installation. Per instance without it
Response cache, backend tokens, JWKS, verified JWTs, breaker and health state Per instance Per instance, on purpose
Access log, request inspector This instance's file or stdout; this instance's memory Each instance's own; ship the logs to one place (below), and read traces on the instance that served
WebSocket sessions cap (Apinx Cloud plans) This instance Shared through Redis, as the concurrency limit; per instance without Redis
Something else to run Nothing A load balancer, PostgreSQL, and Redis for the shared counters

Nothing in the gateway's request path changes between the modes: a request never waits on the database or on another instance.

What it looks like

                 ┌──────────── load balancer ─────────────┐
console users ──►│ console.example.com  ──► :9000 on A, B │
API callers   ──►│ api.example.com      ──► :8080 on A, B │   health: GET /readyz
                 └────────────────┬───────────────────────┘
                     ┌────────────┴────────────┐
              ┌──────┴──────┐           ┌──────┴──────┐
              │ apinx  A  │           │ apinx  B  │   same binary, same configuration,
              │ node: gw-a  │           │ node: gw-b  │   same master key
              └──────┬──────┘           └──────┬──────┘
                     └────────────┬────────────┘
              ┌───────────────┴───────────────┐
      ┌───────┴────────┐              ┌───────┴────────┐
      │  PostgreSQL    │              │  Redis         │   rate-limit and quota counters
      │  configuration │              │  counters      │   every instance shares
      └────────────────┘              └────────────────┘

Every instance writes to the database and every instance watches it; nothing is pushed between instances. Counters are the exception: a rate limit or a plan quota that must be exact for the whole installation is one number in Redis, moved by one atomic script per counted request. A deployment made in the console on A is a row in the database; B sees the new published sequence on its next look and applies that revision to its own data plane, exactly as A did. A key revoked on B disappears from A's memory the same way. The watcher costs one or two single-row queries per interval per instance.

Setting it up

The Linux deployment stands; repeat steps 1 to 4 and 6 on each server, with these differences.

1. One database for everyone. PostgreSQL on its own host (or a managed service), reachable from every instance, with sslmode=require:

APINX_STORAGE_DRIVER=postgres
APINX_STORAGE_DSN=postgres://apinx:<password>@db.internal:5432/apinx?sslmode=require

2. The same master key everywhere. Secrets at rest are encrypted with it; an instance with a different key cannot read what another one saved, and a generated key would be different on every server. Put the one key in each server's apinx.env (or point every instance at the same Vault Transit key or KMS command). In ha mode an instance without a configured key refuses to start, and says why.

3. The mode, and a name for each instance:

cluster:
  mode: ha
  node: gw-a              # gw-b on the second server; empty uses the host name
  watch_interval: 2s      # how fast a change on another instance is applied here

or APINX_CLUSTER_MODE=ha and APINX_CLUSTER_NODE=gw-a in apinx.env. The node name appears on every trace in Traffic, so you can tell which instance served a request.

4. Redis for the shared counters. A Redis 6 or later server every instance can reach:

redis:
  address: redis.internal:6379
  # password: set APINX_REDIS_PASSWORD in apinx.env
  # tls: true
  # timeout: 200ms

With it, every rate-limit and concurrency-limit policy and every plan's rate limit and quota count across all instances: a limit of 100 per minute is 100 per minute for the installation, and 50 requests in flight are 50 across every instance, whichever one answers. Each counted request costs one round trip to Redis, one atomic script, well under a millisecond on a LAN. A limit that must stay local, for speed or by design, sets shared: false on the policy. Without redis.address, limits count per instance, as before.

A concurrency slot held by an instance that dies mid-request frees itself after two minutes. Redis needs no persistence for this: counters are short-lived, and a plan quota that Redis lost (a restart without persistence) resumes from the highest count any instance knows, which every instance also snapshots to PostgreSQL every ten seconds.

One Redis is enough. For a Redis that survives its own host, name the Sentinels and the master they watch, or the nodes of a Redis Cluster:

redis:
  addresses: [sentinel-a:26379, sentinel-b:26379, sentinel-c:26379]
  master_name: apinx          # Sentinel
# or
redis:
  addresses: [redis-1:6379, redis-2:6379, redis-3:6379]   # Cluster

Every key of one counter operation carries a hash tag, so Cluster slots never split a script.

5. The load balancer. Two pools, one for the console (:9000) and one for the proxy listeners, each instance in both. Health check GET /readyz on the console port: it answers 200 when the instance serves and 503 while it starts or when its store is unreachable. Session cookies carry no instance affinity; any instance answers any console request.

6. Start the first instance, then the others. The first one creates the tables; the others wait for it (migrations run under a database lock). On a fresh installation every instance prints the same claim token, and the set-up page works on whichever one the load balancer picks.

Day to day

  • Deploying. Deploy in the console as before. The Deployments page shows the revision; each instance applies it within the watch interval and logs applied a revision deployed on another instance. A revision that fails to apply on one instance leaves that instance on its previous revision, logs the error, and tries again next interval. Two people deploying at the same moment through two instances: the first deploy stands and the second is answered 409 APX-CP-0029, nothing of it deployed; deploying again puts it on top of the first.
  • Revoking. A key, a secret or a token session revoked on one instance is refused on the others within the watch interval. An instance whose reload failed (the database did not answer) reloads at its next look, until it succeeds.
  • Watching the cluster. The Overview's Components card lists every instance with its version, the revision it runs, which one leads the background jobs and its last heartbeat (every ten seconds). An instance that missed three heartbeats shows stale; one on an older revision than the published one shows behind until its next watch; one silent for an hour is forgotten, and a clean stop removes it at once. A stale instance also raises a warning banner on every console page, so nobody has to be on the Overview to notice. The same card shows the store, analytics, the gateway, secrets at rest, the sign-in provider and, for now, that shared counters are not configured.
  • Upgrading. Drain one instance at the load balancer, stop it, replace the binary, start it, let /readyz turn green, move to the next. Schema migrations are forward-only; the first upgraded instance migrates and the older ones keep serving their revision until they are upgraded too. Take the backup first, as in Upgrading.
  • Losing an instance. The load balancer stops sending to it; the others carry the traffic. If it held the background jobs, another instance takes them over at its next tick (within ten minutes for the session sweep, five for analytics maintenance). Nothing in flight is lost but that instance's own requests.
  • Losing Redis. Traffic continues. The instance that failed a counter operation counts on its own for two seconds, then tries Redis again; while it does, a caller may get up to one limit per instance, and quotas continue from the last shared count. The trace of each request says "counted on this instance" when that happens, the log says it once, and the Components card shows the Redis row down. When Redis is back, counts converge within a window.
  • Losing the database. Traffic continues on every instance: the request path never touches the database. Deployments, consumer changes and console pages that read or write fail with a clear error until it is back; the watcher logs cluster sync failed; retrying next interval. Fail over to your standby as you would for any application; no instance needs a restart.
  • Analytics. Every instance flushes its own counts into the same tables; the merge is serialised in the database so no instance overwrites another's. The dashboards show the whole installation.

What stays per instance

The response cache is per instance; a purge (Purge cache on the API page) clears the instance that received it at once and every other instance on its next watch, within cluster.watch_interval. Backend tokens (upstream-auth) are fetched once per instance.

The request inspector is the memory of the instance that served a request. With inspector.shared: true every captured request is also kept in the Redis the counters use (for the inspector's capacity and retention), and the Traffic screen and Try it find a request whichever instance served it, each trace still naming its node; without it, a console behind a load balancer shows the traces of the instance that answers it, and session affinity at the load balancer helps. The plan's cap on open WebSocket sessions (Apinx Cloud) is shared through Redis like the concurrency limit, with a slot that frees itself ten minutes after an instance dies; without Redis it counts per instance.

Logs across instances

Each instance writes its own access log; a shared disk is the wrong tool for it. Every line carries node, the instance's name, so lines are told apart once collected. Two ways to collect them:

  • Let the gateway send them. Set the same access_log.sink on every instance: http to Seq, Grafana Loki, Elasticsearch or OpenSearch, tcp to Vector, Fluent Bit or Logstash, or syslog. Nothing to install beside the gateway, and a slow or absent collector never delays a request: lines wait in a bounded queue and the counters on Admin › Observability say what was delivered, dropped or given up. The examples are in Observability.
  • Ship them yourself. Keep access_log.sink: stdout, let journald hold the lines, and run a log shipper on each server (Vector, Promtail or Fluent Bit) that sends journald to one place. A shipper tails files as well, so the file sink with its rotation works too.

Nothing on disk needs moving when a server is added: the access log is a rolling window, and the old files age out.

Checklist

  • [ ] storage.driver: postgres, same DSN on every instance, sslmode=require
  • [ ] The same APINX_SECURITY_MASTER_KEY on every instance, kept with your production secrets
  • [ ] cluster.mode: ha and a distinct cluster.node per instance
  • [ ] inspector.shared: true on every instance, so a trace is found wherever it was served
  • [ ] redis.address on every instance, the same server, for shared rate limits and quotas
  • [ ] Load balancer health check on GET /readyz, both the console and the proxy pools
  • [ ] Deploy on one instance, confirm the others log the applied revision
  • [ ] Without Redis: limits sized for the number of instances, or callers pinned at the load balancer