Sub topic 16
Cookies and caching
This chapter covers how HTTP adds state on top of a stateless protocol (cookies) and how it avoids repeating work (caching). It assumes you can read an HTTP request and response, know the common methods and status code classes, and understand that HTTP runs over TCP. The chapter ends with the typical GATE calculation patterns for both topics.
Why HTTP needs cookies
HTTP is stateless. The server treats each request on its own and keeps no memory of earlier ones. That keeps servers simple and lets any server in a pool answer any request. It also means a site cannot tell, from the protocol alone, that two requests came from the same user. A shopping cart, a login session, and a language preference all need that link.
A cookie is a small piece of data that the server asks the browser to store and send back on later requests. The standard case uses four parts:
- The server's response carries a
Set-Cookieheader. - The browser stores the cookie, tagged with the site it came from.
- Later requests to that site carry a
Cookieheader with the stored value. - The server keeps a back-end record, usually a database row, keyed by the cookie value.
The protocol stays stateless. The state lives in the browser's cookie jar and in the server's database.
A cookie exchange in code
The following program runs a small local server that sets a cookie on the first visit and recognizes it later. It then plays the browser's part with a raw socket client, in the style used earlier in this tutorial. Run it as one script.
import socket
import threading
ready = threading.Event()
def serve():
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as srv:
srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
srv.bind(("127.0.0.1", 5001))
srv.listen()
ready.set()
for _ in range(2):
conn, _ = srv.accept()
with conn:
req = conn.recv(4096).decode()
if "Cookie: id=1678" in req:
body = "welcome back, user 1678"
head = "HTTP/1.1 200 OK\r\n"
else:
body = "hello, new visitor"
head = "HTTP/1.1 200 OK\r\nSet-Cookie: id=1678; Max-Age=3600\r\n"
head += f"Content-Length: {len(body)}\r\nConnection: close\r\n\r\n"
conn.sendall((head + body).encode())
def fetch(extra=""):
req = f"GET / HTTP/1.1\r\nHost: localhost\r\n{extra}Connection: close\r\n\r\n"
with socket.create_connection(("127.0.0.1", 5001)) as s:
s.sendall(req.encode())
data = b""
while chunk := s.recv(4096):
data += chunk
return data.decode()
threading.Thread(target=serve, daemon=True).start()
ready.wait()
first = fetch()
print(first.split("\r\n\r\n")[1])
print([l for l in first.split("\r\n") if l.startswith("Set-Cookie")])
second = fetch("Cookie: id=1678\r\n")
print(second.split("\r\n\r\n")[1])The first reply says hello, new visitor and shows the Set-Cookie header. The second request carries the cookie, so the server replies welcome back, user 1678.
Cookie attributes and risks
The Set-Cookie header can carry attributes that control the cookie.
| Attribute | Effect |
|---|---|
| `Max-Age` or `Expires` | Lifetime. Without either, the cookie is a session cookie and is dropped when the browser closes. |
| `Domain`, `Path` | Which requests carry the cookie. |
| `Secure` | Send only over HTTPS. |
| `HttpOnly` | Hide the cookie from page scripts, which limits theft through script injection. |
| `SameSite` | Restrict sending on cross-site requests, which limits cross-site request forgery. |
A cookie set by a site the user is visiting is a first-party cookie. A cookie set by a different site whose content is embedded in the page, such as an advertisement, is a third-party cookie. Third-party cookies allow tracking a user across sites, which is why browsers restrict them. A cookie is also not a secret store. The user can read and edit it, so servers should store only an opaque identifier and keep real data on the server.
Why caching matters
Fetching the same object repeatedly wastes time and bandwidth. A cache keeps a copy of a response and serves it again. Two kinds exist:
- A browser cache is private to one user.
- A shared cache, such as a proxy or a web cache run by an organization, serves many users. It sits between clients and origin servers. A hit is answered by the cache. A miss is forwarded to the origin server, and the reply is stored on the way back.
Caching helps in three ways. It cuts response time, because the cache is closer than the origin. It reduces traffic on the access link. It reduces load on the origin server.
Freshness: deciding when a copy is still valid
A cached copy can become stale if the origin changes the object. HTTP gives the server two ways to say how long a copy is fresh.
Cache-Control: max-age=Nsays the copy is fresh for N seconds after it was received.Expiresgives an absolute date.
While the copy is fresh, the cache answers without contacting the origin at all. Other useful Cache-Control values:
no-store: do not keep the response anywhere.no-cache: you may keep it, but revalidate with the origin before every reuse.private: only the user's own browser may store it.public: shared caches may store it.
Revalidation with conditional GET
When a copy is stale, the cache need not download the object again. It asks whether the object changed. This is a conditional GET. The origin gives a validator with each response, which is either a modification time or an entity tag.
- The first response includes
Last-Modified: Mon, 01 Jun 2026 10:00:00 GMTorETag: "v7". - The cache later sends
If-Modified-Since: Mon, 01 Jun 2026 10:00:00 GMTorIf-None-Match: "v7". - If the object is unchanged, the origin replies
304 Not Modifiedwith no body. The cache serves its copy and treats it as fresh again. - If the object changed, the origin replies
200 OKwith the new body.
A 304 response still costs one round trip. It saves the transfer of the body, not the request itself.
Common mistakes
- Thinking a cookie makes HTTP stateful. The protocol is unchanged. The state is kept by the endpoints.
- Thinking
no-cachemeans "do not store". That isno-store. - Forgetting that a 304 response has no body.
- Assuming a cache hit always avoids the network. A fresh hit does. A stale copy still needs a conditional request.
- Treating a cookie as proof of identity. A guessable cookie value lets anyone impersonate the user.
GATE-style calculations
The standard question compares average delay with and without a cache. Let h be the hit ratio, the fraction of requests served from the cache.
Average delay = h × (cache delay) + (1 − h) × (cache delay + origin delay), where a miss pays for the cache lookup and the trip to the origin.
If the cache is on the local network and the cost of reaching it is small, a common simplification is:
Average delay = h × Tcache + (1 − h) × Torigin
Suppose 80 percent of requests hit, a hit takes 10 ms, and a miss takes 210 ms. Then the average is 0.8 × 10 + 0.2 × 210 = 8 + 42 = 50 ms.
A related question asks about link load. If the average object is 100 000 bits and the request rate is 15 per second, the offered load on the access link is 1.5 Mbps. With a hit ratio of 0.4, only 60 percent of requests cross the link, so the load falls to 0.9 Mbps. Lower utilization of the link also cuts queuing delay, which is often the largest saving.
The same conditional logic applies to a conditional GET. If a validation check costs one round trip and a full fetch costs one round trip plus the transfer time, an unchanged object saves the transfer time only.
A short program checks the arithmetic:
def avg_delay(h, t_hit, t_miss):
return h * t_hit + (1 - h) * t_miss
def link_load(rate, size_bits, h):
return rate * size_bits * (1 - h)
print(avg_delay(0.8, 10, 210)) # 50.0 ms
print(link_load(15, 100_000, 0) / 1e6) # 1.5 Mbps
print(link_load(15, 100_000, 0.4) / 1e6) # 0.9 MbpsSummary
Cookies let a stateless protocol carry session state: the server issues Set-Cookie, the browser returns Cookie, and the server's database holds the data. Caches reuse responses while they are fresh, then revalidate with If-Modified-Since or If-None-Match and accept a bodiless 304. In numerical questions, weight hit and miss delays by the hit ratio and scale link load by the miss fraction.
Exercise
A cache has a hit ratio of 0.6. A hit takes 20 ms. A miss takes 320 ms in total. Find the average delay, and say how much of the 15 requests per second of 80 000-bit objects reaches the access link, in Mbps.
Show answer
Average delay = 0.6 × 20 + 0.4 × 320 = 12 + 128 = 140 ms. Only the 40 percent of requests that miss use the access link: 15 × 80 000 × 0.4 = 480 000 bits per second, which is 0.48 Mbps.
Exercise
A browser holds a copy of an image whose max-age has expired. It sends a request with If-None-Match: "v7". The image has not changed. What status code does the server return, and does the response contain a body?
Show answer
The server returns 304 Not Modified with no body. The browser serves its stored copy and treats it as fresh again.
Exercise
Explain why a server that uses cookies still counts as using a stateless protocol, and name the attribute that stops page scripts from reading a session cookie.
Show answer
HTTP itself keeps no per-client memory. Each request is handled independently, and the state is held in the browser's cookie and in the server's back-end record that the cookie value identifies. The HttpOnly attribute hides the cookie from page scripts.