A proxy is an intermediary that forwards traffic on someone else's behalf. A forward proxy acts for clients (hiding and controlling them), while a reverse proxy acts for servers (hiding, protecting and accelerating them). An API gateway is a reverse proxy specialized as the front door to a set of APIs or microservices, handling routing, authentication, rate limiting and request shaping so that individual services don't have to.
Think of it like
Assistants and receptionists
A forward proxy is your personal assistant making calls for you: the person called only sees the assistant's number. A reverse proxy is a company receptionist: callers dial one main number and get routed to the right department without ever learning internal extensions. An API gateway is a receptionist who also checks visitor badges, enforces visiting hours, and can collect answers from three departments into one reply.
Forward vs reverse proxy
Both kinds of proxy sit in the middle of an HTTP conversation and can inspect, modify, cache or block it. The difference is whose side they are on and who configures them. Press play on the end-to-end flow to see a request pass through both.
Forward proxy
- Acts on behalf of clients; clients know about it and are configured to use it
- Hides client identities from destination servers
- Uses: corporate egress filtering, malware scanning, shared caching, compliance logging, bypassing geo-restrictions
- Examples: Squid, Zscaler and other secure web gateways
Reverse proxy
- Acts on behalf of servers; clients usually don't know it exists
- Hides server topology; only the proxy is publicly reachable
- Uses: load balancing, TLS termination, caching, compression, WAF
- Examples: NGINX, HAProxy, Envoy, Traefik, Caddy, Cloudflare
What a reverse proxy does
- TLS termination
- Decrypt HTTPS once at the edge so app servers deal with plain HTTP, and certificates live in one place.
- Load balancing
- Spread requests across backends with health checks. See Load Balancing.
- Caching
- Store responses (
proxy_cache) so repeated requests never reach the app. Even 1–5 s of "micro-caching" absorbs huge spikes. - Compression
- gzip or Brotli responses once at the proxy instead of in every service.
- Security
- Hide internal IPs, cap request sizes, filter bad requests (WAF rules), and block abusive clients.
- Connection management
- Buffer slow clients so app threads aren't tied up (which also blunts slowloris attacks), and reuse keep-alive connections to backends.
- Static files
- Serve images, CSS and JS straight from disk, never touching the application.
- Header hygiene
- Add
X-Forwarded-For,X-Forwarded-Protoand request IDs; strip internal headers from responses.
# Pool of application servers
upstream app_backend {
least_conn;
server 10.0.2.11:8080 max_fails=3 fail_timeout=10s;
server 10.0.2.12:8080 max_fails=3 fail_timeout=10s;
keepalive 32; # reuse upstream connections
}
# Response cache: 10 MB of keys in shared memory, up to 1 GB on disk
proxy_cache_path /var/cache/nginx keys_zone=api_cache:10m max_size=1g inactive=10m;
# Rate limit: 10 requests/second per client IP
limit_req_zone $binary_remote_addr zone=per_ip:10m rate=10r/s;
server {
listen 80;
server_name api.example.com;
return 301 https://$host$request_uri; # force HTTPS
}
server {
listen 443 ssl;
http2 on;
server_name api.example.com;
ssl_certificate /etc/nginx/certs/api.example.com.pem;
ssl_certificate_key /etc/nginx/certs/api.example.com.key;
gzip on;
gzip_types application/json text/css application/javascript;
client_max_body_size 5m;
location /static/ {
root /var/www; # served from disk, never hits the app
expires 30d;
}
location /api/ {
limit_req zone=per_ip burst=20 nodelay;
proxy_pass http://app_backend;
proxy_http_version 1.1;
proxy_set_header Connection ""; # required for upstream keepalive
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_connect_timeout 2s;
proxy_read_timeout 10s;
proxy_cache api_cache;
proxy_cache_valid 200 30s;
proxy_cache_use_stale error timeout updating; # serve stale if the app is down
add_header X-Cache-Status $upstream_cache_status;
}
}API gateways
In a microservices system, clients would otherwise need to know dozens of service addresses, and every service would reimplement authentication, rate limiting, logging and CORS. An API gateway gives clients one entry point and centralizes those cross-cutting concerns, so services can focus on business logic. See Monoliths vs Microservices for why the services exist in the first place.
| Responsibility | What the gateway does | Example |
|---|---|---|
| Routing | Map host, path, method or version to a service | /v1/orders/... → order-service |
| Authentication | Validate JWTs, API keys or OAuth tokens; pass the identity downstream | Reject unauthenticated calls before they reach any service |
| Coarse authorization | Check scopes or roles per route | orders:read required for GET /v1/orders |
| Rate limiting and quotas | Per API key, user or IP; tiered plans | 1,000 requests/min on the free tier |
| Aggregation / BFF | Fan out to several services and merge results | One /home call instead of five |
| Protocol translation | REST ↔ gRPC, HTTP ↔ WebSocket, legacy SOAP | gRPC-JSON transcoding |
| Transformation and versioning | Rename fields, add or strip headers, map v1 to v2 | Keep old mobile clients working |
| Resilience | Timeouts, retries, circuit breaking, response caching | See Resilience Patterns |
| Observability | Access logs, metrics, distributed-trace headers | See Observability |
Backend for frontend (BFF)
A single general-purpose gateway tends to serve every client badly: mobile wants small payloads, the web app wants rich ones, partners want stable versioned APIs. The BFF pattern gives each client type its own thin gateway layer, owned by the team that builds that client.
One shared gateway
- One place to configure auth, quotas and routing
- Simple when clients have similar needs
- Becomes a bottleneck when every team needs changes in it
A BFF per client
- Web BFF, iOS/Android BFF, partner API, each tailored to its client
- Frontend teams ship without waiting on a central team
- Some duplication across BFFs; shared concerns stay in an edge gateway in front
Gateway, load balancer, reverse proxy, service mesh
| Component | Primary job | Traffic direction | Typical tools |
|---|---|---|---|
| Reverse proxy | Front servers: TLS, caching, compression, static files | North-south (into the system) | NGINX, HAProxy, Caddy |
| Load balancer | Spread load and remove unhealthy servers | North-south, sometimes internal | AWS ALB/NLB, HAProxy |
| API gateway | API management: auth, quotas, routing, transformation, developer keys | North-south, at the edge | Kong, AWS API Gateway, Apigee, Envoy Gateway |
| Service mesh | Service-to-service: mTLS, retries, traffic shifting, telemetry | East-west (between services) | Istio, Linkerd, Consul |
A service mesh pushes proxy features into the network between services. A sidecar proxy (usually Envoy) runs next to every service instance and intercepts its inbound and outbound calls, while a control plane (such as Istio's istiod) distributes configuration and certificates. Services get mutual TLS, retries, timeouts, canary traffic splitting and uniform metrics without code changes. The cost is an extra proxy hop on every call and a sizable system to operate; newer "ambient" and eBPF-based meshes reduce the per-pod sidecars. See Service Discovery & Service Mesh.
Pitfalls and how to avoid them
Single point of failure
- Every request passes through the proxy or gateway
- Run several stateless instances across zones behind an L4 balancer
- Keep their state (rate-limit counters, sessions) in a replicated store
Added latency
- Each hop adds parsing, TLS and queueing time (often around a millisecond, more with heavy plugins)
- Reuse upstream connections; cache JWKS keys and auth decisions
- Measure the gateway's own p99, not just the services'
Gateway bloat
- Business rules creep into gateway scripts and plugins
- It becomes a shared monolith every team must change and redeploy
- Keep it to cross-cutting concerns: "smart endpoints, dumb pipes"
Implementation
Route by path prefix, reject unauthenticated calls and forward with `X-Forwarded-For`. For brevity the token check only tests presence; a real gateway verifies the JWT signature and expiry.
import http from "node:http";
const routes: Record<string, { host: string; port: number }> = {
"/users/": { host: "10.0.2.11", port: 8080 },
"/orders/": { host: "10.0.2.21", port: 8080 },
};
const server = http.createServer((req, res) => {
const path = req.url ?? "/";
const prefix = Object.keys(routes).find((p) => path.startsWith(p));
if (!prefix) {
res.writeHead(404).end("No route");
return;
}
if (!req.headers.authorization?.startsWith("Bearer ")) {
res.writeHead(401).end("Missing token");
return;
}
const { host, port } = routes[prefix];
const forwardedFor = [req.headers["x-forwarded-for"], req.socket.remoteAddress]
.filter(Boolean)
.join(", ");
const upstream = http.request(
{
host,
port,
method: req.method,
path,
headers: { ...req.headers, "x-forwarded-for": forwardedFor },
timeout: 5000,
},
(upstreamRes) => {
res.writeHead(upstreamRes.statusCode ?? 502, upstreamRes.headers);
upstreamRes.pipe(res);
},
);
upstream.on("timeout", () => upstream.destroy(new Error("upstream timeout")));
upstream.on("error", () => {
if (!res.headersSent) res.writeHead(502);
res.end("Bad gateway");
});
req.pipe(upstream);
});
server.listen(8000);Key takeaways
- Forward proxies act for clients (egress control, anonymity); reverse proxies act for servers (protection, acceleration).
- Reverse proxies terminate TLS, balance load, cache, compress, buffer slow clients and hide internal topology.
- API gateways centralize cross-cutting API concerns: routing, authentication, rate limiting, aggregation and protocol translation.
- The BFF pattern gives each client type its own tailored gateway layer.
- Service meshes apply proxy features to east-west, service-to-service traffic via sidecars.
- Keep gateways redundant, fast and free of business logic.
Common pitfalls
- Running a single gateway instance, so the front door becomes the single point of failure.
- Letting business logic accumulate in gateway plugins until it becomes a shared monolith.
- Trusting client-supplied
X-Forwarded-Foror identity headers. - Leaving services reachable directly, bypassing the gateway's authentication.
- Stacking proxy after proxy (CDN → LB → gateway → sidecar) without measuring the latency each one adds.
Interview tips
- Be precise about direction: forward proxies serve clients, reverse proxies serve servers.
- When you add an API gateway, list its concrete responsibilities rather than saying it "handles things".
- Mention BFF when there are multiple client types, and service mesh when the question is about service-to-service security or traffic shifting.
Real-world applications
- NGINX or Envoy in front of web applications.
- AWS API Gateway in front of Lambda functions.
- Kong or Apigee for public partner APIs with keys and quotas.
- Corporate secure web gateways filtering employee traffic.
- Istio or Linkerd for mTLS between microservices.
Test yourself
Which component hides the client's IP address from the destination server?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.