NovaGateCase study · API gateway

A hybrid API gateway where live traffic never leaves your servers

Self-hosted data plane, SaaS control plane, one outbound WebSocket between them. If the control plane goes down, the gateway keeps serving from its last good config.

By · Updated

Product
NovaGate
Role
Designed and built end to end
Timeline
May 2026 – present
Stack
  • TypeScript
  • NestJS
  • Node.js
  • Redis
  • PostgreSQL
  • Next.js
  • Prometheus
  • Docker
  • Nx
  • Go
NovaGate's tenant dashboard for the demo workspace “Acme Logistics”: gateway online, requests per second, error rate and active routes, with detected traffic anomalies below.
The tenant dashboard, from a local demo with fake data.
01

Overview

NovaGate is an API gateway I designed and built end to end. The gateway runs on the customer's own server and proxies their traffic straight to their services; a hosted control plane handles configuration, the dashboard and telemetry. The two halves talk over one WebSocket that the gateway opens outbound, so the customer doesn't open any extra inbound port.

It's about 83,000 lines of source and 38,000 lines of tests across five apps, two shared libraries and two Go integrations: a Terraform provider and a Kubernetes controller. The 1,808 automated tests include integration suites against real PostgreSQL and Redis.

  • 0.76 ms

    median gateway overhead at 500 req/s (keep-alive clients)

  • 0

    errors across 180,000 measured requests

  • 1,808

    automated tests across the TypeScript projects

  • 13

    built-in plugins

  • 19

    Prometheus metrics

  • 83k

    lines of source, plus 38k lines of tests

Clients call the NovaGate gateway (data plane) on the customer's VPS, which proxies directly to upstream services and keeps state in a local Redis. The gateway opens one outbound WebSocket to the NovaGate SaaS control plane for configuration and telemetry.
Architecture: live traffic stays on the customer's server; config and telemetry cross one outbound WebSocket.Open full size (SVG, new tab)
02

The problem

A hosted gateway sends every request through the vendor's servers: one more network hop, and a third party sitting in the path of your traffic. A self-hosted gateway keeps the traffic local, but then you run the admin side, the config store and the dashboards yourself.

I wanted the split in between. Requests never pass through the SaaS; only configuration and batched telemetry cross to it. That raises two requirements a fully hosted product doesn't have: the gateway has to keep working when the SaaS is unreachable, and configuration changes made in a browser have to reach a server the SaaS can't connect to.

03

Design

  • Data plane (apps/api): a NestJS service shipped as a Docker image. It has no database. It holds the tenant's routes, services and consumers in memory and keeps its working state (rate-limit windows, usage meters, the cached config) in a Redis on the same machine.
  • Control link: the gateway authenticates with an API key over an outbound wss:// connection, receives its config in auth_ok, then gets config.update pushes and answers each with config.ack. Logs, metrics, health and errors travel back up the same socket in batches.
  • Control plane: a WebSocket server that validates gateway keys and fans out updates; a REST admin API behind the Next.js dashboard that writes to a PostgreSQL schema per tenant and publishes each change on Redis pub/sub.
  • Request path: JWT identity → Redis rate limit → route match → the route's plugin chain → quota, circuit breaker and load-balancer lease → upstream over HTTP/1.1, HTTP/2, WebSocket or gRPC. Prometheus metrics are recorded when the response finishes, labelled by route pattern so the label set stays bounded.
Each proxied HTTP request passes JWT authentication, a Redis sliding-window rate limit, route matching, the route's plugin chain and the proxy stage, while the logging middleware measures the whole request and records Prometheus metrics when the response finishes.
Request pipeline, in code order, with what each stage answers when it refuses a request.Open full size (SVG, new tab)
  • Grafana over the gateway's own Prometheus metrics, from a local demo with fake traffic. Its latencies come from that laptop demo and aren't a performance claim; see Performance.
04

Three hard problems

1. Control-plane outage fallback

The gateway can't depend on the SaaS being up.

How it works

Every config it installs is also written to its local Redis as cfg:default with a 7-day expiry, and on startup it loads that copy before it tries the WebSocket. A gateway that restarts in the middle of an outage comes back with its last good routes and keeps serving while it reconnects in the background.

Reconnection backs off from 1 s to 30 s and can rotate through several control-plane regions. Up to 10,000 telemetry messages wait in a buffer until the link returns. Authentication failures (close codes 4001, 4003 and 4004) stop the retries for good instead of hammering the server. On the SaaS side, updates for an offline gateway are stored and delivered when it reconnects. The gateway installs configs one at a time and ignores any version older than the one it runs, so a late redelivery can't roll it back.

Simplified sketch, not the production codeTypeScript
// Every installed config is also kept locally
await redis.set("cfg:default", json, "EX", 7 * 86400);

// On startup, before the WebSocket connects
const cached = await redis.get("cfg:default");
if (cached) install(JSON.parse(cached), "cache");
connect(); // retry after 1, 2, 4, 8, 16, then 30 s

2. Pluggable auth

Different routes need different proof: user tokens from an identity provider, signed webhooks from a partner, client certificates from internal services.

How it works

Global middleware does only one thing: it reads a Bearer JWT if there is one, and tells an expired token (401 TOKEN_EXPIRED, so clients know to refresh) apart from an invalid one (401 TOKEN_INVALID). Everything else is an ordered list of plugins on the route, and any plugin can answer the request and stop the chain:

  • OIDC: validates JWTs against the provider's JWKS, caches the keys and refreshes them when an unknown key ID shows up, with a cooldown.
  • OAuth2: token introspection cached in Redis, or a client-credentials token injected on calls to the upstream.
  • HMAC: SHA-256/512 signatures including Stripe's format, several secrets at once for rotation, constant-time comparison.
  • mTLS: reads the client certificate chain from the TLS socket and verifies it against the tenant's CA.
  • ACL on consumer groups, and Basic auth.

The same interface runs CORS, IP rules, body-size limits, header transforms and GraphQL depth and complexity limits, 13 built-in plugins in all. Third-party npm plugins run behind per-hook deadlines and are quarantined after repeated failures, and WebAssembly plugins run in a sandbox.

Simplified sketch, not the production codeTypeScript
// The route's plugins run in order;
// any of them can answer and stop the chain
for (const plugin of route.plugins) {
  const res = await plugin.onRequest(ctx);
  if (res) return res; // e.g. 401, 403, 413, 429
}
return proxy(ctx);

3. Sliding-window rate limits

A fixed-window counter lets a client send twice its limit by bunching requests on both sides of a window boundary.

How it works

NovaGate keeps a Redis sorted set per client instead. For every request, one pipeline drops entries older than the window, adds the request, counts the set, reads the oldest entry to compute Retry-After, and refreshes the expiry.

Rejected requests are added too, so a client that keeps retrying stays limited until it backs off. Signed-in users are keyed by user and IP, anonymous callers by IP, with separate limits, and a route can add its own tighter window through the rate-limit plugin. If Redis fails, the limiter lets the request through and counts the failure in gateway_rate_limit_redis_errors_total; an outage of the cache shouldn't take the API down with it. The cost is memory: the set holds one entry per request in the window, where a counter holds one number.

Simplified sketch, not the production codeTypeScript
// One Redis pipeline per check, key rl:<client>
redis.pipeline()
  .zremrangebyscore(key, 0, now - windowMs)
  .zadd(key, now, requestId) // even if rejected
  .zcard(key)                // requests in window
  .zrange(key, 0, 0, "WITHSCORES") // Retry-After
  .expire(key, windowSec)
  .exec();
// over the limit → 429 RATE_LIMIT_EXCEEDED
05

Performance

I measured the plain HTTP/1.1 path (JWT middleware, Redis rate limit, route match, proxy, metrics) at a fixed 500 requests per second and compared it with calling the same upstream directly. On an Apple M2 laptop, inside a Linux container on Node 26, the gateway added 0.76 ms at the median for keep-alive clients and 0.50 ms when every request opened a new connection. It used 37–67 % of one CPU core and under 200 MB of memory, with no errors across 180,000 measured requests.

ClientDirect p50 / p99Via gateway p50 / p99Overhead p50Overhead p99
Keep-alive client0.24 / 103.43 ms1.00 / 658.14 ms0.76 ms554.71 ms
New connection per request0.49 / 15.95 ms0.99 / 251.85 ms0.50 ms235.90 ms
Fixed 500 req/s, 3 rounds × 30 s per target and scenario after a 10 s warm-up. Plain HTTP/1.1 path only: no auth plugins, TLS, HTTP/2, WebSocket or gRPC.

The tail is where it falls short. p99 overhead ranged from 10 ms to several hundred milliseconds between rounds, so I don't claim "under 10 ms" for it. Some of that was the laptop: in one round the direct path's own p99 jumped to 276 ms. Some of it is the gateway: its own request log puts its internal p99 at 52 ms, and the benchmark surfaced a defect behind part of that. The proxy closes every client and upstream connection, so each request pays for two TCP handshakes.

Getting a trustworthy measurement took three attempts. autocannon kept writing to sockets the gateway was closing and reported ~950 ms; macOS ran out of ephemeral ports; and piping the gateway's log through the load generator stalled the gateway, because Node writes to pipes synchronously on Linux. The script, the raw results and the failed attempts are kept with the benchmark.

06

What's next

  • Connection reuse. The benchmark exposed that the HTTP/1.1 proxy opens a fresh upstream connection for every request and passes the upstream's connection: close header back to the client, so each proxied request costs two new TCP connections, one of the causes of the p99 tail. The fix is a keep-alive agent towards upstreams plus stripping hop-by-hop headers from responses, as the HTTP/2 path already does. After that I'll re-run the same benchmark.
  • Wider benchmarks. So far only the plain HTTP/1.1 path has been measured. Next are the auth plugins, TLS termination, HTTP/2, WebSocket and gRPC, then the head-to-head comparison with Kong that the roadmap asks for.
  • Smaller cleanups found while writing this up: stop labelling one metric with raw client IPs, and decide whether a gateway with no cached config and no control plane should refuse to start (the docs say yes; today it serves 404s until config arrives).

Need an API gateway, an auth layer or a backend that has to stay fast?