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.
Key ideas
- 01
STATIC FILES:
rootoraliasinside 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). - 02
COMPRESSION:
gzip on;withgzip_typesfor text formats (JSON, JS, CSS, HTML) cuts bytes by 70–90%. Don't compress images or video, which are already compressed. - 03
CACHING:
proxy_cache_pathdefines a disk cache;proxy_cacheplusproxy_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 respectCache-Control: private. - 04
RATE LIMITING:
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;pluslimit_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. - 05
Behind another load balancer, the client IP must come from
X-Forwarded-For(real_ip_headerandset_real_ip_from), or every client looks like the load balancer and shares one rate limit.
Code & diagrams
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
Why serve static files from Nginx instead of from the application?
Practice
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.