DBRaven
Pattern · scaling

API Gateway

mature

Summary

Provide a single, managed entry point for all client requests that handles routing, authentication, rate limiting, protocol translation, and observability : decoupling clients from the internal service topology.

Problem

Clients coupling directly to individual services creates fragile integrations that require client changes for every service topology change, and forces each service to independently implement authentication, rate limiting, and observability.

Description

Without an API gateway, each client must know the address of every service, authenticate independently, and handle rate limiting errors from multiple sources. Adding a new service or changing an existing one requires client changes. Observability requires per-service instrumentation.

An API gateway is a reverse proxy that sits at the edge of the system and centralises these cross-cutting concerns. Clients connect to a single endpoint. The gateway resolves routing (path /orders → order-service:8080, path /payments → payment-service:8081), verifies JWT tokens or API keys before forwarding requests, enforces rate limits (e.g., 1,000 req/min per API key from a Redis counter), translates protocols (REST client → gRPC backend), and emits standardised access logs and metrics for every request.

Rate limit state requires shared storage accessible to all gateway replicas; Redis is the standard choice (INCR + EXPIRE on a per-key counter). A per- replica in-memory counter allows clients to exceed the limit by a factor of (N replicas × limit) before being rejected: unacceptable for enforcement.

An API gateway is a potential single point of failure: all traffic flows through it. High-availability deployment (minimum 2 replicas, preferably 3, behind a load balancer) is mandatory. The gateway must be stateless so that any replica can handle any request; state (sessions, rate limit counters) must be externalised to Redis or a distributed store.

As traffic grows, the gateway can become a throughput bottleneck. Horizontal scaling is straightforward (stateless + externalised state), but each gateway replica adds a network hop. For latency-sensitive paths, direct service-to- service communication (service mesh) is preferred over gateway routing.

Tradeoffs

Client decoupling
+0.9

Clients are fully decoupled from internal service topology

Cross-cutting concerns
+0.8

Auth, rate limiting, and observability are centralised and consistent

Single point of failure risk
-0.7

All traffic routes through the gateway; outage is total availability loss

Latency
-0.3

Additional network hop adds 0.5–2ms per request

Operational complexity
-0.4

Gateway configuration, HA deployment, and Redis dependency add ops surface

Throughput ceiling
-0.3

Single gateway tier can become bottleneck under extreme load

When to use

Multiple client types (web, mobile, third-party) access the same backend services

A gateway provides a single contract; internal service changes are hidden from clients; client-specific APIs (BFF) can be layered on top

Authentication and rate limiting must be enforced uniformly across all endpoints

Centralised enforcement is more reliable than per-service implementation where gaps or inconsistencies can occur

Service topology changes frequently

Routing changes in the gateway require no client changes; services can be split, merged, or renamed without breaking external contracts

Edge observability (request rates, error rates, latency per route) is required

The gateway emits consistent metrics for all traffic before it reaches any service, providing a complete picture of external load

When not to use

All clients are internal services with direct service discovery

Service-to-service traffic in a mesh is better handled by a sidecar proxy (Envoy, Linkerd) than an API gateway; gateway adds unnecessary latency

Latency budget is extremely tight (<1ms)

Each gateway hop adds 0.5–2ms of network latency; for sub-millisecond SLAs, direct service communication is required

System has a single service with no anticipated growth

A reverse proxy (nginx, HAProxy) is sufficient; a full API gateway is over-engineered for a single-service deployment

Operational Requirements

mandatory

Deploy minimum 2 gateway replicas behind a load balancer

A single gateway replica is a single point of failure; all traffic is lost on restart or crash; minimum 2 replicas with health-check-based routing

mandatory

Externalise rate limit state to Redis with appropriate key expiry

Per-replica in-memory counters allow limit bypass proportional to replica count; shared Redis counter is required for accurate enforcement

mandatory

Monitor gateway error rate, latency p99, and throughput independently

Gateway metrics are the first signal for external-facing degradation; gateway latency increase often indicates downstream service problems

recommended

Implement health checks and circuit breakers per upstream service

A gateway that continues routing to a failed upstream will propagate errors to all clients; health-check-based routing removes failed upstreams

Characteristics

Scales on
readconnections
Implementation complexitymedium
Operational complexitymedium
Scaling ceilingGateway becomes a throughput bottleneck when handling >100,000 req/second per replica on CPU-intensive operations (JWT verification, TLS termination). Horizontal scaling is straightforward but each replica requires Redis connectivity for rate limit counters. TLS termination CPU cost dominates at high throughput: hardware offload or session resumption reduces this. At very high scale, purpose-built gateways (Kong, AWS API Gateway, Envoy) are preferred over application-code gateways.

Technologies

Canonical

redispostgresql

Alternatives

kongnginxenvoyaws api gatewaytraefik

Relationships

Evolves to

strangler fig

Complements

circuit breakerbulkhead isolationstrangler fig

Basis

Universally deployed pattern with well-understood characteristics; single-point-of-failure risk and latency overhead are real and must be addressed

Related Architecture Knowledge

Outbound: this entity affects

ComplementsPattern
circuit breaker
Grounded

API gateways are the natural enforcement point for circuit breakers: the gateway intercepts all inbound requests, tracks per-service error rates, and can open circuits to specific backend services while returning cached responses or 503s to callers: without any changes to individual service code.

Tradeoffs

  • ·Gateway-level circuit breaking is coarser-grained than per-call circuit breaking in application code
  • ·A centralized gateway is itself a potential single point of failure: requires high-availability deployment
  • ·Gateway circuit breakers may not capture partial failures within a service (e.g., only one endpoint degraded)
Full relationship →

Inbound: affects this entity

ComplementsPattern
rate limiting
Grounded

API gateways are the standard enforcement point for rate limiting; rate limiting rules configured on the gateway apply uniformly to all callers without code changes in downstream services.

Full relationship →

Used In Architecture Scenarios

API Gateway Platformhigh

Multi-Tenant SaaS

A multi-tenant API gateway providing authentication, distributed rate limiting, request routing, payload transformation, and per-tenant usage analytics for API publishers. The hot path: authentication check, rate limit evaluation, and routing decision: must complete in under 1ms using Redis-only data structures to avoid proxying latency dominating upstream service response time. PostgreSQL stores tenant configuration, subscription plans, and API key definitions. Kafka receives API usage events for downstream billing and analytics. Configuration changes (rate limit updates, routing rule edits) must propagate to all gateway replicas without restart.

Developer Tools Platformhigh

Multi-Tenant SaaS

A multi-tenant developer tooling platform providing CI/CD pipeline execution, log aggregation, code analysis, and dependency scanning across isolated tenant organizations. Tenant isolation is the primary correctness constraint: a security boundary violation between tenants is a critical incident, not a performance event. PostgreSQL row-level security enforces data isolation; Redis manages job queues and distributed locks; Elasticsearch indexes pipeline log output for search; Kafka delivers webhook events to tenant-registered endpoints; MinIO stores pipeline artifacts. Resource quota enforcement prevents any single tenant's burst from affecting others.

Two-Sided Marketplace Platformexpert

Marketplace Platform

A two-sided marketplace architecture serving buyers, sellers, listings, transactions, search, and notifications from a shared infrastructure, where multiple independent domains must coordinate without tight coupling. Event sourcing captures every state transition; the saga pattern orchestrates multi-step transactions (create order, reserve inventory, charge payment, notify seller) with compensating transactions for partial failures. Kafka decouples domain event publication from consumption; RabbitMQ handles notification fanout; Elasticsearch serves listing search; Redis caches listing display and session state.