← Building blocks

One front door for many services

Scaling & loadfundamental

Clients must know every service, and cross-cutting concerns (auth, limits, TLS) are duplicated.

Say it like this

Auth, rate limits and TLS belong in one place, so I put an API gateway in front of the services; it does the cross-cutting work once per request and the services behind it stay simple.

Basic solution

Put an API gateway in front: it terminates TLS, authenticates, rate limits, and routes to services.

KongAWS API GatewayEnvoynginx

Cross-cutting policy once, at the edge

The gateway terminates TLS, validates identity, applies limits and routes. Rejected requests never reach a backend; accepted ones carry identity headers and a correlation id.

How it works

  1. The client sends every request to one hostname. DNS resolves it to a load balancer, which spreads requests across the gateway instances.
  2. The gateway terminates TLS, decrypting the request, and reads the route: the path, the method and any version header. That tells it which backend the request is for.
  3. It authenticates. For a JWT, it checks the signature and expiry locally with the issuer's public key, with no network call. For an API key, it looks the key up in a local cache. Either way it attaches the resolved identity (user id, scopes) as headers for the backend to trust.
  4. It applies policy: a rate-limit check per user and key against a Redis store in the same zone, a request size limit, and schema validation of the body. Anything that fails is rejected here with 401, 413 or 429, and never reaches a backend.
  5. It forwards the request to the right backend service, adding a correlation id and a deadline header. If needed it translates on the way: REST to gRPC, or an old API version's shape to the current one.
  6. It records a metric per route and client (count, latency, status) and returns the backend's response with standard headers added: rate-limit remaining and the request id.

What the gateway must not do

  • Business logic, joins across services, or anything that needs a database on the request path. Keep it a thin, stateless policy layer that any instance can serve.

Worked example

Gateway for the rate-limited API

  • 50K requests per second at peak across 30 backend services.
  • Without a gateway: each of 30 services implements JWT validation, rate limiting and TLS. One rate-limit bug fix is 30 deploys; one key rotation is 30 config changes.
  • With a gateway: 50K requests per second of policy work. JWT validation is a signature check at about 20 microseconds; a rate-limit check is one Redis EVALSHA at about 0.3 ms. Per gateway instance with an event-loop runtime: about 10K requests per second comfortably, so 8 instances with headroom, behind a layer-4 balancer.
  • Added latency: about 1 ms per request for auth, limit and routing, against backend latencies of 20 to 200 ms.
  • Rejections at the edge: 3 percent of traffic is rate limited or unauthenticated, 1,500 requests per second that never reach a backend and never consume a database connection.
  • Observability: one place emits per-route p99 and error rate for all 30 services, so the dashboards exist before any service adds instrumentation.

Variants and when each wins

Dedicated gateway (Kong, AWS API Gateway, Apigee)

  • A product built for the job, with plugins for auth, limits, transformation and a developer portal. It wins for public APIs with many external clients and products to manage.

Reverse proxy with policy (nginx, Envoy)

  • A fast proxy configured as routes and filters, with auth and limits added as modules. It wins when the policy set is small and raw performance matters more than features.

Service mesh sidecars

  • A local proxy next to each service that handles mTLS, retries and routing between services. It complements the gateway rather than replacing it: the mesh handles traffic between services (east-west), the gateway handles traffic from clients (north-south).

Backend-for-frontend

  • A gateway per client type (mobile, web) that also combines several backend calls into one response. It wins when clients need very different response shapes; the risk is that it turns into a business-logic layer.

Recommendation: one thin gateway at the edge for auth, limits and routing; a mesh for service-to-service concerns; a backend-for-frontend only when client shapes diverge a lot.

Failure modes

The gateway becomes the monolith

  • Every feature needs a gateway change and gateway deploys become the bottleneck for every team. It happens because business logic and response aggregation crept into the gateway over time. Enforce a rule that the gateway holds only cross-cutting policy, and move aggregation into a backend-for-frontend owned by the client team.

Single point of failure

  • A bug in a gateway release takes every API down at once. It happens because the gateway is one tier on every request path. Run several instances across zones, canary the gateway's own deploys, and keep a bypass route for health checks and status pages that does not go through the gateway logic.

Auth cache poisoning or staleness

  • A revoked API key keeps working for ten minutes. It happens because the gateway caches key lookups and nothing tells it about the revocation. Use short cache TTLs plus an invalidation channel the gateway subscribes to, and keep JWTs short-lived so a revocation takes effect at the next token refresh.

Added tail latency

  • The p99 latency rises by tens of milliseconds after the gateway is introduced. It happens because the gateway makes a synchronous call to an auth service or a remote rate-limit store on every request. Validate JWTs locally, cache API-key lookups, keep the rate-limit store in the same zone with a tight timeout, and fail open on the limit check for routes that are not security-sensitive.

Header trust leaks

  • A client sets an X-User-Id header and the backend believes it. It happens because backends trust identity headers no matter where the request came from. Make backends accept identity headers only from the gateway over the private network, and have the gateway strip any such headers that arrive from clients.

Interviewer follow-ups

Answer out loud before you open each one.

What belongs in the gateway and what belongs in the services?

Anything identical for every route belongs in the gateway: TLS, authentication, coarse rate limits, request size and schema checks, correlation ids, metrics. Anything that depends on the domain belongs in the service: authorisation on a specific resource, business validation, and any read of business data.

How does the gateway avoid becoming a latency bottleneck?

By doing only local, cheap work per request: signature checks rather than auth-service calls, cached key lookups, a single in-zone Redis call for limits with a few-millisecond timeout. Anything that would need a remote call per request is either cached or pushed to the backend.

Gateway or service mesh?

Both, for different traffic. The gateway handles north-south traffic from clients: auth, limits, routing, versioning. The mesh handles east-west traffic between services: mTLS, retries, timeouts, traffic shifting. A mesh does not replace an API gateway, and a gateway does not secure internal calls.

How do you roll out a breaking API change through the gateway?

Expose the new version on a new path or version header while keeping the old one, and let the gateway route each to the right backend or translate the old shape to the new. Publish a sunset date, watch per-version traffic in the gateway metrics, and remove the old route when it drops to zero.

Connections

Pairs with
Limit requests per client · Authenticate, then authorise · Terminate TLS at the edge · Spread traffic across servers · Tag every log line with the request · Change an API without breaking clients
Pulls against
Split a monolith by domain
Used in
Distributed Rate Limiter

The same parts on other clouds

The diagrams above name AWS services as one concrete example. Every part has a close equivalent elsewhere. In an interview, name the role first, such as “a managed Redis cache”, then the product you would pick.

AWSUsed here asGoogle CloudMicrosoft AzureOpen source and others
Amazon API GatewayAPI gatewayAPI Gateway, ApigeeAPI ManagementKong, Tyk
Amazon ElastiCacheRate-limit storeMemorystoreAzure Managed RedisRedis, Valkey, Memcached
Amazon EC2 Auto ScalingOrders service, Users service, Search serviceCompute Engine managed instance groupsVirtual Machine Scale SetsKubernetes Deployment with a HorizontalPodAutoscaler, Nomad
Amazon CloudWatchMetrics + logsCloud Monitoring, Cloud LoggingAzure MonitorPrometheus and Grafana, Datadog