advanced
Nginx compression and caching
Apply gzip or Brotli, proxy cache keys, validators, bypass rules, stale responses, cache purge strategy, and CPU-versus-bandwidth trade-offs.
Enable gzip or Brotli at Nginx for text responses — often better CPU economics than compressing in Node. Set `gzip_types` explicitly; default may skip `application/json`.
Proxy cache stores responses from upstream using a cache key (scheme, host, URI, optionally args). Use `proxy_cache_bypass` and `proxy_no_cache` for authenticated routes.
gzip on;
gzip_types application/json application/javascript text/css;
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=api:10m;
location /api/public/ {
proxy_cache api;
proxy_cache_valid 200 5m;
proxy_cache_key $scheme$host$request_uri;
add_header X-Cache-Status $upstream_cache_status;
proxy_pass http://node_upstream;
}
`stale` directives serve cached content when upstream errors — define product tolerance for staleness.
On interviews: avoid double compression (upstream already sends Content-Encoding); cache poisoning via unkeyed `Vary`; purge strategy after deploys.
Common pitfalls: caching Set-Cookie responses; ignoring `Cache-Control: private` from upstream; Brotli on tiny payloads.
The trade-off is balancing simplicity, performance, safety, and operability — name which axis you optimized and what cost you accepted.
Checklist:
- Compress at edge for JSON/HTML when upstream is plain.
- Key proxy cache on variants that matter.
- Bypass cache for auth and mutation routes.
- Expose cache status for debugging.