Command Palette

Search for a command to run...

Hectal
PHASE 5Intermediate ~7 min· topic 3 of 4

Topic 5.3

Nginx: Static Files, Compression, Caching & Rate Limiting

In one line

Beyond forwarding, Nginx serves static files efficiently, compresses responses, caches upstream answers, and rate-limits clients — taking load off the application.

0/4 · 0%

Key ideas

  1. 01

    STATIC FILES: root or alias inside a location serves files straight from disk using the kernel's sendfile, far faster than routing them through a Node or Java app. Add long cache headers for content-hashed assets (the same idea as the Terraform course, Mission 3.2).

  2. 02

    COMPRESSION: gzip on; with gzip_types for text formats (JSON, JS, CSS, HTML) cuts bytes by 70–90%. Don't compress images or video, which are already compressed.

  3. 03

    CACHING: proxy_cache_path defines a disk cache; proxy_cache plus proxy_cache_valid 200 1m; stores upstream responses briefly. Even a 10-second cache on a hot, public endpoint can absorb traffic spikes (SRE course, Shift 2.1). Never cache personalised responses: key the cache carefully and respect Cache-Control: private.

  4. 04

    RATE LIMITING: limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s; plus limit_req zone=api burst=20 nodelay; allows 10 requests per second per client IP with a short burst, returning 503 (or a configured 429) beyond that. It's the local equivalent of the WAF rate rule in the SRE course.

  5. 05

    Behind another load balancer, the client IP must come from X-Forwarded-For (real_ip_header and set_real_ip_from), or every client looks like the load balancer and shares one rate limit.

Code & diagrams

features.confnginx
gzip on;
gzip_types application/json text/css application/javascript;

limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
proxy_cache_path /var/cache/nginx keys_zone=hot:10m max_size=1g;

server {
    listen 80;
    location /static/ { root /srv/shoplite; expires 1y; }
    location /api/    { limit_req zone=api burst=20 nodelay; proxy_pass http://shoplite; }
    location /products { proxy_cache hot; proxy_cache_valid 200 10s; proxy_pass http://shoplite; }
}

Explain it without notes

01

Why serve static files from Nginx instead of from the application?

Practice

01

Every client gets rate-limited together after you put Nginx behind an AWS ALB. Why, and how do you fix it?

Trade-offs

  • ↔

    Caching and rate limiting at the proxy protect the application cheaply, but add configuration to reason about: stale data from caches, and legitimate users blocked by limits that are too tight.

Done when you can

  • I can serve static files and enable compression in Nginx.

  • I can add a short proxy cache to a hot public endpoint.

  • I can rate-limit per client IP, including behind another load balancer.