You visit a site twice. The second visit is instant. The first one made you wait. The difference is what the browser remembered between visits: the answers it kept, and the key card it carried. This lesson is about both, and about telling them apart.
Difficulty: Beginner · Know this first: Lesson 01 — how a request travels
Every hop charges rent in milliseconds. The bar below is a worked example for this lesson's scenario — not a measurement from a live system — but the shape is honest: on a cache hit the trip is almost free, on a miss the kitchen eats the budget. Step through the lesson or switch the scenario and watch the bar change.
Extra diagram · from scratch to master
Start with one guest. Add one box at a time until the whole hotel is on the map, blocked doors included.
The budget bar above shows three fixed stories. This simulator lets you write your own. Move a slider and watch the tray, the trip out, and the trip back change in the budget bar, in the hop timings, and in the total. The numbers are a teaching example, not live measurements. The shape is the lesson: one bad input can bend the whole trip.
Share of answers the tray already holds. A hit costs 5 ms, a miss costs 240 ms, so the data hop is 5 ms plus 235 ms times the miss share. At 90 percent the data hop is about 29 ms. At 50 percent it is about 123 ms.
How big the key card is. The cookie rides on every request, so a fatter card makes every trip out slower: 20 ms plus 5 ms for each kilobyte. A 4 KB card costs 40 ms before the server has done anything.
How big the answer is. The trip back costs 20 ms at 100 KB and one more millisecond for each 50 KB above that, up to 60 ms.
Try this: (1) Set cache hit rate to 50, cookie size to 1, response size to 100. The data hop is about 123 ms and the total is about 190 ms. (2) Set all three to the worst end: 0 percent, 4 KB, 2000 KB. The data hop is 240 ms, the trip out is 40 ms, the trip back is 58 ms, and the total is about 360 ms. Same system, same code. Only the inputs changed.
Type your own numbers: Get the total under 150 ms. Type 95 for the hit rate, 1 for the cookie, 100 for the size, and run it. Then lower the hit rate until it fails and note where the line is.
Three questions. No score is saved anywhere — this is just you against the material.
I take the same hotel four times here. First I learn the two things the browser remembers. Then I learn to read the instructions that come with them. Then I manage the memory so one stale answer cannot hurt anyone. Last I run it for the world.
Definition: Two kinds of memory. The cache keeps answers: pages, images, files. The cookie keeps identity: who you are, what you picked. The hotel keeps your usual order on a tray. It hands you a key card at check-in. The tray saves waiting. The card saves introducing yourself.
Types:
Uses: I use the cache every time a page feels slow on first load and fast on second. I use the cookie every time a site remembers I am logged in. When a user says "it worked yesterday", I ask what changed: the tray, or the card.
Dimensions: At low traffic both are nearly free. What breaks first is freshness: a tray that serves yesterday's order, or a card that expired while the guest was still in the building. It costs almost nothing to keep either. It costs real time when I confuse them and clear the wrong one.
Open this page in a browser. Press F12, open the Console tab, and type these lines one at a time. The page sets no cookies of its own, so you start from empty and watch each drawer fill.
document.cookie
localStorage.setItem('tray', 'usual-order')
localStorage.getItem('tray')
localStorage.length
document.cookie = 'keycard=guest42; Max-Age=3600; Path=/'
document.cookie
sessionStorage.setItem('tab-note', 'dies with the tab')
sessionStorage.getItem('tab-note') What you should see: document.cookie prints "" first, then "keycard=guest42" after you set it. localStorage.getItem('tray') prints "usual-order" and localStorage.length prints 1. The tab note prints "dies with the tab".
It passes when: the cookie line shows the card, the tray line shows the order, and closing the tab wipes the tab note while the tray and the card survive. Reopen the tab and localStorage.getItem('tray') still prints "usual-order".
Try it: Basic
The cache keeps answers and the cookie keeps identity. What does the cookie keep?
Now do it: Run the Try it yourself block above: set the cookie, then check document.cookie prints keycard=guest42 and localStorage.getItem('tray') prints usual-order.
Definition: The server tells the browser what to keep, for how long, in headers. Cache-Control: max-age=3600 says keep this answer for an hour. Set-Cookie says carry this card, and names its rules: how long it lives, which paths it works on, whether JavaScript may read it. I read these headers before I guess anything about a caching bug.
Types:
Uses: I use long ages on files that never change, like a versioned image, and short ages on pages that do. I use ETag so the browser can ask "still fresh?" instead of downloading the whole file again. I check Set-Cookie first when a login works in one browser and fails in another.
Dimensions: As traffic grows, the cache is what keeps the origin alive. What breaks is the header I forgot: a page cached for a day that changes every hour, or a cookie without Secure that leaks over plain HTTP. It costs one look at the response headers. The trade is that every minute of max-age buys speed and sells freshness.
Save this file as server.py in an empty folder. It serves one page with a cache header and an ETag, plus a login page and an account page you will use in the next two sections. Run it in one terminal. The curl commands go in a second terminal.
Flags in the commands that run this file, letter by letter. I read every flag out loud before I run a command I copied. A flag I cannot explain is a flag I do not run yet.
python3 server.py starts the little origin server in this lesson. No flags. The file name is the argument. The server listens on port 8321 on localhost only, and it runs until I stop it with Ctrl+C.curl -sI http://127.0.0.1:8321/page.html asks for the headers of the page only. The -s means silent, no progress bar. The -I means headers only, send a HEAD request and print the response headers without the body. Without -I, curl prints the whole page body. Without -s, curl prints a progress meter to stderr on top of the answer.python3 -c "..." runs code given on the command line instead of a file. The -c means command string. I use it for one line checks.python3 -m py_compile server.py checks the syntax without running the code. The -m means run a library module as a script.python3 --version prints the version. I run it first on a new box, because the version decides what the code can use.Check it: run curl -sI http://127.0.0.1:8321/page.html, then run the same curl without -I and compare. The first prints headers only. The second prints the page body after them.
#!/usr/bin/env python3
"""A tiny origin server. Serves one page, one login, one account page."""
from http.server import BaseHTTPRequestHandler, HTTPServer
VERSION = {"v": 1}
class H(BaseHTTPRequestHandler):
def log_message(self, *a):
pass
def do_HEAD(self):
self._head = True
self.do_GET()
def do_GET(self):
head = getattr(self, "_head", False)
if self.path == "/page.html":
etag = '"v%d"' % VERSION["v"]
if self.headers.get("If-None-Match") == etag:
self.send_response(304)
self.send_header("ETag", etag)
self.end_headers()
return
body = ("<html><body><h1>Numbers, version %d</h1></body></html>" % VERSION["v"]).encode()
self.send_response(200)
self.send_header("Content-Type", "text/html")
self.send_header("Cache-Control", "public, max-age=3600, stale-while-revalidate=60")
self.send_header("ETag", etag)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
if not head:
self.wfile.write(body)
elif self.path == "/login":
body = b"<html><body>logged in</body></html>"
self.send_response(200)
self.send_header("Set-Cookie", "session=guest42; Max-Age=1800; Path=/; HttpOnly; Secure; SameSite=Lax")
self.send_header("Content-Type", "text/html")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
if not head:
self.wfile.write(body)
elif self.path == "/account":
body = b"<html><body>balance: 42.00</body></html>"
self.send_response(200)
self.send_header("Content-Type", "text/html")
self.send_header("Cache-Control", "private, no-store")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
if not head:
self.wfile.write(body)
elif self.path == "/bump":
VERSION["v"] = 2
body = b"now serving version 2"
self.send_response(200)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
if not head:
self.wfile.write(body)
else:
self.send_response(404)
self.end_headers()
HTTPServer(("127.0.0.1", 8321), H).serve_forever()python3 server.py
curl -sI http://127.0.0.1:8321/page.html What you should see:
HTTP/1.0 200 OK
Cache-Control: public, max-age=3600, stale-while-revalidate=60
ETag: "v1" It passes when: the Cache-Control line says max-age=3600 and the ETag line says "v1". Stop the server with Ctrl+C when you are done.
Try it: Intermediate
Cache-Control: max-age=3600 says what?
Now do it: Run the Try it yourself block above and check the Cache-Control line says max-age=3600 and the ETag line says v1.
Definition: At this level I stop trusting the tray and start managing it. Invalidation means throwing a stale answer away on purpose. Revalidation means asking the server "is my copy still good" and getting a 304 back instead of the whole file. And the cross-origin wall means a cookie from one site does not work at another: SameSite decides when the card may be shown, and CORS decides when one origin may read another's answers.
Types:
Uses: I use versioned file names on every deploy so no user ever sees last week's JavaScript. I use stale-while-revalidate on pages where a slightly old answer is fine and a slow answer is not. I use SameSite=Lax on session cookies, and I test third-party widgets with third-party cookies blocked, because that is the browser my users actually run.
Dimensions: At ten times the traffic, invalidation is the hard part, not storage. What breaks is the answer I cannot throw away: a poisoned cache entry, or a cookie a widget depends on that the browser now refuses to send. It costs a deploy-time cache-bust plan and a test with cookies blocked. The trade is that strictness buys safety and costs the features that quietly depended on being loose.
With the same server running, ask for the page again and send the tag back. Then change the version on the server and ask again.
Flags in the commands that run this file, letter by letter. I read every flag out loud before I run a command I copied. A flag I cannot explain is a flag I do not run yet.
curl -sI -H 'If-None-Match: "v1"' http://127.0.0.1:8321/page.html sends the tag back to the server. The -sI is the silent and headers only pair from the earlier block. The -H takes one extra request header to send. The header here says I already hold version v1, so the server answers 304 when nothing changed and sends no body. Without the -H header, the server answers 200 with the whole page every time.curl -s http://127.0.0.1:8321/bump asks the server to move to version 2. The -s is the silent flag. No -I here, because I want the small body back, which says the version changed.curl -s -o /dev/null -w "page: %{time_total}s\n" http://127.0.0.1:8321/page.html measures the trip instead of printing it. The -o /dev/null throws the body away. The -w takes a format string and prints the timing after the request. The %{time_total} inside it is the whole trip in seconds. Without -o, the body would print and bury the timing line.Check it: run the first curl twice, once with the -H header and once without. The first should print 304. The second should print 200 with the body.
curl -sI -H 'If-None-Match: "v1"' http://127.0.0.1:8321/page.html
curl -s http://127.0.0.1:8321/bump
curl -s http://127.0.0.1:8321/page.html What you should see: the first command prints HTTP/1.0 304 Not Modified and no body. The bump prints now serving version 2. The last command prints <html><body><h1>Numbers, version 2</h1></body></html>.
It passes when: the 304 arrives with no body, and the page after the bump shows version 2. The tag did its job. The browser asked instead of downloading.
Advanced drill — A cache key that forgets the user serves one user to another. A cache key decides which requests share an answer. A key built from the URL alone shares the answer with everyone. That is fine for a public image. It is a leak for a page with a name on it. I have seen a dashboard cached by URL serve one user's account page to the next user who asked.
Run this. A cache keyed by URL only stores the first user's page and serves it to the second user. The same cache keyed by URL plus user serves each user their own page. The fix is one field in the key, and the bug is invisible until two users ask for the same URL.
cache = {}
def get_page_wrong(user, url):
if url in cache:
return cache[url]
page = f"account page for {user}"
cache[url] = page
return page
def get_page_right(user, url):
key = (user, url)
if key in cache:
return cache[key]
page = f"account page for {user}"
cache[key] = page
return page
print("wrong key, alice asks:", get_page_wrong("alice", "/account"))
print("wrong key, bob asks: ", get_page_wrong("bob", "/account"))
cache.clear()
print("right key, alice asks:", get_page_right("alice", "/account"))
print("right key, bob asks: ", get_page_right("bob", "/account"))
Expected output:
$ python3 cache-and-cookies-adv.py wrong key, alice asks: account page for alice wrong key, bob asks: account page for alice right key, alice asks: account page for alice right key, bob asks: account page for bob
Read it like this: Bob got Alice's page, because the key forgot who asked. The rule I use: if the response differs per user, the user belongs in the key. If the response is the same for everyone, it does not.
Try it: Advanced
I send If-None-Match: v1 and nothing changed. What does the server answer?
Now do it: Run the Try it yourself block above: send the tag back and expect 304 with no body, then bump the version and expect version 2.
Definition: At this level the tray is not one tray. There is the browser cache, the edge cache, and the origin cache, each with its own rules, and a cookie must survive all of them without leaking. Per-user answers are never cached where another user could read them. Static files are cached forever under versioned names. The session cookie is HttpOnly, Secure, SameSite=Lax, and short-lived, with a refresh path that does not ask the user to log in again.
Types:
Uses: I use this when a page serves users on more than one continent, or when a cached answer shown to the wrong user would be a security incident, not just a bug. It is also how I review a system I did not build: I ask which answers are shared, which are per-user, and what proves the two never mix.
Dimensions: At a hundred times the traffic the edge does most of the work and the origin only answers misses. What breaks is the shared cache serving a private answer, or a cookie that outlives the session it belonged to, and I notice it from a user report, not from a dashboard. It costs real operational work: cache-key reviews, purge drills, and cookie audits. The trade is that the memory is now a system of its own, and it needs an owner the way the database has one.
Audit the cookie the login sets and the headers the account page sends. A session cookie must carry all five decisions, and a page with a balance must never be stored.
Flags in the commands that run this file, letter by letter. I read every flag out loud before I run a command I copied. A flag I cannot explain is a flag I do not run yet.
curl -sI http://127.0.0.1:8321/login | grep -i set-cookie prints only the cookie line from the headers. The -sI is the silent and headers only pair. The pipe sends the headers to grep. The -i means case insensitive, so set-cookie matches Set-Cookie. Without -i, the lowercase pattern would miss the header, because HTTP headers start with a capital letter.curl -sI http://127.0.0.1:8321/account | grep -i cache-control prints only the cache line from the account page. Same flags. The answer should be private, no-store, which means no cache anywhere may store this page.Check it: run the login curl without the grep and read all the headers. Then add the grep back and see only the cookie line left.
curl -sI http://127.0.0.1:8321/login | grep -i set-cookie
curl -sI http://127.0.0.1:8321/account | grep -i cache-control
curl -sI http://127.0.0.1:8321/account | grep -i set-cookie What you should see:
Set-Cookie: session=guest42; Max-Age=1800; Path=/; HttpOnly; Secure; SameSite=Lax
Cache-Control: private, no-store The third command prints nothing at all.
It passes when: the cookie line shows HttpOnly, Secure, SameSite=Lax, Max-Age=1800, and Path=/; the account page says private, no-store; and no Set-Cookie line appears on the account page. If any flag is missing, the audit fails and the cookie goes back for a fix.
Master drill — A cookie without its flags is a cookie anyone can steal. A session cookie needs three flags. HttpOnly keeps scripts from reading it, so a cross-site scripting bug cannot steal the session. Secure keeps it off plain HTTP, so a network observer cannot read it. SameSite keeps the browser from sending it on cross-site requests, so a forged form cannot ride the session.
Run this. It starts a tiny server with two login endpoints. One sets the cookie bare. One sets it with all three flags. The headers print side by side. The difference is three words, and those three words are the whole defence.
import threading
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.request import urlopen
class H(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
if self.path == "/bad":
self.send_header("Set-Cookie", "session=abc123")
else:
self.send_header("Set-Cookie", "session=abc123; HttpOnly; Secure; SameSite=Lax")
self.send_header("Content-Length", "2")
self.end_headers()
self.wfile.write(b"ok")
def log_message(self, *a):
pass
srv = HTTPServer(("127.0.0.1", 0), H)
threading.Thread(target=srv.serve_forever, daemon=True).start()
port = srv.server_address[1]
for path in ("/bad", "/good"):
with urlopen(f"http://127.0.0.1:{port}{path}") as r:
print(path, "->", r.headers["Set-Cookie"])
srv.shutdown()
Expected output:
$ python3 cache-and-cookies-master.py /bad -> session=abc123 /good -> session=abc123; HttpOnly; Secure; SameSite=Lax
Read it like this: the bad cookie is one bare value, and the good one carries three flags. I check Set-Cookie headers with curl on every login endpoint I ship. A missing flag is a one-line fix, and it is the cheapest security fix I know.
Try it: Master
A page shows a balance. What must its cache header say?
Now do it: Run the Try it yourself block above: check the cookie line shows HttpOnly, Secure, SameSite=Lax, Max-Age=1800, and Path=/, and the account page says private, no-store.
Cache-Control and ETag do different jobs. Cache-Control says how long the browser may keep an answer without asking. ETag says how the browser asks: it sends the tag back, and the server answers 304, still fresh, instead of the whole file again. I set long ages on files with versioned names and short ages on pages that change. A page that changes every hour with max-age=86400 is a page that lies for a day.
Stale-while-revalidate is the middle ground. Sometimes a slightly old answer now beats a fresh answer later. It lets the browser serve the tray copy immediately and fetch a fresh one in the background. The next visitor gets the fresh copy. I use it on pages where fresh matters but waiting hurts more.
A cookie is five decisions. How long it lives (Max-Age). Where it works (Path and Domain). Whether JavaScript may read it (HttpOnly). Whether it travels only over HTTPS (Secure). And SameSite: Lax sends the card on visits to your own hotel but not on cross-site form posts; Strict never sends it across sites; None sends it everywhere but demands Secure. My default for a session cookie is HttpOnly, Secure, SameSite=Lax.
Not everything belongs in a cookie. localStorage holds about 5 MB per origin and stays until you clear it, but it is never sent to the server, so it cannot prove who you are. sessionStorage is the same drawer with a shorter life: it dies when the tab closes. IndexedDB is the filing cabinet: large, structured, asynchronous, good for offline data. The rule I use: the cookie carries identity, the cache carries answers, and the drawers carry data the page needs but the server does not.
Across origins, the wall is real. A cookie belongs to the site that set it. A page on one origin cannot read another origin's cookies, and a fetch to another origin does not send your cookies unless you ask for credentials and the other side allows it. CORS is the handshake for that: the browser asks first, the server answers with Access-Control-Allow-Origin, and without the right answer the browser blocks the read. Third-party cookies are the same idea from the other side: a widget from another site wants to leave its own key card in your browser. Browsers now refuse that by default, so a widget that depended on it breaks quietly. I test with third-party cookies blocked before my users do.
At 10x the traffic, the shape holds and the numbers grow. The cache hit rate is the number I watch, because every point of hit rate is load the origin never feels. At 100x, the design changes: the edge cache moves close to the user, per-user answers bypass the shared cache entirely, and the cookie stays small, because every byte of it rides on every single request.
Cache-Control: public, max-age=3600, stale-while-revalidate=60
ETag: "v42"
Set-Cookie: session=abc123; HttpOnly; Secure; SameSite=Lax; Max-Age=86400; Path=/
What the snippet means: the answer may be kept for an hour, and for one more minute after that the browser may serve the old copy while it fetches a fresh one. The ETag lets the browser ask "still fresh?" and get a 304 back. The session cookie lives a day, JavaScript cannot read it, it only travels over HTTPS, and it is sent on visits to this site but not on cross-site requests. Those six lines are the whole memory policy for this page.
Read the memory policy of all three endpoints in one pass. Write one line per endpoint: what the browser may keep, and what it must not.
curl -sI http://127.0.0.1:8321/page.html | grep -iE "cache-control|etag"
curl -sI http://127.0.0.1:8321/login | grep -i set-cookie
curl -sI http://127.0.0.1:8321/account | grep -i cache-control What you should see: the page is cacheable for an hour with an ETag; the login sets an identity cookie with all five flags; the account page is private, no-store.
It passes when: you can say the policy for each endpoint in one sentence, and each sentence matches a header line above. If you cannot, the policy is not written down anywhere except in your head, and that is where it will be forgotten.
A browser that already has a file does not need to download it again. It sends the ETag it saved, and the server answers 304 when the file is unchanged. No body crosses the wire. A server that ignores If-None-Match sends the whole file every time, and the cache is decoration.
Run this. It starts a tiny server that answers with an ETag. The first request gets 200 and the file. The second request sends the ETag back and gets 304 with no body. The byte count is the proof: the second response is headers only.
import threading
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.request import Request, urlopen
BODY = b"hello, this is the file body"
class H(BaseHTTPRequestHandler):
def do_GET(self):
if self.headers.get("If-None-Match") == '"v1"':
self.send_response(304)
self.send_header("ETag", '"v1"')
self.end_headers()
return
self.send_response(200)
self.send_header("ETag", '"v1"')
self.send_header("Content-Length", str(len(BODY)))
self.end_headers()
self.wfile.write(BODY)
def log_message(self, *a):
pass
srv = HTTPServer(("127.0.0.1", 0), H)
threading.Thread(target=srv.serve_forever, daemon=True).start()
port = srv.server_address[1]
with urlopen(f"http://127.0.0.1:{port}/file") as r:
body = r.read()
print("first request:", r.status, "etag:", r.headers["ETag"], "bytes:", len(body))
req = Request(f"http://127.0.0.1:{port}/file", headers={"If-None-Match": '"v1"'})
try:
with urlopen(req) as r:
print("second request:", r.status, "bytes:", len(r.read()))
except Exception as e:
print("second request:", e.code, "bytes: 0 (not modified, nothing sent)")
srv.shutdown()
Expected output:
$ python3 cache-and-cookies-deep.py first request: 200 etag: "v1" bytes: 28 second request: 304 bytes: 0 (not modified, nothing sent)
Read it like this: the second request got a 304 and zero bytes. That is the cache working. If your server answers 200 to a matching ETag, the revalidation is broken, and every repeat visit pays full price.
A page I owned showed yesterday's numbers all morning. No deploy had failed. The servers were healthy. But every user who had visited the page the day before saw the old version, and every first-time visitor saw the new one. The tray was serving yesterday's order, and the kitchen had already cooked a new one.
Three things. First, HTML pages get short cache ages by default; only versioned files get long ones. Second, every deploy now checks the Cache-Control header on the changed pages before it ships, not after. Third, I stopped telling users to clear their cache as if that were a fix. A cache that serves a day-old page is not a user error. It is a header I wrote.
Replay the stale page with the server. Fetch the page, change the version on the server, then fetch again. The server is right both times. The cache is the liar. Then make the fix from the incident: the page gets a short age.
Flags in the commands that run this file, letter by letter. I read every flag out loud before I run a command I copied. A flag I cannot explain is a flag I do not run yet.
curl -s http://127.0.0.1:8321/page.html fetches the page body. The -s is the silent flag. No -I here, because the point is the body, which shows the version number.sed -i 's/max-age=3600/max-age=60/' server.py edits the server file in place. The -i means edit the file itself instead of printing the changed text. The s/old/new/ is the substitute command. Without -i, sed would print the changed line to the screen and leave the file untouched, and the restart after it would serve the old value. I always check a file after an -i edit, because there is no undo.Check it: run the sed line, then run grep max-age server.py. The file should say 60 now. Then restart the server and fetch the headers to see the new value live.
curl -s http://127.0.0.1:8321/page.html
curl -s http://127.0.0.1:8321/bump
curl -s http://127.0.0.1:8321/page.html
sed -i 's/max-age=3600/max-age=60/' server.py Restart the server, then check the header again.
curl -sI http://127.0.0.1:8321/page.html | grep -i cache-control What you should see: the first fetch prints version 1, the bump prints now serving version 2, and the second fetch prints version 2. After the fix, the header says Cache-Control: public, max-age=60, stale-while-revalidate=60.
It passes when: the second fetch shows version 2, and after the fix the header says max-age=60. The page can now lie for at most a minute. A browser that loaded the page before the fix still holds the old copy for up to an hour, because the old header allowed it. That is why the fix also needs versioned file names on the next deploy.
Design caching and cookies for a login page and an account page that must answer in under 200 ms at p99 while serving 1,000 requests per second. The account page shows the user's name, balance, and recent activity. The balance changes often. You have a browser cache, an edge cache, a session cookie, and an origin server.
Start with the budget from this lesson. Key card 2, tray check 5, trip out 20, front desk 10, kitchen 240 on a miss, trip back 20, drawer 5. That is 302 ms on a miss, which already breaks the 200 ms target, so the design must make misses rare: versioned static files cached at the edge, the account shell cached per user for seconds, and the balance fetched fresh only where it is shown. Little's Law says the requests in flight equal the arrival rate times the time in the system, so 1,000 requests per second times 0.2 seconds is 200 requests inside the system at once. I need room for at least 200, plus headroom for a spike, so I plan for 400 and alert at 80 percent.
Caching the account page buys speed and costs privacy if a shared cache ever serves one user's balance to another, so per-user answers bypass the shared cache entirely. A long-lived cookie buys fewer logins and costs a longer window if it is stolen, so the session is short-lived with a refresh path. SameSite=Lax buys protection against cross-site requests and costs the embedded widget that depended on the cookie arriving cross-site, so say it on the page. And the target is p99, not the average. An average of 120 ms with a p99 of 500 ms fails this design.
Build the login and account pages on the local server, then prove the memory policy with a check script. The server is the one from the Intermediate section. The fix is the one from the incident above: change max-age=3600 to max-age=60 and restart it.
Steps:
check-cache.py in the same folder.Flags in the commands that run this file, letter by letter. I read every flag out loud before I run a command I copied. A flag I cannot explain is a flag I do not run yet.
python3 check-cache.py runs the checker script. No flags. It fetches the pages, reads the headers, and prints PASS or FAIL for each design rule.curl -s -o /dev/null -w "page: %{time_total}s\n" http://127.0.0.1:8321/page.html measures the page trip. The -s is silent. The -o /dev/null throws the body away. The -w prints the timing format after the request. The %{time_total} is the whole trip in seconds. The account line below it measures the same trip for the account page, so the two numbers sit side by side.Check it: run the two timing curls and compare the numbers. Both should print well under 0.2 seconds on a local machine. Then run one without -o /dev/null and see the body bury the timing line.
#!/usr/bin/env python3
"""Check the login + account memory policy. All three checks must print PASS."""
import subprocess
def headers(path):
out = subprocess.run(["curl", "-sI", "http://127.0.0.1:8321" + path],
capture_output=True, text=True).stdout
return out
fails = []
login = headers("/login")
need = ["HttpOnly", "Secure", "SameSite=Lax", "Max-Age=1800", "Path=/"]
missing = [f for f in need if f not in login]
print("login cookie flags:", "PASS" if not missing else "FAIL missing " + ", ".join(missing))
if missing:
fails.append("login cookie")
account = headers("/account")
ok = "private, no-store" in account
print("account is private, no-store:", "PASS" if ok else "FAIL")
if not ok:
fails.append("account cache")
page = headers("/page.html")
ok = "max-age=60" in page and "ETag:" in page
print("page has short age + ETag:", "PASS" if ok else "FAIL")
if not ok:
fails.append("page cache")
print("ALL PASS" if not fails else "FAILED: " + ", ".join(fails))
raise SystemExit(1 if fails else 0)python3 check-cache.py
curl -s -o /dev/null -w "page: %{time_total}s\n" http://127.0.0.1:8321/page.html
curl -s -o /dev/null -w "account: %{time_total}s\n" http://127.0.0.1:8321/account What you should see:
login cookie flags: PASS
account is private, no-store: PASS
page has short age + ETag: PASS
ALL PASS The two timing lines each print a number well under 0.2 seconds on a local machine.
It passes when: the check script prints ALL PASS and both timing lines print a number under 0.2. That is the design, built and measured, not just described. If any check prints FAIL, the header it names is the fix. The p99 target from the exercise is met here on the local machine; on a real deployment you would measure the same two endpoints under load.