Skip to content

Interview PrepEdge · Core

Reverse Proxies and CDNs ​

14. What is a reverse proxy, and why might you use Nginx? ​

The short answer

A reverse proxy is a server that sits in front of your app servers and receives every client request, then forwards it to the app and relays the response back. Clients only ever see the proxy. Nginx is the most common one, because it is very fast at handling many connections. You use it to terminate TLS, serve static files, compress responses, buffer slow clients so Node is not tied up, enforce size limits and timeouts, cache responses, route paths to different services, and hide the app servers from the internet. A forward proxy is the opposite: it sits in front of clients, such as a corporate web filter.

JobWhy do it in Nginx, not Node
TLS terminationOne place for certificates; very efficient
Static filesServed from disk with sendfile, no JavaScript involved
Slow clientsNginx buffers the upload or response, so a Node process is not held for a slow phone connection
CompressionOffloads CPU from the app
LimitsBody size, request rate, timeouts, before Node sees the request
Routing/api to Node, / to the static front end, /admin blocked
CachingMicro-cache public responses for a second or two

Forward versus reverse:

Forward proxyReverse proxy
Sits in front ofClientsServers
Acts forThe userThe website
ExampleCompany web filter, VPNNginx, a CDN, a cloud load balancer

15. What is SSL/TLS termination at a load balancer or reverse proxy? ​

The short answer

TLS termination means the proxy or load balancer decrypts incoming HTTPS traffic, holds the certificates, and forwards plain HTTP, or newly encrypted traffic, to the app servers. The app no longer handles certificates or the CPU cost of encryption, and certificates are managed and rotated in one place. The app must then learn that the original request was HTTPS from X-Forwarded-Proto, which needs trust proxy in Express. If the network between the proxy and the app is not trusted, re-encrypt to the backends, or use mTLS, instead of sending plain HTTP inside.

browserload balancerholds the certificatedecrypts hereadds X-Forwarded-ProtoNode instancesprivate networkHTTPSHTTP or re-TLSExpress: app.set('trust proxy', 1) so req.secure and secure cookies work
Encryption ends at the edge. The outside connection is HTTPS. Inside, the load balancer passes the request on and says, in a header, that it arrived securely.
ModeProxy to appUse when
TerminationPlain HTTPTrusted private network
Re-encryptionNew TLS connectionCompliance or untrusted internal network
PassthroughEncrypted bytes forwarded untouchedApp must see the client's TLS, such as for mTLS to the app

The bug this causes: Express thinks every request is plain HTTP, so it refuses to set Secure cookies and redirect loops appear. app.set('trust proxy', 1) fixes it (trust proxy).

16. What is a Content Delivery Network (CDN), and when is it useful? ​

The short answer

A CDN is a network of servers in many cities, called edge locations, that cache your content close to users. A visitor in Mumbai gets your JavaScript bundle from a server in Mumbai instead of your origin in London, which cuts latency from hundreds of milliseconds to tens, and your origin serves only the cache misses. CDNs are useful for static assets, images and video, public pages and API responses that many users share, and as a shield: they absorb traffic spikes and DDoS attacks and often include a web application firewall. Examples are Cloudflare, CloudFront, Fastly and Akamai.

ContentThrough a CDN?
JS, CSS, fonts, images with hashed namesYes, cached for a year
Product images and videoYes
Public pages, public API listsYes, short TTL
Logged-in pages and personal API responsesPass through only, private or no-store
UploadsUsually directly to object storage, served back through the CDN

What else a CDN gives you: TLS at the edge, HTTP/3, compression, DDoS protection, bot filtering, rate limits, and image resizing. The caching headers that control it are explained in browser and CDN caching.

17. How should static files be cached in production? ​

The short answer

Give every built asset a content hash in its file name, such as app.3f9a1c.js, which Vite and other bundlers do by default, and serve it with Cache-Control: public, max-age=31536000, immutable, so browsers and CDNs keep it for a year and never revalidate. When the file changes, its name changes, so users fetch the new one. Serve index.html with no-cache, so browsers always revalidate it and pick up the new file names after a deploy. Serve all of this from a CDN or Nginx, pre-compressed with Brotli and gzip.

FileHeaderWhy
assets/app.3f9a1c.js, .css, fontspublic, max-age=31536000, immutableName changes when the content does
index.htmlno-cacheMust point to the newest asset names
favicon.ico, robots.txtpublic, max-age=86400Unhashed; a day is fine
User uploadspublic, max-age=604800 with unique namesImmutable once uploaded

In Express, if you must serve them yourself:

ts
app.use('/assets', express.static('dist/assets', { immutable: true, maxAge: '1y' }))   // (1)
app.get('*', (req, res) => {
  res.set('Cache-Control', 'no-cache')                                          // (2)
  res.sendFile(path.resolve('dist/index.html'))
})
  1. Hashed assets, cached for a year.
  2. The HTML shell, always revalidated. This is also the fallback for client-side routes in a single-page app (Vite deployment).

The deploy trap. Delete old hashed files too early and users with an old index.html open in a tab get 404 for the chunks it references. Keep the previous deploy's assets for a while.

18. How should a Node.js service be deployed behind Nginx? ​

The short answer

Run the Node app on a private port, such as 127.0.0.1:3000, or as several instances, under a process manager or containers. Configure Nginx to listen on 80 and 443, terminate TLS, redirect HTTP to HTTPS, serve static files directly, and proxy_pass everything else to an upstream of Node instances, passing Host, X-Forwarded-For and X-Forwarded-Proto. Add body size limits, timeouts, compression, keep-alive to the upstream, and the headers needed for WebSockets. In Express, set trust proxy. Firewall the Node port so only Nginx can reach it.

nginx
upstream orders_api {
  server 127.0.0.1:3000;
  server 127.0.0.1:3001;
  keepalive 32;                                           # (1)
}

server {
  listen 443 ssl;
  http2 on;
  server_name api.shop.example;
  ssl_certificate     /etc/letsencrypt/live/api.shop.example/fullchain.pem;
  ssl_certificate_key /etc/letsencrypt/live/api.shop.example/privkey.pem;

  client_max_body_size 10m;                               # (2)
  gzip on;
  gzip_types application/json text/css application/javascript;

  location /assets/ {
    root /srv/web;                                        # (3)
    expires 1y;
    add_header Cache-Control "public, immutable";
  }

  location / {
    proxy_pass http://orders_api;
    proxy_http_version 1.1;
    proxy_set_header Connection "";                       # (4)
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_read_timeout 30s;
  }
}

server {
  listen 80;
  server_name api.shop.example;
  return 301 https://$host$request_uri;                   # (5)
}
  1. Keep connections to Node open and reuse them, instead of a new TCP connection per request.
  2. Reject request bodies over 10 MB before they reach Node.
  3. Static files straight from disk.
  4. HTTP/1.1 with an empty Connection header is what makes upstream keep-alive work.
  5. Plain HTTP only redirects.

For WebSockets, add proxy_set_header Upgrade $http_upgrade; and proxy_set_header Connection "upgrade"; on the WebSocket location, and a longer proxy_read_timeout.

19. How do load balancers and reverse proxies differ? ​

The short answer

They overlap heavily, and one product often does both. A load balancer's main job is spreading traffic across many instances and removing unhealthy ones; it can work at layer 4, on raw TCP, or layer 7, on HTTP. A reverse proxy's main job is standing in front of servers and handling HTTP concerns on their behalf: TLS, caching, compression, routing, static files and security headers; it may front a single server. Nginx, HAProxy, Envoy and a cloud application load balancer are all reverse proxies that also load balance.

Load balancerReverse proxy
Main purposeDistribute traffic, health checkingAct for the servers: TLS, caching, routing
Needs several backendsYes, by definitionNo
OSI layer4 or 77
Caching and compressionRarelyOften
ExamplesAWS NLB, ALB, HAProxyNginx, Envoy, Caddy, a CDN

A typical stack uses both: a cloud load balancer across zones, then Nginx or an ingress controller in front of the app pods, then the Node processes (Kubernetes ingress).

Combine chapters into one PDF

Pick the chapters you want. They print in the order you pick them.

Interview Prep
Production & Operations
Performance
Scaling
Edge
Deploying
Delivery
Observability
Other topics
Nothing picked yet