00:00

API Gateway vs Reverse Proxy

Last updated:

Every API gateway is built on a reverse proxy, but not every reverse proxy is an API gateway. A reverse proxy moves traffic to the right server. An API gateway also understands that traffic as API calls from consumers, and applies rules to each one: who is calling, how often, and which version of which service should answer.

This tutorial shows exactly what the gateway adds, with Nginx and Spring Cloud Gateway configurations side by side. For the pattern itself, see the API Gateway pattern.

1. What Are an API Gateway and a Reverse Proxy?

A reverse proxy is a server that forwards client requests to backend servers and returns their responses, commonly handling TLS, caching, compression and path-based routing.

An API gateway is a reverse proxy specialised for APIs. It is the single entry point for API clients and applies cross-cutting policies to each call: authentication and authorisation, rate limiting and quotas, request and response transformation, API versioning, aggregation of several service calls, and API analytics.

A useful way to put it in an interview: a reverse proxy knows where a request should go; an API gateway also knows who sent it and what they are allowed to do.

2. Architecture Comparison

API gateway compared with reverse proxy Top lane: a reverse proxy receives a request and routes it by host or path to a web app or an API, without knowing anything about the API consumer. Bottom lane: an API gateway processes each API call through a chain of policies, first authentication with a JWT, then a rate limit of 10 requests per second, then routing to the orders, users or payments service. REVERSE PROXY · ROUTES TRAFFIC Browser Reverse Proxyroutes by host / path Web app API API GATEWAY · POLICIES ON EVERY CALL Mobile app AuthJWT Rate limit10 req/s Routeby API Orders Users Payments
A reverse proxy routes traffic. An API gateway also applies API policies such as authentication and rate limits to every call.

3. How an API Call Flows Through a Gateway

A mobile app calls GET /api/orders/42 with an access token:

  1. Authenticate: the gateway validates the JWT signature, expiry and issuer. An invalid token gets 401 Unauthorized immediately.
  2. Rate limit: it checks the caller's token bucket. Too many calls get 429 Too Many Requests.
  3. Route: it matches /api/orders/** to the orders service and rewrites the path to /orders/42.
  4. Balance: it picks a healthy orders instance.
  5. Respond: it returns the response and records metrics per API and per consumer.

A plain reverse proxy would perform only the routing and balancing steps; it does not know who the caller is.

Request and response transformation

Gateways also adapt traffic between clients and services. A gateway can add a correlation ID header to every request, remove internal headers such as server versions from responses, rename a path when a service is reorganised, or translate a public REST call into an internal gRPC call. These changes keep clients stable while the services behind the gateway evolve.

4. Features an API Gateway Adds

  • Identity: OAuth 2.0 and JWT validation, API keys, and mutual TLS for partners.
  • Traffic policies: per-consumer rate limits, quotas and spike arrest; see the Rate Limiting pattern.
  • Transformation: header and path rewriting, protocol translation such as REST to gRPC, and response shaping.
  • Aggregation: one client call fans out to several services, which is useful for mobile clients.
  • Resilience: per-route timeouts, retries and circuit breakers.
  • API management: versioning, developer portals and usage analytics in managed gateways.

Kinds of API gateways

Gateways come in three forms. Libraries and frameworks such as Spring Cloud Gateway run as your own Java service and are configured in YAML or code. Self-hosted products such as Kong or Envoy-based gateways run as separate infrastructure. Managed cloud gateways such as AWS API Gateway, Azure API Management and Google Apigee are operated by the provider and add developer portals, billing and analytics. Choose by how much control, customisation and operational work your team wants.

5. Practical Implementation

Reverse proxy: Nginx path routing

nginx.conf
server {
    listen 443 ssl;
    server_name api.shop.example;
    ssl_certificate     /etc/nginx/certs/api.crt;
    ssl_certificate_key /etc/nginx/certs/api.key;

    location /api/orders/ { proxy_pass http://10.0.2.11:8080/orders/; }
    location /api/users/  { proxy_pass http://10.0.2.21:8080/users/; }
}

This routes and terminates TLS, but every caller is treated the same.

API gateway: Spring Cloud Gateway

The same routes, plus JWT validation, per-user rate limiting and load-balanced service discovery:

application.yml
spring:
  cloud:
    gateway:
      server:
        webflux:
          routes:
            - id: orders
              uri: lb://orders-service          # load-balanced across registered instances
              predicates:
                - Path=/api/orders/**
              filters:
                - StripPrefix=1                  # /api/orders/42 -> /orders/42
                - name: RequestRateLimiter
                  args:
                    redis-rate-limiter.replenishRate: 10
                    redis-rate-limiter.burstCapacity: 20
                    key-resolver: "#{@userKeyResolver}"
            - id: users
              uri: lb://users-service
              predicates:
                - Path=/api/users/**
              filters:
                - StripPrefix=1
  security:
    oauth2:
      resourceserver:
        jwt:
          issuer-uri: https://auth.example.com/realms/shop   # validate JWT access tokens
GatewayConfig.java
package com.example.gateway;

import java.security.Principal;

import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class GatewayConfig {

    /**
     * Rate-limit per authenticated user. The principal comes from the validated JWT,
     * so a client cannot pick its own key by sending a header.
     */
    @Bean
    KeyResolver userKeyResolver() {
        return exchange -> exchange.getPrincipal().map(Principal::getName);
    }
}
Note: These property names are for Spring Cloud 2025.0 and later, which use the spring-cloud-starter-gateway-server-webflux starter. Older releases use spring.cloud.gateway.routes without server.webflux. The rate limiter also needs the reactive Redis starter, and JWT validation needs the OAuth2 resource server starter.

6. Advantages and Disadvantages

Reverse proxyAPI gateway
StrengthFast, simple, general purposeCentral API security and policies
Knows the callerNoYes (token, key or certificate)
ComplexityLowHigher; more configuration and code
RiskLittle API protectionCan become a bottleneck or a "god service" if it holds business logic

7. API Gateway vs Reverse Proxy Comparison

AspectReverse proxyAPI gateway
FocusAny HTTP trafficAPI calls from consumers
AuthenticationBasic, if anyOAuth 2.0, JWT, API keys, mTLS
Rate limitingPer IP, simplePer consumer, plan or API
TransformationHeaders and pathsPayloads, protocols, aggregation
ObservabilityAccess logsPer-API and per-consumer analytics
ExamplesNginx, HAProxy, CaddySpring Cloud Gateway, Kong, AWS API Gateway, Apigee

8. Real-World Use Cases

  • Reverse proxy: serving a website, a single application, or static assets with TLS and caching.
  • API gateway: a public API with partner keys and quotas; a microservices backend for mobile apps; a backend-for-frontend layer.
  • Both: an Nginx or cloud reverse proxy at the edge for TLS and static content, forwarding /api traffic to a Spring Cloud Gateway cluster.
  • Backend for frontend (BFF): a small gateway per client type, such as one for the mobile app and one for the web app, shapes responses for each screen.

Many teams start with a reverse proxy and add a gateway only when the number of APIs, consumers or security rules grows. That is a sensible order: the gateway brings real value, but also more configuration to own.

9. Best Practices

  • Keep business logic out of the gateway: limit it to cross-cutting concerns.
  • Validate tokens at the gateway, authorise in services: the services still check what the user may do.
  • Scale the gateway horizontally and keep it stateless; store rate-limit counters in Redis.
  • Set per-route timeouts and circuit breakers so one slow service cannot exhaust gateway resources.
  • Follow API security guidelines: see API Security Best Practices.
  • Return consistent error bodies for 401, 403 and 429 so clients can handle them in one place.

Migrating from a reverse proxy to a gateway

  1. Keep the existing reverse proxy for TLS and static content.
  2. Point the /api paths to the new gateway one route at a time.
  3. Move authentication to the gateway and remove duplicated checks from the proxy.
  4. Add per-consumer rate limits and monitoring once traffic flows through the gateway.

This incremental path avoids a risky big-bang switch and lets you compare latency and error rates after each step.

10. Summary

  • An API gateway is a reverse proxy specialised for APIs.
  • A reverse proxy routes traffic; a gateway also knows the caller and applies policies.
  • Gateway features: authentication, rate limits, transformation, aggregation and analytics.
  • Spring Cloud Gateway configures routes, predicates and filters in YAML or Java.
  • Use a reverse proxy for websites and simple routing, and a gateway for managed APIs.

Next, see how a gateway relates to load balancing in API Gateway vs Load Balancer.