Lectures

HTTP Cache

1. Simple Meaning

HTTP Cache means storing a copy of the server’s response so that the next time someone requests the same thing, it can be served faster without asking the backend again.

Think of it like:

  • You go to a shop and ask for a Coke.

  • The shopkeeper gets it from the warehouse (backend server) — takes 5 minutes.

  • Next time, he already has Coke in the fridge (cache) — gives it in 5 seconds.




2. Why Caching is Important

Without caching:

  • Every request hits your backend.

  • Backend works harder, even for the same repeated request.

  • Slow responses under high traffic.

With caching:

  • Common requests are served from stored copies.

  • Backend is less busy.

  • Responses are much faster.


3. Types of Caching in HTTP

  1. Browser Cache → Stored in the user’s browser.

  2. Proxy Cache → Stored in a middle server like Nginx.

  3. CDN Cache → Stored in geographically distributed servers.

We’re focusing on Proxy Cache in Nginx.


4. How Nginx HTTP Cache Works

  1. First request → Nginx checks if response is cached.

  2. If not cached → Nginx asks backend → stores response in cache → sends to client.

  3. If cached → Nginx sends stored copy directly to client.


5. Nginx HTTP Cache Basic Setup

Let’s say you want to cache image files for 1 hour.

proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m inactive=60m;

server {
    listen 80;
    server_name example.com;

    location /images/ {
        proxy_cache my_cache;
        proxy_cache_valid 200 1h;
        proxy_pass http://localhost:3000;
    }
}

Explanation:

  • /var/cache/nginx → Folder where cached files are stored.

  • keys_zone=my_cache:10m → Name + memory used for cache metadata.

  • inactive=60m → If not used for 60 minutes, remove from cache.

  • proxy_cache_valid 200 1h → Cache only successful responses (200 OK) for 1 hour.


6. Example Use Case

Without Cache:

  • 1000 users request the same /images/logo.png

  • Backend gets 1000 hits.

With Cache:

  • First request → Backend

  • Next 999 requests → Served from Nginx cache (0 backend hits).


7. Advanced Cache Controls

  • Cache different URLs differently:

location /api/ {
    proxy_cache my_cache;
    proxy_cache_valid 200 10m;
}
location /images/ {
    proxy_cache my_cache;
    proxy_cache_valid 200 1h;
}
  • Bypass cache for logged-in users:

location / {
    if ($http_cookie ~* "session_id") {
        proxy_no_cache 1;
        proxy_cache_bypass 1;
    }
}
  • Clear cache manually (delete files in /var/cache/nginx).


8. Benefits of HTTP Cache

  • Faster load time

  • Less load on backend

  • Better scalability

  • Lower bandwidth cost


No comments:

Post a Comment