Skip to content

Forward Proxy vs Reverse Proxy vs API Gateway

Basic 42 min read Part 3 of 18

What forward proxies, reverse proxies, load balancers and API gateways each do, how Nginx's event-driven model works, and how to combine them.

Summary#

A proxy is a server that sits in the middle of a connection. A forward proxy acts for clients: it sends their requests out to the internet (corporate filtering, privacy, egress control). A reverse proxy acts for servers: clients talk to it as if it were the site, and it forwards requests to backends while adding TLS termination, compression, caching and protection. A load balancer is a reverse proxy focused on spreading traffic; an API gateway is a reverse proxy focused on API concerns like auth and rate limits. In practice one product (Nginx, Envoy) can play several roles.

Why It Exists#

Companies want to control what their machines reach on the internet; services want one hardened front door instead of exposing every backend. Proxies provide that middle layer without changing clients or applications. The terms are often confused because the same software does all of them. This page separates the roles; Load Balancing covered the traffic-spreading role in depth.

How It Works#

What a proxy is, precisely#

A proxy terminates one connection and opens another. The client's TCP connection ends at the proxy, and the proxy makes its own connection onward. That one fact explains most of what proxies can do (read, change, cache, block or reroute traffic) and most of their costs (an extra hop, an extra thing to scale, and a place where the original client's identity gets lost).

Two questions classify any proxy:

  1. Whom does it act for? A forward proxy acts for a group of clients and reaches out to many servers. A reverse proxy acts for a group of servers and faces many clients.
  2. Does the client know it is there? An explicit proxy is configured on the client: the browser or app is told "send everything to proxy.corp:3128". A transparent (intercepting) proxy sits on the network path and grabs traffic without the client being configured. A reverse proxy is always "transparent" from the client's point of view: the client believes the proxy is the website.

How clients find an explicit forward proxy. Browsers and operating systems accept a fixed proxy address, a PAC file (Proxy Auto-Config: a small script that returns which proxy to use for each URL), or WPAD discovery on corporate networks. Command-line tools and most HTTP libraries read the HTTP_PROXY, HTTPS_PROXY and NO_PROXY environment variables. Forgetting NO_PROXY for internal hosts is a classic way to send internal traffic out through a corporate proxy and break it.

How HTTPS goes through a forward proxy. A forward proxy cannot read HTTPS without breaking encryption, so the client asks it to open a raw tunnel with the HTTP CONNECT method. The proxy checks the destination against its policy, connects, replies "200 Connection established", and then just copies encrypted bytes both ways. It sees the destination host name and port, and how many bytes flow, but not the URLs or content.

Hop-by-hop vs end-to-end headers. HTTP separates headers that describe one connection (hop-by-hop: Connection, Keep-Alive, Proxy-Authorization, TE, Upgrade, Transfer-Encoding) from headers meant for the final recipient (end-to-end: Authorization, Cache-Control, Content-Type). A correct proxy removes hop-by-hop headers before forwarding and may add its own: Via (which proxies the message passed through), X-Forwarded-For, X-Forwarded-Proto and X-Forwarded-Host, or the standard Forwarded header. Getting this wrong causes subtle bugs, and disagreements between proxies about where a message ends are the root of request smuggling (see HTTP and HTTPS).

HTTP proxies vs SOCKS proxies. An HTTP proxy understands HTTP and can cache, filter by URL and add headers (for HTTPS only by host, via CONNECT). A SOCKS5 proxy works one level lower: it relays arbitrary TCP connections (and UDP associations) after a short handshake, with no understanding of the protocol inside. SSH's dynamic port forwarding (ssh -D) creates a SOCKS proxy, which is a common way to reach a private network for debugging.

HTTP proxySOCKS5 proxy
ProtocolsHTTP, plus HTTPS tunnels via CONNECTAny TCP, plus UDP
Can cache or filter by URL?Yes for plain HTTPNo
Sees content?Plain HTTP onlyNo
Typical useCorporate web access, egress controlSSH tunnels, generic relays, some privacy tools

Forward proxy uses#

A forward proxy is configured on the client side (browser settings, OS settings, or a transparent network rule).

  • Access control and filtering: block categories of sites, enforce company policy.
  • Egress control and auditing: servers in a private network can only reach approved external APIs through a proxy that logs every call.
  • Privacy: the destination sees the proxy's IP, not the client's.
  • Caching shared downloads: package mirrors and OS updates fetched once for many machines.

Forward proxies in depth#

Corporate filtering. A company routes employee web traffic through a proxy (Zscaler, Netskope, Squid, Blue Coat, or a cloud "secure web gateway"). The proxy blocks site categories, scans downloads for malware and logs access. For HTTPS it can only see host names, unless the company does TLS inspection: the proxy decrypts traffic using a company root certificate that every managed laptop is set to trust, inspects it, and re-encrypts it. This gives visibility but has real costs. The proxy now holds plaintext of everything, including banking and health traffic, so it becomes a high-value target. Apps that pin their certificates break. And the proxy's own TLS handling must be as careful as the browser's, which it often is not.

Egress control for servers. In a production network, servers should not be able to reach arbitrary internet hosts. An egress proxy (or an egress gateway in a service mesh) allows only approved destinations, such as the payment provider, the email API and the package mirror, and logs every call. This limits the damage of a compromised server, which can no longer send data to an attacker's host or download tools freely.

Egress proxies are also a defence against server-side request forgery (SSRF), where an attacker tricks a server into making a request on their behalf, for example "fetch this image URL" pointing at an internal address. A particularly dangerous target is the cloud instance metadata service at 169.254.169.254, which hands out temporary credentials. The 2019 Capital One breach was widely reported to involve SSRF against this metadata service through a misconfigured web application firewall. Defences include sending all user-supplied URL fetches through a proxy that blocks private and link-local ranges, and requiring session tokens for metadata access (AWS IMDSv2).

Stable source IPs. Partners often say "we will only accept calls from these IPs". If your services run on hundreds of autoscaled instances, their IPs keep changing. Sending outbound calls through a small set of egress proxies or a NAT gateway with fixed Elastic IPs gives the partner a stable list. A NAT gateway changes addresses only; a proxy can also enforce rules and log by URL or host.

Caching proxies for shared downloads. Build farms and server fleets download the same packages, container images and OS updates again and again. A caching forward proxy or a pull-through registry (Squid, apt-cacher-ng, Artifactory, Nexus, or a container registry mirror) fetches each artifact once and serves it locally. This saves bandwidth and speeds up builds, and it keeps builds working when the public registry is slow or down.

Privacy and anonymity. A forward proxy hides the client's IP from the destination: the site sees the proxy's address. A VPN does the same for all traffic from a device, encrypting it to the VPN server. Tor chains several proxies so that no single relay knows both who you are and what you are visiting. A plain proxy is not anonymous from the proxy operator, who sees everything.

The proxy becomes critical infrastructure. Once all outbound traffic goes through a forward proxy, it is a single point of failure for everything that calls out. Run it as a redundant pool behind an internal load balancer, give it its own monitoring, and decide what happens if it is down. For most systems, failing closed (no outbound calls) is safer than silently bypassing policy.

Proxy vs NAT gateway vs VPN#

Three tools change where outbound traffic appears to come from, and they are often confused:

Forward proxyNAT gatewayVPN
LayerApplication (HTTP) or session (SOCKS)Network (IP and port rewriting)Network, inside an encrypted tunnel
Client configurationUsually needed (proxy settings or env variables)None, it is the default routeVPN client or site-to-site config
Understands requests?Yes, can filter by host or URL and log themNo, sees only addresses and portsNo
Encrypts traffic?No, beyond the client's own TLSNoYes, between client and VPN server
Typical usePolicy, auditing, caching, SSRF defenceGiving private servers internet access with fixed public IPsJoining a remote device or office to a private network

A NAT gateway is the simplest way to give private servers outbound internet access, and it is enough when you only need fixed source IPs. Choose a forward proxy when you also need to decide which destinations are allowed and to keep a record of them. Choose a VPN when the goal is to place a remote machine inside a private network, not to control its internet access. Large platforms often combine all three: a NAT gateway for general egress, an egress proxy for sensitive destinations, and VPN or private links to partners and offices.

Reverse proxy uses#

A reverse proxy is deployed with the servers; clients usually do not know it exists.

  • TLS termination: one place holds certificates and decrypts traffic. See HTTP and HTTPS.
  • Compression: gzip or Brotli responses, saving bandwidth for slow clients.
  • Caching: serve repeated responses without hitting backends (a CDN is a global network of reverse proxies; see CDN).
  • Protection: hide backend addresses, absorb slow clients (buffering), enforce request size limits, block bad traffic, add a WAF.
  • Routing and load balancing: send /api to one service and / to another, and spread across instances.
  • Static file serving: serve images and JavaScript directly, leaving app servers for dynamic work.

Reverse proxies in depth#

A reverse proxy gives a set of internal services one public face. Clients only ever see the proxy's address and its responses. That is useful even with a single backend server, which is the clearest difference from a load balancer: you add a load balancer because you have several servers; you add a reverse proxy because of what it does at the front door.

Security. The proxy hides the backend's real addresses, software versions and internal error pages. It can block IP ranges, cap the number of connections and requests per client, reject oversized bodies and headers, normalise odd requests, and run a web application firewall (WAF) that matches known attack patterns such as SQL injection probes. Because backends accept traffic only from the proxy, they can sit in private subnets with no public IP at all.

Scalability and flexibility. Since clients see only the proxy, you can add, remove, resize, rename or move backends without anyone noticing. You can split one monolith into services path by path (/search first, then /orders) behind the same domain, a pattern often called the strangler fig migration. You can also switch traffic between blue and green deployments in one config change.

TLS termination. The proxy decrypts HTTPS once, so backends skip that CPU work and you do not need an X.509 certificate on every server. Details, including re-encryption and passthrough, are in Load Balancing.

Compression. The proxy compresses text responses (HTML, CSS, JavaScript, JSON) before they cross the slow part of the network. gzip typically shrinks text to about a quarter to a third of its size; Brotli usually does 15-25% better than gzip on the same text, at more CPU for high levels. Compress only what benefits: JPEG, PNG, video and zip files are already compressed, and recompressing them wastes CPU for nothing. For static assets, compress once at build time and let the proxy serve the precompressed file (gzip_static, brotli_static).

Caching. A reverse proxy can store responses and answer repeats without touching the backend. Even tiny lifetimes help. Worked example of micro-caching: a product page gets 5,000 requests per second, all for the same 200 popular products. Cache each page for 1 second at each of 4 proxy nodes, and the backend sees at most 200 products x 4 nodes = 800 requests per second instead of 5,000, while users see data at most 1 second old. Add request collapsing (proxy_cache_lock in Nginx), so that when a cache entry expires only one request goes to the backend while the others wait for its answer, and add stale-while-revalidate and stale-if-error, so the proxy serves the old copy while refreshing or when the backend is failing. The danger is caching something personal: the cache key must include anything the response varies on, and responses with cookies or Authorization should not be shared unless you are sure. A CDN is the same idea spread across hundreds of cities (see CDN).

Static content. HTML, CSS, JavaScript, images, fonts and video segments can be served straight from the proxy's disk or memory. Nginx uses the sendfile system call to copy file data from the page cache to the socket inside the kernel, without passing it through user space. Application servers are much slower at this and are better spent on dynamic work.

Buffering slow clients. This is the least obvious and one of the most valuable jobs. Suppose an app server has 64 worker threads, and a phone on a poor network downloads a 1 MB response at 50 KB/s. Without a proxy, one worker thread is stuck for 20 seconds feeding that phone. Sixty-four such phones freeze the whole server. With a reverse proxy in front, the app hands the 1 MB to the proxy over the local network in a few milliseconds and is free again; the proxy, which can hold thousands of slow connections cheaply, trickles the bytes out. The same applies to uploads: the proxy can read a whole slow upload before passing it on in one quick burst. This is why Ruby, Python and PHP app servers are almost always deployed behind Nginx or a similar proxy.

Disadvantages. A reverse proxy adds complexity: another config to manage, another hop, another place for bugs. A single reverse proxy is also a single point of failure, so production setups run at least two behind a floating IP, an L4 load balancer or DNS, and that adds more complexity again.

Where rate limiting and auth live: in the app, in a service, or at the edge#

Cross-cutting checks such as rate limiting and authentication can run in three places. The rate-limiter case shows the trade-offs well.

  • In-process. Each app server keeps its own counters in memory. It is fast and has no dependencies, but each server sees only its share of traffic. With a limit of 200 requests per minute and 4 servers behind round robin, a user can send 200 to each server, 800 in total, before anyone objects. If the balancer's distribution changes, the effective limit changes too. It only works with one server or when a limit that is off by a factor of N is acceptable.
  • A dedicated rate-limit service. App servers ask a central service "may user 42 make this call?" before doing work. Limits are exact and global, and the app can pass rich context such as subscription tier or account status. The price is an extra network round trip on every request (a few milliseconds), a new critical dependency, and a hard choice for when it is down: fail open (allow everything and risk overload) or fail closed (reject everything and cause an outage).
  • At the gateway or load balancer. The check runs at the very edge, before any app server sees the request, and rejected requests get a 429 immediately. Like a doorman, it turns trouble away before it gets inside, so backends spend nothing on blocked traffic. It is the most common production choice. The limits are about context and state. The gateway only knows what is in the request: path, headers, IP, API key and token claims. A rule like "premium users get 10x" only works if the tier is in the token. Counters must be shared across gateway nodes, usually in Redis, which brings back the question of what to do when Redis is slow.

At the edge, the limiter must decide who the client is, using only the request:

  • User ID, taken from a validated JWT or session in the Authorization header. This is the best key for logged-in APIs.
  • IP address, read from X-Forwarded-For as set by your own outer proxy. Good for anonymous traffic, but many users can share one IP behind NAT or a corporate firewall.
  • API key, from a header such as X-API-Key. Standard for developer APIs.

Full algorithms and failure handling are in Rate Limiting.

API gateways in depth#

An API gateway is a reverse proxy specialised for APIs consumed by many clients: mobile apps, web front ends, partners and internal teams. Typical jobs:

  • Authentication: validate JWTs, OAuth tokens or API keys once at the edge, and pass a trusted identity header to services, so each service does not reimplement it. See Authentication and Authorization.
  • Quotas and rate limits per key, per user or per plan ("free tier: 1,000 calls a day").
  • Routing and versioning: /v1/orders to the old service, /v2/orders to the new one.
  • Transformation: rename fields, convert JSON to gRPC or SOAP for legacy backends, add or strip headers.
  • Aggregation: one client call fans out to several services and returns a combined response, saving mobile round trips. When a gateway does this per client type, it is called a backend for frontend (BFF).
  • Developer experience: key issuing, usage analytics, a developer portal and API documentation.

Common choices include Kong, Tyk, Apigee, AWS API Gateway, Azure API Management and Envoy-based gateways. Managed gateways bring their own constraints, such as request size limits, integration timeouts (AWS API Gateway's REST APIs, for example, have a default integration timeout of 29 seconds) and per-million-request pricing that adds up at high volume.

The main risk is the god gateway: business rules creep into gateway scripts and plugins until the gateway becomes a fragile, hard-to-test monolith owned by one team. Keep the gateway to cross-cutting, stateless concerns and keep business logic in services. Full detail is in API Gateway.

Load balancer vs reverse proxy vs API gateway#

Reverse proxyLoad balancerAPI gateway
Main jobFront door for backendsSpread traffic over many instancesManage APIs for many clients
Typical featuresTLS, compression, caching, static files, routingAlgorithms, health checks, drainingAuth, rate limits, API keys, request transformation, aggregation, analytics
Useful with one backend?YesNoYes
LayerL7L4 or L7L7
ExamplesNginx, Caddy, Apache httpdAWS ALB/NLB, HAProxyKong, AWS API Gateway, Apigee

All three are reverse proxies in the technical sense. The names describe emphasis. A load balancer is a reverse proxy with more than one backend; an API gateway is a reverse proxy with API-management features. See API Gateway.

The Nginx event-driven model#

Older web servers (Apache's classic prefork mode) used one process or thread per connection. With 10,000 mostly idle connections (keep-alives, slow clients), that meant 10,000 threads, each with its own stack memory and context switches.

Nginx instead runs a few worker processes, usually one per CPU core. Each worker runs an event loop: it asks the operating system (via epoll on Linux, kqueue on BSD) which of its thousands of sockets are ready, handles each ready one without blocking, and moves on. A waiting connection costs only a little memory, not a thread. This lets one Nginx server hold tens of thousands of concurrent connections with modest memory, which is exactly what a proxy in front of slow clients needs. The same model is used by Node.js, HAProxy and Envoy.

worker (one per core)
  loop:
    ready = epoll_wait(sockets)        # which sockets have data or can write?
    for s in ready:
      read what is available; parse; forward to upstream or write response
      never block: if not ready, move to the next socket

The Nginx event-driven model in depth#

The problem it solved. In 1999 Dan Kegel's essay "The C10K problem" asked how a server could handle ten thousand clients at once. The common design then was one process or thread per connection. That is simple to program, since each connection's code can block on reads and writes, but each thread reserves its own stack (often 1-8 MB of virtual memory, tens to hundreds of KB actually used), and the kernel must schedule thousands of threads that spend almost all their time waiting. Idle keep-alive connections and slow clients made it worse: most of those threads did nothing but hold memory.

Nginx's answer. Igor Sysoev started Nginx in 2002 and released it publicly in 2004. Nginx runs one master process and a small number of worker processes, usually one per CPU core (worker_processes auto).

  • The master reads the configuration, opens the listening sockets, starts and watches the workers, and handles signals. It never touches client traffic.
  • Each worker is single-threaded and runs an event loop over thousands of non-blocking sockets. It asks the kernel which sockets are ready (epoll on Linux, kqueue on BSD and macOS), does whatever work is possible on each without waiting, and moves on. A connection waiting for the client or the upstream costs only a small state structure and some buffers.

How cheap is an idle connection? The Nginx documentation has long stated that 10,000 inactive HTTP keep-alive connections take about 2.5 MB of memory. A thread-per-connection server would need gigabytes of reserved stack for the same 10,000 connections.

The rule: never block the loop. Because one worker serves thousands of connections, any blocking call (a slow disk read, a synchronous DNS lookup, a heavy computation in a script) stalls every connection on that worker. Nginx uses non-blocking network I/O everywhere, its own asynchronous DNS resolver, and, since version 1.7.11, optional thread pools that move blocking file reads off the event loop. The same discipline applies to Node.js, which uses an event loop in the same way. A CPU-heavy function in a Node handler blocks every other request on that process.

Handling a request step by step. A worker accepts a connection, reads bytes as they arrive until it has a full request header, runs the request through configured phases (rewrite, access checks, content handler), opens or reuses an upstream connection, writes the request, and registers interest in the response. While waiting, it serves other sockets. When the response arrives, it buffers it (to memory, or to a temp file if it is large) and writes it to the client as fast as the client accepts it.

Zero-downtime reloads. Send the master a reload signal (nginx -s reload) and it checks the new config, starts new workers with it, and tells old workers to stop accepting new connections and exit once their current ones finish. Config changes and even binary upgrades happen without dropping traffic. Proxies with very frequent config changes, such as in large Kubernetes clusters, find these reloads costly, which is one reason Envoy uses dynamic configuration over APIs (xDS) instead.

Spreading connections across workers. If every worker waits on the same listening socket, a new connection can wake all of them while only one wins, which is the thundering herd problem. Nginx historically used an accept mutex; modern setups use reuseport (the Linux SO_REUSEPORT option), which gives each worker its own listening socket and lets the kernel spread new connections among them.

Other models.

ServerModelNotes
Apache httpd preforkOne process per connectionSimple, robust for non-thread-safe modules, heavy at high concurrency
Apache httpd event MPMThreads, plus a listener that parks idle keep-alivesMuch closer to Nginx for idle connections
NginxFew single-threaded event-loop workersVery low memory per connection
HAProxyEvent loops, multithreaded since 1.8Extremely fast L4 and L7 proxying
EnvoyOne event loop per worker thread, connections pinned to a threadDynamic config, rich L7 filters
Node.jsOne event loop per process, libuv thread pool for file and DNS workSame "never block" rule

One product, many roles#

The same software often fills several roles, so names on a diagram describe jobs, not products:

RoleNginxHAProxyEnvoyManaged cloud
Reverse proxy and static filesStrongProxy only, no static filesProxy, limited staticUsually not
L7 load balancerYesStrongStrongALB, Google HTTP(S) LB
L4 load balancerStream moduleStrongYesNLB, Google TCP/UDP LB
API gatewayWith plugins (OpenResty, Kong)PartlyWith filters and a control planeAWS API Gateway, Apigee
Forward or egress proxyPossible, not typicalPossibleMesh egress gatewayNAT gateway with firewall
Mesh sidecarRareRareStandard choiceManaged meshes

When to combine them#

A typical production path stacks several reverse proxies, each with a clear role:

Combine layers when each adds something; collapse them when they duplicate. A small app can use one Nginx for everything; a large platform may have a CDN, a cloud LB, an API gateway, a service mesh and an egress proxy.

Choosing the layer: a decision walk-through#

Because the boxes overlap, it helps to start from the need rather than the product name:

Read it as "add a layer only when a need appears". A startup with one region and one service may run a managed load balancer and nothing else. A company exposing public APIs to partners adds a gateway. A global consumer app adds a CDN. A regulated company adds egress control. Each layer should be named for the problem it solves.

The same roles in the major clouds#

RoleAWSGoogle CloudAzure
CDN and edge reverse proxyCloudFrontCloud CDN, Media CDNAzure Front Door
L7 load balancerApplication Load BalancerExternal Application Load BalancerApplication Gateway, Front Door
L4 load balancerNetwork Load BalancerExternal passthrough Network Load BalancerAzure Load Balancer
API gatewayAPI GatewayAPI Gateway, ApigeeAPI Management
Edge WAFAWS WAFCloud ArmorAzure WAF
Egress controlNAT Gateway plus Network FirewallCloud NAT plus Secure Web ProxyNAT Gateway plus Azure Firewall

Managed services remove the work of running proxies, but each has its own limits on timeouts, body size, header size and rule counts. Check them early, because they often decide the design. Long-running uploads, long polling and streaming responses are where those limits most often bite.

Configuring an egress allow-list#

A forward proxy for servers usually starts from "deny everything" and lists the few destinations each environment may reach. A minimal Squid example:

# squid.conf (simplified): servers in 10.0.0.0/16 may reach only approved hosts
acl internal src 10.0.0.0/16
acl approved dstdomain .stripe.com .sendgrid.net .pypi.org .files.pythonhosted.org
acl ssl_ports port 443
acl CONNECT method CONNECT
http_access deny CONNECT !ssl_ports
http_access allow internal approved
http_access deny all
http_port 3128

Servers then set HTTPS_PROXY=http://egress.internal:3128 and NO_PROXY for internal domains. Every blocked attempt shows up in the proxy's logs, which is often how teams discover forgotten dependencies, or a compromised host trying to call out.

How setups grow: from one proxy to a full edge#

Most systems grow their proxy layers in stages. Adding each layer is worth it only when it solves a problem you actually have.

A useful worked example is a ticketing service like Ticketmaster. Event details (names, dates, venues, performer bios) are read constantly and change rarely, so they are cached aggressively: a read-through Redis or Memcached cache keyed by event ID, with long TTLs for venue data, short TTLs for availability, and invalidation when an event changes. The Event Service holds no state, so it scales horizontally by adding instances behind a load balancer using round robin or least connections. Load balancing applies to every horizontally scaled tier, including database read replicas, but you rarely need to draw it on every arrow; saying so is enough. The challenges that remain are keeping the cache consistent with the database, and operating many instances with safe deploys and rollbacks.

Drawing proxies in an interview. You need a load balancer wherever several machines can serve the same request, but drawing one in front of every service clutters the diagram. Either draw one at the front as an abstraction and say "every service is horizontally scaled behind a load balancer", or leave them out and say it aloud. Draw specific boxes only when they matter to the design: an L4 balancer for WebSockets, an API gateway that does auth and rate limits, an egress proxy for a payment provider. A good rule of thumb: persistent connections such as WebSockets suggest an L4 load balancer; everything else suits an L7 one, which can route to different services and also cuts the number of connections that reach backends, since it pools and reuses them. For common products, name AWS Elastic Load Balancing, NGINX or HAProxy, and if traffic is extreme, mention that hardware or specialised software balancers exist.

The latency budget of stacked proxies#

Each proxy layer costs time. Typical figures:

HopAdded latencyNotes
CDN edge (cache hit)10-30 ms total, from user to nearby edgeSaves a long trip to the origin
CDN edge to origin (miss)Distance-dependent, often 20-150 msReused, warm connections help a lot
Cloud L7 load balancerAbout 0.5-2 msMore with TLS handshakes on new connections
API gatewayAbout 1-5 msPlus a Redis lookup for rate limits, about 0.5-1 ms
Mesh sidecarAbout 0.2-1 ms per sidecarTwo sidecars per call: caller and callee

A request that passes CDN, load balancer, gateway and two sidecars might add 3-10 ms inside the data center. That is usually fine for an API with a 200 ms target, but it compounds when one user request fans out into a chain of 10 internal calls, each going through two sidecars.

Timeouts and connection reuse across layers#

Stacked proxies fail in a recognisable way when their settings disagree.

Request timeouts should get shorter as you go inward. If the CDN waits 30 seconds, the load balancer 60 seconds and the service 90 seconds, the CDN gives up first and returns a generic 504, while the inner layers keep working on a request nobody is waiting for. Set each inner timeout below the outer one, leaving room for any retries, so the innermost layer that can give a meaningful error does so first.

Idle keep-alive timeouts should get longer as you go inward. A proxy reuses idle connections to the backend. If the backend closes an idle connection at 5 seconds while the proxy thinks it is good for 60, the proxy will sometimes send a request on a connection the backend has just closed, and the client gets a random 502. A well-known example: Node.js's default server keep-alive timeout is 5 seconds, while AWS ALB's default idle timeout is 60 seconds, which caused intermittent 502s for many teams until they raised the Node timeout above the ALB's.

The fix is simple once you know it: make the backend's idle timeout longer than the proxy's (for example 75 seconds behind a 60-second ALB), and let the proxy retry idempotent requests that failed on a reused connection before any bytes were sent.

Body size and header limits must agree. If the gateway allows 10 MB uploads but the inner Nginx allows 1 MB (client_max_body_size defaults to 1 MB), users get a 413 error from a layer nobody remembered to change. List each layer's limits in one place.

Client IP must pass through every hop. Each layer must append to X-Forwarded-For, and the app must know how many trusted proxies to skip from the right-hand end to find the real client address. Get the count wrong and either your logs show the load balancer's IP for everyone, or attackers can forge their address by sending their own header.

Debugging a chain of proxies#

When a request crosses a CDN, a load balancer, a gateway and two sidecars, the first question in any incident is which hop is slow or failing. Proxies make this answerable if they are set up for it.

Request IDs. The outermost proxy should create a unique request ID (or a W3C traceparent header for distributed tracing) if the client did not send one, and every layer should log it and pass it on. Then one search across all logs shows the whole path of a single failing request.

Split the timing. Nginx can log both $request_time (total time from the first client byte to the last byte sent) and $upstream_response_time (time waiting for the backend). They tell different stories:

request_timeupstream_response_timeWhat it means
3.2 s3.1 sThe backend is slow; look at the service and its dependencies
3.2 s0.05 sThe client is slow to send or receive; the backend is fine
0.9 s0.85 s, 0.02 sFirst upstream attempt timed out or failed, retry succeeded
0.001 snoneServed from cache or rejected at the proxy (check the status)

Know which layer produced the status. A 502 means the proxy got an invalid response or a broken connection from upstream; a 504 means the upstream did not answer within the proxy's timeout; a 503 often means no healthy upstream or deliberate load shedding; a 429 means the limiter rejected it. Nginx also logs a non-standard 499 when the client closed the connection before the response was ready, which usually means a client or an outer proxy timed out first. Adding a response header such as Server-Timing or a custom X-Served-By, with the name of the layer that generated an error page, saves a lot of guessing.

Compare layers. If the load balancer reports 5xx errors but the backends' own metrics show none, the failures are between them: connection resets, keep-alive races, or the proxy's own limits. If the backends report errors too, the problem is in or behind the service. Cloud load balancers publish separate metrics for errors they generated themselves and errors returned by targets (AWS ALB, for example, distinguishes ELB 5xx from target 5xx), which makes this split quick.

Sidecars, service meshes and egress gateways#

Inside a microservice platform the proxy pattern repeats on every call. In a service mesh each service instance runs a sidecar proxy, usually Envoy (Linkerd uses its own Rust proxy). The application sends its outbound calls to the local sidecar, which finds the destination through service discovery, balances across instances, applies retries and timeouts, encrypts the call with mutual TLS, and records metrics and traces. The receiving instance's sidecar terminates that mTLS, checks whether the caller is allowed, and hands the request to the local app.

So every internal call passes through two proxies: a forward proxy on the caller's side and a reverse proxy on the callee's side. The roles described on this page still apply; they have just moved next to each service.

What a mesh buys:

  • Uniform behaviour across languages: retries, timeouts, circuit breaking and mTLS work the same in Go, Java and Python services without per-language libraries.
  • Zero-trust networking: each workload has a cryptographic identity, and policies say "orders may call payments" rather than trusting anything inside the network.
  • Traffic control: canaries, traffic shifting and fault injection for testing, all set by config.
  • Visibility: consistent golden metrics (request rate, errors, latency) for every service-to-service edge. See Observability.

What it costs: an extra 0.2-1 ms per sidecar hop, CPU and memory for every sidecar (multiplied by every pod), a control plane (Istio's istiod, Linkerd's control plane) that must be highly available, and a steep learning curve. Newer designs reduce the cost. Istio's ambient mode replaces per-pod sidecars with a shared per-node proxy for mTLS and an optional per-service proxy for L7 features. Proxyless gRPC has gRPC libraries read mesh configuration directly.

An egress gateway is the mesh's version of a forward proxy: a dedicated set of proxies through which all traffic leaving the mesh must pass, so security teams can allow-list external hosts and audit calls in one place.

Making the reverse proxy itself reliable#

The primer's warning applies to every proxy: one instance is a single point of failure, and fixing that adds complexity. Common patterns:

  • Two or more instances behind a floating IP (keepalived with VRRP) on-premise, or behind a managed L4 load balancer in the cloud.
  • DNS with several proxy addresses, so clients can try another if one fails.
  • Stateless proxies: keep caches disposable and config in version control, so a failed proxy is replaced rather than repaired.
  • Shared state outside the proxy: rate-limit counters in Redis, sessions in a store, certificates in a secret manager.
  • Careful config rollout: a bad config pushed to every proxy at once takes everything down. Validate configs (nginx -t, Envoy config validation) and roll out to a small share of proxies first.
  • Capacity headroom: proxies are usually CPU-bound on TLS handshakes and compression, so watch CPU and new-connection rates, not just request counts.

When to Use It#

  • Forward proxy: controlling and auditing outbound traffic from corporate or server networks.
  • Reverse proxy: in front of almost every web application, even with one backend.
  • Load balancer: as soon as there are two or more instances.
  • API gateway: when many clients or partners use many APIs and need consistent auth, quotas and keys.

When NOT to Use It#

  • Do not stack layers that duplicate each other (TLS terminated three times, rate limiting in two places with different rules).
  • Do not put heavy business logic in a proxy or gateway; keep it in services.

How to Implement It#

  1. Start with one reverse proxy (Nginx, Caddy, or the cloud LB) terminating TLS and routing to the app.
  2. Add load balancing when you run more than one instance.
  3. Add a CDN in front for static assets and global users.
  4. Add an API gateway when you have many APIs or external API consumers.
  5. Add an egress proxy when servers must only reach approved external hosts.
# Nginx as a reverse proxy with compression and caching (simplified)
proxy_cache_path /var/cache/nginx keys_zone=app:50m max_size=5g;
server {
    listen 443 ssl http2;
    gzip on;
    client_max_body_size 10m;
    location /static/ { root /srv/app; expires 7d; }
    location / {
        proxy_pass http://app_backend;
        proxy_cache app;  proxy_cache_valid 200 60s;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}
TechnologyFits when
NginxGeneral reverse proxy, static files, simple caching and LB
CaddySimple setups with automatic HTTPS
EnvoyDynamic configuration, gRPC, service mesh data plane
SquidForward proxy and caching for outbound traffic
Cloud egress gateways / NAT with firewallControlling outbound traffic from cloud networks

Trade-offs#

ChoiceProsConsPick when
One reverse proxy for everythingSimple, cheapSingle place for many concerns; scaling limitsSmall and medium apps
Separate CDN, LB, gatewayEach layer specialised and scalableMore hops (~1-5 ms each), more configLarge platforms
Forward proxy for egressAudit and control outbound callsExtra hop; another component to keep upRegulated or security-sensitive networks
Explicit forward proxyClear policy, works with CONNECT for HTTPSClients must be configured; NO_PROXY mistakesCorporate web access, build farms
Transparent interceptionNo client configurationBreaks with HTTPS unless doing TLS inspectionLegacy networks, guest Wi-Fi
TLS inspectionFull visibility of outbound contentPrivacy risk, breaks pinned apps, high-value targetRegulated enterprises with strong governance
Rate limiting at the gatewayBlocks traffic before it reaches appsOnly request-level context, shared counter storeMost public APIs
Rate limiting in a dedicated serviceExact global limits with business contextExtra round trip per request, new dependencyComplex tiered limits
Rate limiting in-processFastest, no dependenciesLimits off by a factor of the server countSingle server or approximate limits
Service mesh sidecarsUniform mTLS, retries and metricsLatency and resources per pod, complex control planeLarge polyglot microservice fleets
Micro-caching at the proxyHuge backend load reduction for hot readsData up to the TTL stale, cache key mistakes leak dataRead-heavy public pages and APIs

Common Pitfalls#

  • Losing the real client IP: forward it in X-Forwarded-For or the PROXY protocol, and trust it only from your own proxies.
  • Caching responses that vary by user because the cache key ignores cookies or auth.
  • Timeouts that do not line up across layers, so an outer proxy gives up while an inner one keeps working.
  • Proxy buffers too small for large uploads, causing failures at the proxy, not the app.
  • Request timeouts that grow inward, so outer layers give up while inner ones keep working on abandoned requests.
  • Backend keep-alive timeouts shorter than the proxy's idle timeout, causing random 502s.
  • Trusting identity headers like X-User-Id without stripping client-sent copies at the edge.
  • Running an open forward proxy reachable from the internet.
  • Letting user input choose the upstream host, opening the door to SSRF.
  • Business logic creeping into gateway plugins until the gateway is a fragile monolith.
  • Forgetting NO_PROXY for internal hosts, so internal calls go out through the corporate proxy.
  • Pushing a new proxy config to every node at once without validation.

Real-World Examples#

Nginx was created by Igor Sysoev to address the "C10k problem" of handling ten thousand concurrent connections, and is now one of the most widely used web servers and reverse proxies.

Cloudflare's network acts as a reverse proxy for its customers' websites, adding caching, TLS and DDoS protection in front of their origin servers.

Netflix built Zuul as the gateway at the edge of its streaming service and open-sourced it in 2013. It handled routing, authentication, load shedding and the traffic shifting used in regional failover drills. Zuul 2 later moved to an asynchronous, event-driven design on Netty for the same reasons Nginx uses an event loop.

Cloudflare described Pingora, the Rust proxy it built to replace Nginx for much of its traffic, in 2022. It reported significant CPU and memory savings, partly because connections to origins could be reused across all threads instead of being trapped inside one Nginx worker process.

Envoy started at Lyft as an edge and service proxy to tame a growing set of microservices. It became the default data plane for Istio and many other meshes, and the base of several API gateways.

Squid, first released in the 1990s, is one of the longest-lived caching forward proxies and is still used by ISPs, schools and companies to filter and cache outbound web traffic.

In the Interview#

How to talk about proxies in an interview#

Name each box by its job, say which side it acts for, and say why it is there:

  • "The CDN caches static assets and absorbs DDoS traffic at the edge."
  • "A managed L7 load balancer terminates TLS and spreads requests across stateless API servers."
  • "The API gateway validates JWTs and enforces per-user rate limits before requests reach services, returning 429s at the edge. Counters live in Redis."
  • "WebSocket traffic uses a separate L4 load balancer, since connections are long-lived."
  • "Outbound calls to the payment provider go through an egress proxy with fixed IPs that the provider allow-lists."

Follow-up questions and strong answers.

  • "Why would you put a reverse proxy in front of a single server?" TLS termination, compression, caching, static files, buffering slow clients and hiding the backend. None of these need a second server.
  • "Where should rate limiting go?" At the gateway for most cases: blocked requests never reach the app. Use a dedicated service when limits need business context, and accept the extra round trip and the fail-open or fail-closed decision.
  • "How does Nginx handle so many connections?" A few single-threaded workers, each running a non-blocking event loop over thousands of sockets using epoll, so an idle connection costs a few hundred bytes, not a thread.
  • "Do we need an API gateway and a load balancer?" Often both exist, but one product can do both. Say which functions you need, then choose the fewest layers that provide them.
  • "Users get random 502s behind the load balancer. Why?" Likely a keep-alive mismatch: the backend closes idle connections before the proxy does. Make the backend's idle timeout longer than the proxy's.
Deep Dive: Transparent proxies, the PROXY protocol and sidecarsShow

Preserving client identity. An L7 proxy adds X-Forwarded-For and X-Forwarded-Proto; an L4 proxy cannot add headers, so it uses the PROXY protocol to prepend the original client address to the connection. Applications must only trust these values from known proxies, or attackers can spoof their IP.

Buffering protects backends. A reverse proxy can read a whole request from a slow mobile client before forwarding it, and absorb a large response quickly, freeing the app's worker in milliseconds. This is one reason to keep a proxy in front of thread-per-request application servers.

Sidecars and service meshes. A service mesh (Istio, Linkerd) places a small proxy next to every service instance. These sidecars handle mTLS, retries, timeouts and metrics for service-to-service calls, so a reverse proxy now sits on both sides of every internal call. The benefit is uniform behaviour; the cost is extra latency (around a millisecond per hop) and operational complexity.

Deep Dive: Security pitfalls that live in proxiesShow

Cache poisoning. If a reverse proxy builds its cache key from the path only, but the backend's response depends on another header (say X-Forwarded-Host, used to build absolute links), an attacker can send one request with a malicious header, get a poisoned response cached, and have it served to every later visitor. Defences: include every input that changes the response in the cache key or the Vary header, strip unexpected headers at the edge, and do not reflect headers into cached responses.

Web cache deception. Described by Omer Gil in 2017. An attacker tricks a logged-in victim into visiting a URL such as /account/profile.css. A lenient backend ignores the fake suffix and returns the private profile page; the proxy sees .css, treats the response as a static asset, and caches it publicly, so the attacker can fetch it. Defences: cache only by explicit rules and content types, respect Cache-Control: private and no-store, and make backends return 404 for paths they do not recognise.

Request smuggling. When a front proxy and a backend disagree on where one HTTP/1.1 request ends (Content-Length versus Transfer-Encoding handling), an attacker can hide a second request inside the first, which then gets attached to another user's connection. Use HTTP/2 end to end where possible, normalise or reject ambiguous requests at the edge, and keep proxy software patched. Covered in HTTP and HTTPS.

Open proxies. A forward proxy that accepts connections from anyone on the internet will be found within hours and abused for spam, scraping, credential stuffing and attacks that look like they come from you. Bind forward proxies to internal networks, require authentication, and restrict CONNECT to port 443 and allowed hosts.

SSRF through the proxy. A reverse proxy or gateway that routes based on user input (a host header, a URL parameter) can be tricked into calling internal services or the cloud metadata endpoint. Route only to a fixed allow-list of upstreams and block private and link-local address ranges for anything user-controlled.

Header trust. Headers like X-Forwarded-For, X-Real-IP, X-User-Id or X-Authenticated-User are only meaningful if your own proxy set them and the client could not. The edge must strip any incoming copies before adding its own. Otherwise a client simply sends X-User-Id: admin.

Host header attacks. Apps that build password-reset links from the Host header can be tricked into emailing links to an attacker's domain. The proxy should accept only known host names and reject or default the rest.

Deep Dive: Caching at the reverse proxy, step by stepShow

What can be shared. A shared cache (a reverse proxy or CDN) may store a response only if it is allowed to: Cache-Control: public or s-maxage make it explicit, while private, no-store, or an Authorization header in the request (without explicit permission) rule it out. See the caching rules in HTTP and HTTPS and the broader strategies in Caching Strategies.

The cache key. By default this is usually method plus host plus path plus query string. Each extra input in Vary (such as Accept-Encoding) multiplies the stored copies. Varying on User-Agent or Cookie usually destroys the hit rate, because nearly every request is different. Normalise first: sort query parameters, drop tracking parameters such as utm_source, and bucket devices into a few classes before varying on them.

Hit-rate math. If the backend takes 50 ms and a hit takes 1 ms, then at a 90% hit rate the average is 0.9 x 1 + 0.1 x 50 = 5.9 ms, and backend load falls tenfold. At 99% the backend load falls a hundredfold. That is why moving from 90% to 99% matters as much as going from 0% to 90%.

Stampedes and collapsing. When a popular entry expires, hundreds of concurrent requests miss together and all go to the backend. Request collapsing (Nginx proxy_cache_lock, Varnish request coalescing, CDN "origin shield" tiers) sends one request upstream while the others wait. Serving stale content during refresh (stale-while-revalidate) removes the wait altogether.

Surviving origin failures. stale-if-error lets the proxy keep serving the last good copy when the backend returns 5xx or times out, so an outage looks like slightly old data instead of an error page. Nginx exposes this as proxy_cache_use_stale error timeout updating.

Invalidation. Prefer short TTLs plus versioned URLs (app.3f9c2.js), which never need purging, over explicit purges. When content must change immediately, use tagged purges (purge by surrogate key, supported by Varnish, Fastly and others) rather than wildcard path purges.

Deep Dive: Streaming, WebSockets and gRPC through a reverse proxyShow

Buffering is the default, and sometimes the enemy. Nginx buffers upstream responses by default (proxy_buffering on): it reads as much of the response as fits in memory buffers, spills larger responses to a temp file, and writes them to the client at the client's pace. That is ideal for normal pages and for protecting app servers from slow clients. It is wrong for responses that are meant to stream, such as Server-Sent Events, live logs or LLM token streams, because the client would see nothing until the buffers fill. Turn buffering off for those routes (proxy_buffering off, or have the app send X-Accel-Buffering: no), and raise proxy_read_timeout so long idle gaps do not close the stream.

WebSockets need the upgrade passed through. Upgrade and Connection are hop-by-hop headers, so a proxy drops them unless told otherwise. In Nginx a WebSocket route needs HTTP/1.1 to the upstream (proxy_http_version 1.1) and both headers forwarded explicitly (proxy_set_header Upgrade with the client's upgrade header, and proxy_set_header Connection "upgrade"). Once upgraded, the proxy only copies frames; idle timeouts still apply, so clients and servers should exchange pings more often than the shortest idle timeout on the path.

gRPC needs HTTP/2 end to end. gRPC runs over HTTP/2 and uses trailers to carry the final status. A proxy that downgrades the upstream leg to HTTP/1.1 breaks it. Use gRPC-aware proxying (grpc_pass in Nginx, or Envoy and HAProxy with HTTP/2 upstreams), and balance per request, not per connection, so new backend instances get traffic. Browsers cannot speak raw gRPC, so a proxy often translates gRPC-Web to gRPC.

Backpressure. A proxy sits between a fast producer and a possibly slow consumer. If a backend streams 100 MB/s to a client that reads 1 MB/s, something must give: the proxy either buffers (bounded by memory and temp-file limits) or stops reading from the backend, which slows the backend down through normal TCP flow control. Good proxies make that limit explicit with per-connection buffer sizes, so one slow client cannot consume all the proxy's memory.

Upstream connection pools. Proxies keep pools of idle connections to each backend to avoid a new TCP and TLS handshake per request. In Nginx each worker process has its own pool (keepalive 64 in an upstream block means up to 64 idle connections per worker), so with 16 workers a backend may see up to 1,024 idle connections from one proxy. Size backend connection limits with that multiplication in mind. Envoy and Pingora share pools more widely, which improves reuse.

Key Takeaways#

  • A forward proxy acts for clients (filtering, egress control, privacy); a reverse proxy acts for servers.
  • Reverse proxies add TLS termination, compression, caching, protection and routing in front of backends.
  • Load balancers and API gateways are reverse proxies with different emphasis: spreading load vs managing APIs.
  • Nginx handles huge connection counts with a few event-loop workers instead of a thread per connection.
  • Stack proxy layers only when each adds a distinct capability, and keep timeouts and client-IP handling consistent.
  • A proxy terminates one connection and opens another, which is what lets it read, change, cache, block or reroute traffic.
  • Forward proxies use CONNECT tunnels for HTTPS and see only host names unless they do TLS inspection, which has real privacy and security costs.
  • Egress proxies give fixed source IPs, allow-lists and SSRF protection for server traffic.
  • Reverse proxies are worth having even with one backend: security, TLS, compression, caching, static files and buffering slow clients.
  • Rate limiting at the gateway is the common choice; a dedicated service adds context at the cost of a round trip, and in-process limits are off by the server count.
  • Nginx's master and per-core event-loop workers make idle connections cost a few hundred bytes; never block the loop.
  • Request timeouts should shrink inward, while idle keep-alive timeouts should grow inward.
  • Strip and reset forwarded and identity headers at the edge, and make every proxy layer redundant.
  • Trace one request through every hop with a request ID, split total time from upstream time, and know which layer produced each error status.
  • Pick layers by need: a forward or egress proxy for outbound control, a reverse proxy for any web backend, a load balancer for several instances, a gateway for many API consumers, and a CDN for global or static-heavy traffic.