Compile Ready
All system design questions
System Design/Foundations

API Gateway

Design an API gateway handling routing, auth, rate limiting, and observability for hundreds of services.

Intermediate 50m interview 22m read High frequency Popularity 84
Amazon Netflix Stripe Microsoft

Problem Statement

Design an API Gateway for a large microservices platform. The gateway sits at the edge between external clients and internal services. It must route requests by host, path, method, headers, and tenant, terminate TLS where appropriate, enforce authentication and authorization, apply quotas, and proxy traffic to healthy backend services.

At interview scale, assume hundreds of microservices, thousands of routes, multiple client types, and traffic bursts from web, mobile, partner, and internal clients. The hard part is not forwarding HTTP packets; it is building a reliable data plane that makes fast per-request decisions while a safer control plane manages configuration, policies, rollout, and service discovery.

A strong design keeps the gateway stateless on the hot path, avoids turning it into a giant business-logic monolith, and treats the gateway as a platform primitive. Services should not each reinvent JWT validation, API key checks, rate limits, retries, logging, tracing, or TLS handling, but they must still own their domain logic and fine-grained business authorization.

Business use case

API gateways let organizations expose many backend services through a small number of stable public APIs. They reduce client complexity, centralize cross-cutting concerns, and provide a consistent place to enforce security, quotas, observability, and reliability policies.

They are especially valuable for microservice platforms, partner APIs, mobile backends, and multi-tenant SaaS products. A well-designed gateway improves developer velocity because new services can publish routes and policies through configuration instead of building edge infrastructure from scratch.

Functional Requirements

  • Route incoming requests based on host, path prefix, method, headers, tenant, and route priority.

  • Terminate TLS at the edge or pass through TLS when a service requires end-to-end encryption.

  • Authenticate callers using JWT, OAuth tokens, API keys, or mTLS client certificates.

  • Authorize requests using scopes, roles, tenant boundaries, and route-level policy rules.

  • Apply rate limits, quotas, request size limits, and burst controls per user, token, tenant, IP, and API plan.

  • Discover healthy backend service instances and load balance requests across them.

  • Support request and response transformation, header enrichment, version translation, and backend-for-frontend aggregation.

  • Emit metrics, structured access logs, audit logs, and distributed traces for every route and dependency.

Non-Functional Requirements

Latency

The gateway is on every request, so it should add less than 5ms p50 and less than 25ms p99 overhead inside a region for simple proxy routes. Expensive features such as token introspection or aggregation must be cached or isolated so they do not dominate tail latency.

Availability

The data plane should target at least 99.99 percent availability and keep proxying with the last known good configuration when the control plane is unavailable. A gateway outage can take down many products at once, so every region and availability zone needs redundant gateway capacity.

Scalability

The gateway fleet must scale horizontally by request volume, TLS handshakes, policy evaluation CPU, and network bandwidth. Route lookup, auth checks, rate limits, and service discovery reads must be local or cached on the data plane.

Configuration consistency

Route and policy changes need versioned rollout, validation, canarying, rollback, and auditability. Data-plane instances can be eventually consistent for most changes, but security revocations and emergency blocks need fast propagation or deny-list overrides.

Security isolation

A tenant or partner should not be able to exhaust shared gateway capacity, bypass authorization, poison route configuration, or read another tenant's traffic. Enforce strict identity, tenancy, input validation, and plugin sandbox boundaries.

Resilience

Timeouts, retries, circuit breakers, outlier detection, and backpressure must protect backend services. The gateway should fail closed for security decisions, fail open only for explicitly safe non-critical telemetry, and avoid retry storms.

Operability

Operators need route-level dashboards, config diffing, synthetic probes, error budgets, trace correlation, and per-policy metrics. Debuggability matters because a wrong route or filter can look like a backend outage to clients.

Capacity Estimation

Assumptions

Assume 20M daily active users, 250 gateway requests per active user per day, 500 backend microservices, 12,000 configured routes, three active regions, 70 percent authenticated traffic, average request metadata plus small body of 3 KB, average backend response of 8 KB, and 1 KB of structured log data per request.

Use a 10x peak multiplier for diurnal traffic and product launches. Assume a gateway instance can safely sustain 8,000 simple proxy requests per second at 60 percent CPU after reserving headroom for TLS, policy evaluation, and occasional retries.

Gateway requests

5B per day

20M active users times 250 requests per day

Average ingress QPS

57,900 requests per second

5B divided by 86,400 seconds

Peak ingress QPS

579,000 requests per second

10x average peak

Peak QPS per region

193,000 requests per second

Evenly spread across three active regions before failover headroom

Authenticated traffic

40,500 auth checks per second average

70 percent of average gateway QPS

Rate-limit operations

116,000 counter operations per second average

Two token-bucket operations per request for user and tenant dimensions

Route configuration

120 MB normalized config

12,000 routes times about 10 KB including policies and compiled matchers

Access log volume

5 TB per day raw

5B requests times 1 KB per structured log before compression

Average response bandwidth

463 MB per second

57,900 requests per second times 8 KB response payload and headers

Gateway fleet size

90 to 120 instances at global peak

579,000 peak QPS divided by 8,000 QPS per instance plus zone and rollout headroom

Calculations

  • Requests: 20M active users times 250 calls per user per day equals 5B gateway requests per day.
  • Average QPS: 5B divided by 86,400 seconds is about 57,870 requests per second, rounded to 57,900.
  • Peak QPS: a 10x multiplier gives about 579,000 requests per second globally. With three active regions, the steady peak is about 193,000 per region before failover reserves.
  • Auth checks: 70 percent authenticated traffic means about 40,500 token or key checks per second on average. Most checks must use local JWT verification, cached public keys, or cached introspection results.
  • Rate limits: if the gateway updates both user and tenant buckets, average counter traffic is about 115,800 operations per second. At peak it is about 1.16M operations per second, so the design needs local batching, sharding, or distributed token buckets.
  • Config memory: 12,000 routes times 10 KB is about 120 MB of normalized route and policy data. Every data-plane instance can keep this in memory, but rollout and validation should avoid loading broken snapshots.
  • Logs: 5B requests times 1 KB is about 5 TB raw logs per day. Compression and sampling help, but security audit events and error logs should remain durable.
  • Bandwidth: average response egress is 57,900 times 8 KB, about 463 MB per second. Peak response egress is about 4.6 GB per second, before retries and TLS overhead.
  • Fleet: at 8,000 requests per second per instance, 579,000 peak requests need about 73 instances. Add availability-zone, deployment, failover, and noisy-route headroom to plan for 90 to 120 instances globally.

API Design

POST/admin/v1/routes

Creates a route definition in the control plane. The control plane validates host and path conflicts, compiles match rules, attaches a policy chain, and includes the route in the next signed config snapshot.

Request


{
  "name": "orders-checkout-v1",
  "hosts": ["api.example.com"],
  "pathPrefix": "/orders/v1/checkout",
  "methods": ["POST"],
  "upstreamService": "orders-service",
  "policyChainId": "policy_checkout_public",
  "priority": 100
}

Response


{
  "routeId": "route_7f3a",
  "version": 41,
  "status": "staged",
  "conflicts": []
}
  • 201Route staged
  • 400Invalid host, path, method, or upstream
  • 401Control-plane authentication required
  • 403Caller cannot manage this tenant or environment
  • 409Route overlaps with a higher-priority route
PATCH/admin/v1/routes/{routeId}/policies

Updates the policy chain for a route, such as JWT issuer, required scopes, rate-limit plan, timeout, retry budget, cache policy, and transformation rules. The update creates a new route version rather than mutating live data-plane state directly.

Request


{
  "requiredScopes": ["orders.write"],
  "rateLimitPolicyId": "tenant_standard_write",
  "timeoutMs": 800,
  "retryPolicy": {
    "maxAttempts": 2,
    "retryOn": ["connect-failure", "reset"]
  },
  "requestTransformId": "checkout_mobile_v2"
}

Response


{
  "routeId": "route_7f3a",
  "version": 42,
  "status": "staged",
  "requiresRollout": true
}
  • 200Policy staged
  • 400Invalid policy
  • 401Authentication required
  • 403Insufficient admin permission
  • 404Route not found
POST/admin/v1/consumers/{consumerId}/api-keys

Issues an API key for a partner or service consumer. Only a salted hash is stored. The returned secret is shown once and is later validated by the gateway through a local or cached credential lookup.

Request


{
  "displayName": "partner-mobile-prod",
  "scopes": ["catalog.read", "orders.write"],
  "quotaPlanId": "partner_gold",
  "expiresAt": "2027-07-26T00:00:00Z"
}

Response


{
  "keyId": "key_b23d",
  "apiKey": "shown-once-secret-value",
  "expiresAt": "2027-07-26T00:00:00Z"
}
  • 201API key issued
  • 400Invalid scopes, quota plan, or expiration
  • 401Authentication required
  • 403Caller cannot manage this consumer
  • 429Credential creation rate limit exceeded
POST/admin/v1/config-snapshots/{snapshotId}/rollouts

Starts a controlled rollout of a signed gateway configuration snapshot. Rollouts can target one canary cell, one region, a percentage of gateway instances, or the full fleet after health checks pass.

Request


{
  "strategy": "canary-then-linear",
  "initialPercent": 1,
  "stepPercent": 20,
  "healthGate": {
    "maxFiveXxRate": 0.01,
    "maxAddedLatencyMsP99": 10
  }
}

Response


{
  "rolloutId": "rollout_991",
  "snapshotId": "snap_1802",
  "state": "running",
  "currentPercent": 1
}
  • 202Rollout accepted
  • 400Invalid rollout plan
  • 401Authentication required
  • 403Caller cannot deploy gateway config
  • 409Another rollout is active
GET/admin/v1/routes/{routeId}/metrics

Returns route-level metrics from the telemetry pipeline for debugging and capacity planning. Operators use this to determine whether errors come from the gateway, auth dependency, rate limiter, or backend service.

Response


{
  "routeId": "route_7f3a",
  "window": "5m",
  "requestsPerSecond": 18420,
  "p99GatewayOverheadMs": 18,
  "backendFiveXxRate": 0.004,
  "rateLimitedRequests": 921,
  "circuitBreakerOpen": false
}
  • 200Metrics returned
  • 401Authentication required
  • 403Caller cannot view route metrics
  • 404Route not found
POST/orders/v1/checkout

Example data-plane request exposed through the gateway. The gateway matches the route, validates identity and scopes, applies quotas, transforms headers, selects a healthy orders-service instance, and proxies the request.

Request


POST /orders/v1/checkout HTTP/1.1
Host: api.example.com
Authorization: Bearer eyJhbGciOiJSUzI1NiJ9
Idempotency-Key: idem_123

{
  "cartId": "cart_123",
  "paymentMethodId": "pm_456"
}

Response


HTTP/1.1 201 Created
Traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01
X-RateLimit-Remaining: 118

{
  "orderId": "ord_789",
  "status": "confirmed"
}
  • 201Backend service created the order
  • 400Request rejected by validation or backend
  • 401Missing or invalid token
  • 403Token lacks required scope or tenant access
  • 429Rate limit or quota exceeded
  • 503No healthy upstream or circuit breaker open

Separate the control-plane API from the data-plane proxy path. Control-plane endpoints create validated, versioned configuration. Data-plane endpoints are the customer's actual APIs and should not read the control-plane database per request.

The public API examples are intentionally simple. In production, admin APIs need strong operator identity, approval workflows for risky changes, audit logs, dry-run validation, and automated rollback gates.

Database Design

The gateway's durable database stores control-plane state: routes, policies, consumers, credentials, and config snapshots. It is not in the hot path for every proxied request. Data-plane instances consume signed snapshots and keep route matchers, keys, policy rules, and service endpoint caches in memory.

Use a relational store for strong validation and transactional updates to configuration. Use a distributed key-value or cache layer for rate-limit counters, token introspection caches, JWKS keys, and short-lived response cache entries.

route_definitions
route_iduuidPrimary key
tenant_iduuidOwning tenant or product
namevarchar(128)Human-readable route name
host_patternsjsonExact hosts or wildcard host rules
path_patternvarchar(512)Prefix, exact path, or parameterized path pattern
methodsjsonAllowed HTTP methods
upstream_servicevarchar(128)Logical service name resolved through discovery
policy_chain_iduuidAttached ordered filter chain
priorityintHigher priority wins for overlapping routes
versionbigintMonotonic route version
statusvarchar(20)Staged, active, disabled, or deleted
updated_attimestampLast configuration change
policy_chains
policy_chain_iduuidPrimary key
tenant_iduuidPolicy owner
filtersjsonOrdered plugin list and parameters
auth_policyjsonJWT, API key, OAuth, or mTLS requirements
rate_limit_policyjsonBucket dimensions, quota plan, and burst limits
resilience_policyjsonTimeouts, retries, circuit breakers, and hedging rules
cache_policyjsonResponse cache TTL and cache-key rules
transform_policyjsonHeader, query, body, and aggregation rules
versionbigintPolicy version included in snapshots
consumer_credentials
credential_iduuidPrimary key
consumer_iduuidPartner, user, service account, or tenant principal
tenant_iduuidTenant boundary for authorization and quotas
credential_typevarchar(32)API key, OAuth client, certificate, or service token
credential_hashvarbinarySalted hash or certificate fingerprint; never store raw API keys
scopesjsonAllowed scopes and route groups
quota_plan_iduuidDefault quota plan
statusvarchar(20)Active, revoked, expired, or suspended
expires_attimestamp nullableExpiration for key rotation
config_snapshots
snapshot_iduuidPrimary key
versionbigintGlobal config version
checksumvarchar(128)Content hash verified by gateways
signed_bundle_uritextLocation of the compiled route and policy bundle
routes_countintNumber of routes in the snapshot
created_byuuidOperator or automation principal
created_attimestampSnapshot creation time
rollout_statevarchar(32)Draft, canary, active, rolled_back, or failed

Indexes

  • route_definitions.tenant_id, host_patterns, path_pattern supports route conflict checks during control-plane validation.
  • route_definitions.status, version supports snapshot creation and audit diffing.
  • consumer_credentials.consumer_id, status supports credential management and revocation workflows.
  • config_snapshots.version is unique so gateways can request the next signed bundle by version.
  • Data-plane route lookup should use compiled in-memory tries or deterministic finite automata, not database indexes.

Relationships

A route references one policy chain and one logical upstream service. A consumer credential references a quota plan and scopes. A config snapshot materializes many active route and policy versions into one immutable bundle. Service instance membership comes from service discovery and is intentionally separate from the route database.

NoSQL alternatives

For very large multi-tenant platforms, route snapshots can be stored as immutable objects in blob storage with metadata in a key-value database. Rate-limit counters belong in Redis, DynamoDB, Aerospike, or a purpose-built distributed counter store. Access logs, traces, and metrics belong in streaming and observability systems, not the control-plane relational database.

High-Level Architecture

Drag to pan · Ctrl/⌘ + scroll to zoom

The data plane handles every client request with local route, policy, auth, quota, cache, and discovery state. The control plane validates and rolls out configuration but is not required for every proxied request.

Split the gateway into a fast data plane and a safer control plane. The data plane is a horizontally scaled fleet of stateless proxies that hold a signed, compiled config snapshot in memory. It should continue serving with the last known good snapshot if the control plane or configuration database is down.

The control plane owns route authoring, policy validation, conflict detection, config signing, canary rollout, rollback, and audit trails. It pulls or receives service discovery data, compiles route matchers, and distributes snapshots to the gateway fleet. This separation prevents slow admin workflows from affecting live request latency.

The gateway must not become the place where every team puts business logic. Keep the plugin surface narrow, version filters carefully, sandbox risky extensions, and push domain decisions back to owning services unless the decision is genuinely cross-cutting.

Request Flow

  1. 1

    Connection reaches the edge

    A client connects through DNS, CDN, WAF, or a regional load balancer. TLS can terminate at the CDN, at the load balancer, or at the gateway depending on trust boundaries. The gateway receives normalized request metadata, peer identity, and trace context.

  2. 2

    Route matcher selects a route

    The data plane matches host, method, path, headers, and tenant against a compiled route table. Exact host and path matches win before wildcard and prefix matches. Route priority resolves intentional overlaps, and ambiguous config should have been rejected by the control plane.

  3. 3

    Pre-routing filters validate the request

    The gateway applies request size limits, header normalization, malformed request rejection, CORS handling, WAF signals, and optional schema validation. These checks protect backend services from wasteful or dangerous traffic before expensive work begins.

  4. 4

    Authentication and authorization run

    The gateway validates JWT signatures with cached public keys, checks API key hashes, performs OAuth token introspection only when needed, or verifies client certificates. It then checks route scopes, tenant boundaries, and coarse roles before forwarding identity claims to the backend.

  5. 5

    Rate limits and quotas are enforced

    The request consumes tokens from per-consumer, per-tenant, per-route, or per-IP buckets. Local warm counters can absorb small bursts, while shared counters enforce global quotas. Exceeded requests return 429 with retry and remaining-quota headers.

  6. 6

    Transform, cache, or aggregate when configured

    The gateway may rewrite paths, add correlation headers, remove unsafe headers, translate API versions, cache safe GET responses, or aggregate a small number of backend calls for a mobile backend-for-frontend route. This should remain declarative and bounded.

  7. 7

    Healthy upstream is chosen

    The gateway resolves the logical upstream service through service discovery, filters unhealthy instances, respects locality and tenant routing, and load balances using round robin, least outstanding requests, weighted routing, or consistent hashing.

  8. 8

    Proxy call runs inside a resilience envelope

    The gateway applies request deadlines, connect timeouts, retry budgets, circuit breakers, connection pooling, and backpressure. Retries are limited to safe or explicitly idempotent operations and must not multiply load during backend incidents.

  9. 9

    Response returns with telemetry

    The gateway records status, latency, route, tenant, upstream, auth outcome, rate-limit decision, and trace identifiers. Response filters add security headers, quota headers, and trace headers before the response is returned to the client.

Core Components

Gateway Data Plane

Processes every client request with local routing and policy state.

This fleet terminates or accepts TLS, matches routes, executes filters, enforces policies, proxies to services, and emits telemetry. It should be stateless except for in-memory config, connection pools, short-lived caches, and local rate-limit warm buckets.

Gateway Control Plane

Manages route and policy lifecycle outside the hot path.

The control plane validates route conflicts, compiles matchers, signs config snapshots, rolls them out gradually, monitors health gates, and supports rollback. It is allowed to be slower than the data plane because it is not on every customer request.

Route Matcher

Finds the winning route using host, path, method, and priority.

A production matcher uses tries, prefix maps, host maps, or generated matching code so lookup remains fast even with thousands of routes. It also needs deterministic precedence rules so teams can reason about overlapping paths.

Plugin and Filter Chain

Runs bounded cross-cutting logic before and after proxying.

Filters implement authentication, authorization, rate limiting, transforms, caching, compression, request validation, and response decoration. The chain must be ordered, versioned, observable, and constrained so teams cannot deploy arbitrary unreviewed business logic into the edge.

Auth and Authorization Offload

Validates caller identity and coarse access policies centrally.

JWT verification should usually be local using cached JWKS keys. API keys require hashed lookup or cache checks. OAuth introspection should be cached aggressively. The gateway enforces coarse scopes and tenant boundaries, while services retain domain-specific authorization.

Rate Limiting and Quota Engine

Protects backend capacity and enforces product plans.

The engine tracks token buckets, leaky buckets, or sliding windows across dimensions such as IP, API key, user, tenant, route, and region. It must handle hot tenants, global quotas, local bursts, and clear client feedback through 429 responses.

Discovery, Load Balancing, and Resilience Layer

Chooses upstream instances and limits failure blast radius.

This layer consumes service registry updates, health checks, outlier detection, locality hints, circuit breakers, retries, connection pools, and timeouts. It prevents slow or failing services from consuming gateway worker threads and client patience.

Observability Pipeline

Provides route-level debugging and platform accountability.

Every request should produce metrics and trace spans with route, tenant, upstream, status, latency, policy outcome, and error classification. Logs should be sampled for success paths but durable for security decisions, admin actions, and failures.

Deep Dive

Control plane versus data plane

The most important architectural split is between the control plane and the data plane. The data plane is the gateway fleet that handles customer requests, so it must be fast, local, horizontally scalable, and able to continue with the last known good configuration. It should not synchronously call the configuration database, admin API, or service catalog for every request.

The control plane handles humans and automation: route creation, policy authoring, validation, compilation, signing, rollout, rollback, and audit. This plane needs stronger consistency and safety checks. It can use relational transactions, approval workflows, and canary health gates because it is not in the proxy hot path.

A common failure mode is letting control-plane availability determine data-plane availability. The safer design is that gateways subscribe to signed snapshots, verify checksums, load them atomically, and keep the previous version if the new version fails validation or health checks.

Route matching, transformation, and filter chain ordering

Route matching must be deterministic. A good design defines exact host before wildcard host, exact path before prefix path, explicit method before any method, and route priority as the final tie-breaker. The control plane should reject accidental overlaps or require the owner to declare precedence.

Filters should run in a predictable order. Typical request order is normalization, WAF, authentication, authorization, rate limit, request transform, cache lookup, discovery, proxy, response transform, and telemetry. If filters are unordered, teams will create subtle security bugs such as transforming an authorization header before token validation.

Request and response transformation is useful for version translation, header enrichment, mobile payload shaping, and backend-for-frontend aggregation. It must be bounded by payload size, timeout, fanout limits, and schema versioning. Heavy business workflows should live in dedicated backend services, not in gateway scripts.

Authentication, authorization, and identity propagation

The gateway should offload common authentication: validate JWT signatures locally, rotate and cache JWKS keys, check API key hashes, support OAuth introspection for opaque tokens, and optionally verify mTLS client certificates. This avoids every microservice implementing the same security plumbing.

Authorization at the gateway should be coarse and route-oriented: required scopes, tenant membership, partner plan, internal versus external caller, and service-to-service identity. Domain-specific checks such as whether a user owns a particular order still belong to the backend service because the gateway should not fetch domain entities or understand business invariants.

Identity propagation must be explicit. Forward signed identity headers only after stripping any client-supplied versions, include tenant and scopes, preserve trace context, and make downstream services trust the gateway only over an authenticated internal network.

Rate limiting, quotas, and edge caching

Rate limiting protects both the platform and paying customers. Token bucket works well for bursty APIs because it allows short bursts while enforcing average rates. Sliding windows give smoother semantics but can be more expensive. Production systems often combine local per-instance buckets for latency with a shared distributed counter for global quota correctness.

Dimensions matter. Per-IP limits stop anonymous abuse, per-token limits enforce customer plans, per-tenant limits protect noisy neighbors, and per-route limits protect expensive APIs. Return useful 429 responses with reset time and remaining quota where safe.

Caching can reduce backend load, but only for safe responses. Cache keys must include tenant, authorization context, query parameters, content negotiation headers, and any relevant version. Never cache personalized or privileged responses unless the key proves isolation. Cache negative auth or credential lookups briefly to protect identity stores.

Timeouts, retries, circuit breakers, and backpressure

The gateway is often the first place to notice backend degradation. Every route needs a request deadline. The gateway should use short connection timeouts, bounded retry attempts, retry budgets, and circuit breakers that open when an upstream is failing. Without this, slow services tie up gateway resources and harm unrelated routes.

Retries are dangerous. Retrying GET may be acceptable, but POST requires idempotency keys or explicit backend support. Retrying after a request reached the service can duplicate side effects. The gateway should avoid retrying on application errors and should never retry so aggressively that it multiplies traffic during an incident.

Backpressure is as important as failure recovery. When queues, connection pools, or worker pools saturate, the gateway should shed load quickly with clear errors rather than allowing latency to grow until clients time out and retry from the outside.

Avoiding a gateway monolith and single point of failure

An API Gateway is strategically central, which makes it risky. If every team embeds custom business logic, the gateway becomes a monolith with unclear ownership, slow releases, and broad blast radius. Keep plugins generic, declarative, reviewed, and versioned. Create dedicated backend-for-frontend services when aggregation becomes complex.

Avoid a single point of failure through multi-zone gateway fleets, health-checked load balancers, active-active regional deployment, last-known-good configuration, and independent scaling of control plane, data plane, rate limiter, and telemetry. Roll out gateway binaries and config separately so a route change does not require a full proxy deployment.

Blast-radius controls should exist at multiple levels: per-route circuit breakers, per-tenant quotas, per-cell deployment, per-region failover, and emergency route disablement. The gateway must be powerful enough to protect the platform but constrained enough that one bad plugin or config cannot break every API.

Scaling

Startup: one region and simple reverse proxy

Start with a managed load balancer, a small gateway fleet, static route configuration, JWT validation, API key checks, simple per-IP limits, and service endpoints from deployment configuration. This is enough when the number of services and routes is small.

Growth: centralized control plane and service discovery

Introduce a control plane for route ownership, policy configuration, validation, and audit. Integrate with service discovery so the gateway routes to healthy instances. Add Redis or a distributed cache for API keys, public keys, token introspection results, response cache, and quota counters.

Large scale: multi-zone gateway cells

Partition the gateway fleet into cells by region, tenant group, or traffic class. Use compiled route snapshots, local rate-limit warm buckets, circuit breakers, and per-route metrics. Separate public, partner, internal, and admin gateways if their traffic and risk profiles differ.

Global scale: active-active edge platform

Deploy gateways in multiple regions behind global load balancing or anycast. Keep data-plane decisions local, replicate configuration snapshots globally, and use regional service discovery. Route failover should consider data residency, tenant home region, and backend service availability.

Platform scale: extensible but governed gateway

Offer self-service route onboarding, policy templates, plugin certification, traffic shadowing, canary releases, schema validation, and automated rollback. At this stage, governance and blast-radius reduction are as important as raw proxy throughput.

Bottlenecks & Optimizations

Route table growth and slow matching

Compile routes into host maps, tries, prefix trees, or generated matchers instead of scanning route lists. Reject ambiguous overlaps in the control plane, keep route snapshots compact, and measure match latency as route count grows.

Auth provider dependency on the hot path

Prefer local JWT verification with cached JWKS keys. Cache opaque token introspection results with short TTLs, negative-cache invalid credentials briefly, and isolate auth provider timeouts. Emergency revocation can use a small fast deny list pushed to gateways.

Hot rate-limit keys for large tenants

Shard counters by tenant and time window, use local token buckets for bursts, periodically reconcile to global quotas, and isolate large tenants into dedicated quota partitions. Return 429 before the shared counter store melts down.

Gateway CPU and network saturation

Use efficient TLS termination, keep-alive connection pools, HTTP/2 or HTTP/3 where useful, zero-copy proxying when available, compression policies, and horizontal autoscaling. Separate large upload or streaming routes from latency-sensitive JSON APIs.

Too much business logic in plugins

Limit gateway plugins to cross-cutting concerns and declarative transforms. Move complex orchestration to backend-for-frontend services with clear owners, tests, and release cycles. Require plugin review, quotas, and timeout budgets.

Failure Handling

Control plane or config database is unavailable

Data-plane gateways continue serving the last known good snapshot. New route changes and rollouts pause, but existing APIs keep working. Operators receive alerts for snapshot staleness, and emergency deny-list updates use a small independent channel if required.

Bad route config or plugin rollout

Use static validation, shadow traffic, canary cells, automated health gates, and instant rollback to the previous signed snapshot. Keep config rollout separate from binary deployment so rollback is fast and low risk.

Identity provider or key endpoint degrades

Continue validating JWTs with cached keys until their safe TTL expires. For opaque token introspection, use cached positive results within policy limits and fail closed for high-risk routes. Surface clear 503 or 401 errors rather than silently bypassing auth.

Backend service becomes slow or unhealthy

Outlier detection removes bad instances. Circuit breakers open for failing upstreams, retries stay within a retry budget, and the gateway returns fast 503 responses when no healthy upstream remains. Unrelated routes and tenants should not share the same exhausted pools.

Rate-limit or cache store is unavailable

Use route-specific fallback policies. Critical paid APIs may fail closed or use conservative local limits. Low-risk public APIs may fail open for a short window with local counters. Alert loudly because fail-open can create backend overload and billing leakage.

Gateway region fails

Global load balancing shifts traffic to healthy regions. Gateways in other regions already have recent config snapshots and regional service discovery data. If backend data is region-bound, failover rules must respect tenant home region and compliance constraints.

Security

Credential handling

Never store raw API keys. Store salted hashes or fingerprints, support key rotation, log key identifiers instead of secrets, and redact authorization headers from logs. JWT public keys should rotate safely with overlapping validity windows.

Authorization boundaries

Strip client-supplied identity headers before adding trusted gateway identity headers. Enforce route scopes and tenant membership at the edge, but require backend services to perform domain-specific authorization for resource ownership.

TLS and mTLS

Terminate TLS at controlled edges with modern cipher policy and certificate automation. Use mTLS for service-to-service or partner traffic when needed, and preserve end-to-end encryption for routes with stricter compliance requirements.

Input and protocol protection

Reject oversized headers, malformed paths, dangerous encodings, unsupported methods, request smuggling patterns, and suspicious protocol upgrades. Apply WAF rules before expensive auth or backend work where possible.

Plugin sandboxing and supply chain

Gateway extensions run with broad traffic access, so they need review, signing, least privilege, resource limits, deterministic timeouts, and auditability. Do not let teams deploy arbitrary untrusted code into the shared edge.

Audit and privacy

Admin actions, credential changes, route changes, and security decisions need durable audit logs. Request logs should minimize personal data, redact secrets, and respect retention policies while retaining enough detail for incident response.

Tradeoffs

Pros

  • +Centralizes cross-cutting security, rate limiting, observability, and resilience policies.
  • +Simplifies clients by exposing stable APIs while backend services evolve independently.
  • +Allows consistent route-level metrics, tracing, audits, and operational controls.
  • +Improves backend protection through quotas, circuit breakers, request validation, and load shedding.
  • +Enables self-service service onboarding through declarative route and policy configuration.

Cons

  • Every request pays gateway latency and availability risk.
  • A misconfigured route, plugin, or auth policy can affect many services at once.
  • The gateway can become an organizational monolith if teams push business logic into it.
  • Global rate limits and config propagation add distributed-systems complexity.
  • Central ownership can become a bottleneck unless the control plane is self-service and well governed.

Alternatives

Alternative one is client-side service discovery with no gateway. It removes a hop, but clients must handle auth, routing, retries, and service changes, which is poor for public APIs and mobile apps.

Alternative two is a service mesh only. A mesh is excellent for east-west service-to-service traffic, mTLS, retries, and observability, but it does not fully replace a north-south edge gateway that handles public API products, partners, WAF, quotas, and client-facing transformations.

Alternative three is one backend-for-frontend per client. This is useful for complex aggregation and mobile-specific payloads, but it still benefits from a thinner gateway in front for TLS, authentication, rate limits, and telemetry.

When not to use this design

Do not introduce a heavy API Gateway for a small monolith, a few internal services, or a system where managed load balancers and service-level libraries are enough. Also avoid placing deep business workflows in a shared gateway; build a dedicated service when orchestration needs domain data, transactions, or independent releases.

Follow-up Questions

How do you keep route matching fast with thousands of routes?

Compile routes into deterministic data structures such as host maps and path tries. Do validation and conflict detection in the control plane. The data plane should perform local in-memory lookup, not scan all routes or call a route database.

What authentication should happen at the gateway versus in services?

The gateway should validate identity and enforce coarse route permissions such as scopes, tenant, and plan. Backend services should still enforce resource-level authorization because they understand domain ownership and business rules.

How should retries be configured?

Retries need short timeouts, a small max-attempt count, and a retry budget. Retry only safe operations or requests with idempotency support. Do not retry application-level failures or multiply load during incidents.

How do you propagate emergency credential revocation?

Use short token lifetimes, cached key rotation, and a fast deny-list channel to gateways. Normal config snapshots can handle routine changes, but emergency revocation needs faster propagation than a standard rollout window.

How do you prevent the gateway from becoming a monolith?

Keep filters generic and declarative, require ownership and review, limit plugin runtime resources, and move complex aggregation to backend-for-frontend services. The gateway should enforce cross-cutting platform policy, not own product workflows.

What happens if the control plane is down?

Existing traffic should continue using the last known good signed snapshot. New changes pause, stale-snapshot alerts fire, and rollback or emergency blocks use a separate minimal path if the organization requires it.

How do global quotas work across regions?

Use local buckets for low-latency burst handling and periodically reconcile against a shared global quota store. For strict quotas, route a tenant to a home region or use a strongly consistent counter, accepting higher latency and lower availability.

Company Variations

Amazon

Amazon interviewers often push on multi-tenant quotas, DynamoDB or Redis counter design, availability-zone isolation, operational alarms, and cost. Be ready to explain how the gateway fails when auth, rate limiting, or service discovery dependencies degrade.

Netflix

Netflix tends to focus on edge reliability, client diversity, backend-for-frontend aggregation, circuit breakers, adaptive retries, and observability. Discuss how route-level resilience keeps one failing service from harming the streaming experience.

Stripe

Stripe may frame this around partner APIs, idempotency, API keys, versioned API contracts, strict audit logs, rate limits by account and endpoint, and safe rollout of policy changes. Security and correctness matter as much as raw throughput.

Microsoft

Microsoft may emphasize enterprise identity, tenant isolation, Azure-style global front doors, compliance, private endpoints, admin governance, and integration with service discovery. Explain control-plane RBAC, auditability, and regional failover.

Interview Tips

Start by saying the gateway is a data-plane plus control-plane problem. Draw the request path first, then layer policy checks in the order they run. Keep repeating which decisions must be local on the hot path and which can happen asynchronously in the control plane. When asked to add features, decide whether they are cross-cutting gateway policy or business logic that belongs in a service.

What interviewers expect

  • Draw clients, edge load balancing, gateway data plane, service discovery, backend services, control plane, config store, and telemetry.
  • Explain route matching by host, path, method, and priority.
  • Describe JWT, API key, OAuth, and mTLS handling at a high level.
  • Quantify QPS, auth checks, rate-limit operations, logs, bandwidth, and instance count.
  • Discuss resilience policies including timeout, retry, circuit breaker, and load shedding.
  • Call out control-plane safety, versioning, rollout, and rollback.

Common mistakes

  • !Putting the control-plane database on the request path.
  • !Treating the gateway as a place for arbitrary business logic.
  • !Forgetting deterministic route precedence and conflict validation.
  • !Calling the identity provider synchronously for every request without caching.
  • !Retrying unsafe POST requests and creating duplicate side effects.
  • !Ignoring observability and making gateway failures indistinguishable from backend failures.

Red flags

  • ×No separation between data plane and control plane.
  • ×No plan for bad config rollback or canary rollout.
  • ×No rate limiting or quota model despite public APIs.
  • ×No auth revocation story or identity propagation model.
  • ×No circuit breakers, timeouts, or retry budgets.
  • ×No explanation of how the gateway avoids becoming a single point of failure.

Revision Notes

  • An API Gateway is the north-south edge for microservices: TLS, routing, auth, quotas, transforms, resilience, and observability.
  • Keep the data plane fast and local. It should use compiled route snapshots, in-memory policy state, cached keys, service discovery caches, and shared rate-limit stores.
  • Keep the control plane safe and auditable. It validates routes, compiles config, signs snapshots, canaries rollouts, and rolls back bad changes.
  • Route matching needs deterministic precedence: host, method, path type, and explicit priority. Ambiguity should be rejected before deployment.
  • JWT validation should usually be local with cached public keys. Opaque token introspection and API key lookup need caching and revocation strategy.
  • Rate limits require dimensions: IP, token, user, tenant, route, and region. Global quotas trade latency and availability for stricter correctness.
  • Timeouts, retries, circuit breakers, outlier detection, and backpressure protect services from retry storms and slow dependency collapse.
  • Gateway transformations and BFF aggregation are useful but should be bounded. Complex business workflows belong in owned services.
  • The gateway is a potential single point of failure, so use active-active regions, multi-zone fleets, last-known-good config, canary rollout, and blast-radius isolation.

Flashcards

Quiz

0/7 answered

  1. 1.Why is the control plane separated from the data plane?

  2. 2.Which route matching rule should be true in a robust gateway?

  3. 3.What is the best default way to validate JWTs at high QPS?

  4. 4.Given 5B requests per day, what is the approximate average QPS?

  5. 5.Which operation is safest for automatic gateway retries?

  6. 6.What should a gateway do when the control plane is unavailable?

  7. 7.What is a major risk of putting complex business workflows in gateway plugins?

Cheat Sheet

Goal: design a reliable edge gateway that routes, secures, shapes, protects, and observes traffic into a microservice platform.

Hot path: client to edge to regional load balancer to gateway data plane to service discovery to backend service. The data plane should use local compiled config and cached policy state.

Control plane: route authoring, conflict validation, policy templates, signed snapshots, config rollout, canarying, rollback, RBAC, and audit logs.

Routing: match host, path, method, headers, tenant, and priority. Reject ambiguous overlaps. Use compiled tries or generated matchers rather than scanning route lists.

Security: validate JWTs with cached keys, hash API keys, support OAuth introspection with caching, use mTLS where needed, strip spoofed identity headers, and enforce route scopes and tenant boundaries.

Rate limits: use per-IP, per-user, per-token, per-tenant, per-route, and per-plan dimensions. Combine local buckets for latency with shared counters for global quotas.

Resilience: enforce deadlines, timeouts, retry budgets, circuit breakers, outlier detection, connection pools, and backpressure. Retry only safe or idempotent operations.

Transforms and BFF: useful for version translation, header enrichment, response shaping, and small aggregations. Keep them bounded and move business workflows to owned services.

Observability: route-level request rate, p50 and p99 gateway overhead, upstream latency, auth failures, 429s, circuit breaker state, logs, audit events, and distributed traces.

Failure posture: if the control plane fails, serve last known good config. If a route rollout fails, rollback. If auth or rate-limit dependencies fail, apply explicit fail-open or fail-closed policies by route risk.

References