Free Python developer course
Go from your first line of code to working as a Python developer: projects, testing, data, databases, web apps and APIs, all in your browser.
Versioning, CORS, caching, request ids and health checks.
How can a client report a failure you can find in production logs?
A request ID travels across the request boundary and through related logs. It lets operators connect a symptom to server events without recording private request contents.
Client receives a 503 with request ID R31
Search structured logs for R31
The associated trace shows where the dependency timed out
Client receives a 503 with request ID R31
Search structured logs for R31
The associated trace shows where the dependency timed out
Given Client receives a 503 with request ID R31 and The associated trace shows where the dependency timed out, write down the missing step that connects them.
Search structured logs for R31
Now take Search structured logs for R31 and the result above. Write an input and an implementation that could produce this trace.
Client receives a 503 with request ID R31. Check that your implementation produces the result shown above.
What should support ask for if the failing request contains private content?
Ask for the request ID and approximate time. Those locate the relevant logs while keeping private content out of the support message.
Check this when debugging. Thinking CORS protects an API from scripts or attackers (only browsers enforce it).
An API that works on your laptop meets a harsher world in production, the way a home cook's recipe meets a restaurant on a Saturday night. Browsers enforce rules your tests never saw. Users report "it failed" with no detail. Load balancers ask whether a server is healthy, and old clients call versions you'd like to retire. These are the habits that make an API operable: when something goes wrong at 2 a.m., you can find out what and why.
The browser enforces CORS, and the API didn't allow that origin
Browsers block a page from reading another site's API unless the API says that origin is allowed (CORS). Python scripts don't enforce it, which is why it worked there.
A request to a production API passes through layers before your handler sees it, and each layer has a job that you can name. The edge is the front door: a proxy or CDN (content delivery network, servers around the world that keep copies near users) that ends HTTPS and answers from cache what it may. A load balancer spreads requests over copies of the server and skips any that fail their health check. The server runs your app. Every layer writes one log line, and one request id in all of them lets you find the whole trail. Step through the two journeys of the same request, with and without a copy at the edge.
A hit costs 8 ms and the servers do nothing. A miss costs 8 + 120 = 128 ms.
RETRY = {429, 502, 503, 504}
def longest_wait(attempt, base=1, cap=30):
return min(cap, base * 2 ** attempt)
print([code in RETRY for code in (503, 422)], [longest_wait(a) for a in range(6)])[True, False] [1, 2, 4, 8, 16, 30]
A 503 says the server is busy now, so a later try may work. A 422 says the request itself is wrong, and sending it again changes nothing. The waits double and stop growing at the cap. Clients that behave like this are half of a reliable service. The other half is this lesson: what your own servers do.
Your API at api.shop.test works fine from Python. Then a web page at app.shop.test calls it with fetch, and the browser blocks it. That's the same-origin policy: a page may only read responses from its own origin (scheme, host and port). Think of the browser as a bodyguard. It stops a malicious site from reading your bank account through your logged-in browser.
CORS (cross-origin resource sharing) is the guest list. It's how a server says "these other origins may read my responses". The browser sends an Origin header, and the server answers with:
Access-Control-Allow-Origin: https://app.shop.test Vary: Origin
For requests that aren't "simple", such as a JSON POST or any request with an Authorization header, the browser phones ahead. It first sends a preflight: an OPTIONS request asking permission. The server answers it with the allowed methods and headers:
HTTP/1.1 204 No Content Access-Control-Allow-Origin: https://app.shop.test Access-Control-Allow-Methods: GET, POST, PATCH, DELETE Access-Control-Allow-Headers: Authorization, Content-Type Access-Control-Max-Age: 600 Vary: Origin
Rules of thumb:
Access-Control-Allow-Origin: * with cookies or credentials, and never "fix" that by echoing back whatever origin asked (the attack in the Python part).Vary: Origin tells caches the answer depends on the Origin header.In plain words: CORS decides which websites may read your API's answers in a visitor's browser. It doesn't stop anyone else from calling your API.
allowed = {"https://app.shop.test"}
origin = "https://evil.test"
print(origin in allowed)False
https://evil.test isn't in the set, so in gives False. The browser only lets that page read the response if the server names its origin.
The browser enforces CORS, and your API didn't allow that origin
Only browsers apply the same-origin policy. The server must send Access-Control-Allow-Origin for that page's origin.
The fastest request is one that never reaches you. A newsstand on your street saves you a trip to the printing press, and a cached response works the same way. Cache-Control tells browsers, CDNs (content delivery networks, servers around the world that keep copies near users) and proxies what they may keep:
| header | meaning |
|---|---|
Cache-Control: public, max-age=300 | anyone may cache it for 5 minutes (a public product list) |
Cache-Control: private, max-age=60 | only the user's own browser may cache it |
Cache-Control: no-store | never store it anywhere (account pages, tokens, personal data) |
Pair it with ETags: when a copy expires, the client asks with If-None-Match, and a 304 Not Modified saves resending the body.
The classic disaster is caching a personal response as public. A CDN then serves one person's account page to everyone, like a shop handing the same customer's receipt to every person in line. Anything that depends on who is asking must be private or no-store.
private or no-store
A balance depends on who is asking. A shared cache must never keep it, so it is private (the user's own browser only) or no-store.
Every request needs a name too.
A user reports "checkout failed at 2:14". Your servers handled 40,000 requests that minute. Which log lines were theirs?
A parcel carries a tracking number so anyone can find it among millions. Give every request a request id for the same reason. Generate one at the edge, or accept one from the caller or load balancer. Then put it in every log line for that request, return it in an X-Request-Id response header, and include it in error bodies. Support can then ask for that id and find the exact trail in seconds. Anthropic's API does this: every response carries a request-id header.
Write logs as structured JSON, one object per line. It's the difference between a spreadsheet and a diary, because each fact sits in its own named column. Here is one record, spread out to fit the page; in the log file it takes a single line:
{
"ts": "2026-10-30T14:14:03Z", "request_id": "9f2c1e", "method": "POST",
"path": "/v1/checkout", "status": 502, "ms": 1840, "user": "u_42"
}
Log tools can then filter, count and graph them: "all 5xx errors on /checkout in the last hour". Never log secrets, tokens, passwords or full card numbers, and keep personal data to what you need. Across many services, the W3C traceparent header carries the id from one service to the next, so a distributed trace shows the whole journey.
Cache-Control: public?GET /me/orders, a logged-in user's own orders
A shared cache could hand that user's orders to someone else. Personal responses are private or no-store.
Write a sentence or two, then compare it with a good answer in the lesson.
The edge decides from headers alone, so caching starts with the server sending the right ones. An ETag is a fingerprint of a response. When a copy expires, the client asks again with If-None-Match, and if nothing changed the server answers 304 with no body at all.
An ETag is a fingerprint of a response. The client sends it back next time, and if nothing changed, the server answers 304 with no body at all.
import hashlib, json def respond(data, if_none_match=None): body = json.dumps(data) etag = hashlib.sha256(body.encode()).hexdigest()[:12] if if_none_match == etag: return 304, etag, "" return 200, etag, body catalog = {"items": ["tent", "stove", "lantern"] * 100} status, etag, body = respond(catalog) print(status, "bytes sent:", len(body)) status, etag, body = respond(catalog, if_none_match=etag) print(status, "bytes sent:", len(body)) catalog["items"].append("kettle") status, etag, body = respond(catalog, if_none_match=etag) print(status, "bytes sent:", len(body))
The second request sends nothing, because the fingerprint still matches. After the catalog changes the fingerprint changes too, so the client gets the new data without anyone having to guess how long to cache it.
Write conditional_status(etag, if_none_match): return 304 when the client's If-None-Match header matches the current ETag, else 200. The header may be None, *, or a comma-separated list, and a tag may carry a weak prefix W/ that should be ignored for this comparison.
def conditional_status(etag, if_none_match): return 304 if if_none_match == etag else 200 print(conditional_status('"v42"', 'W/"v41", W/"v42"'))
The practice prompts route sends a real ETag. Asking again with it gets a 304 and no body.
import requests url = "https://api.gradient.test/v1/prompts/support-reply" first = requests.get(url) tag = first.headers["ETag"] again = requests.get(url, headers={"If-None-Match": tag}) print(first.status_code, tag, len(first.content) > 0) print(again.status_code, len(again.content))
The first reply has a body and a tag. The second request carried the tag back, and the server answered 304 with nothing to send.
A browser refuses Access-Control-Allow-Origin: * together with credentials, since that would let any site read a logged-in user's data. Teams hit that error and "fix" it by echoing back whatever Origin arrived. That is worse than the wildcard: it says yes to everyone, cookies included. This cell compares the echo with an allowlist for an attacker's page.
ALLOWED = {"https://app.shop.test"}
def naive_cors(origin):
return {"Access-Control-Allow-Origin": origin,
"Access-Control-Allow-Credentials": "true"}
def safe_cors(origin):
if origin not in ALLOWED:
return {}
return {"Access-Control-Allow-Origin": origin,
"Access-Control-Allow-Credentials": "true", "Vary": "Origin"}
def page_may_read(headers, origin):
return headers.get("Access-Control-Allow-Origin") == origin
evil = "https://evil.test"
print("naive echo lets evil.test read:", page_may_read(naive_cors(evil), evil))
print("allowlist lets evil.test read: ", page_may_read(safe_cors(evil), evil))
app = "https://app.shop.test"
print("allowlist lets the app read: ", page_may_read(safe_cors(app), app))
Change ALLOWED to hold "https://evil.test" and rerun to see the allowlist fail open. The list is the only safety.
Origin: https://evil.test, which is not on your allowlist. What should the API's response carry?No Access-Control-Allow-Origin header
With no permission header, a browser will not let evil.test's page read the reply. Saying yes to everyone, or echoing the origin, is the hole.
Load balancers and orchestrators such as Kubernetes poll your servers, and they ask two different questions. "Is anyone home?" and "Is the shop open?" have different answers when the owner is inside, waiting for a delivery. Liveness (/healthz): is the process running at all? If not, restart it; keep the check trivial. Readiness (/readyz): can it serve traffic right now? If not, stop sending it requests until it recovers. A liveness check that tests the database restarts every server when the database blips, which turns a small outage into a big one.
Stateless servers keep nothing between requests, so sessions, caches and rate-limit buckets live in a shared store and a load balancer can send any request to any copy. Graceful shutdown lets a copy leave without cutting anyone off: on a deploy the platform sends SIGTERM, the signal an operating system sends to ask a process to stop politely, and the server fails readiness, finishes what is running and exits. Cap body sizes too (413 Content Too Large), set timeouts, and compress large replies with Content-Encoding: gzip.
Write health(checks, critical): checks maps each dependency to True (up) or False; critical is the set the API can't work without. Return (status, body): 503 with "down" if any critical check fails; 200 with "degraded" if only others fail; 200 with "ok" otherwise. The body is {"status": ..., "failing": [sorted names]}.
def health(checks, critical): return 200, {"status": "ok", "failing": []} print(health({"database": True, "cache": False, "email": True}, {"database"}))
A shop that's closing puts a sign in the window months ahead. When an old version must go, warn first. Two standard headers say so on every response. Deprecation says it's on the way out, and Sunset says when it stops working:
Deprecation: @1788134400 Sunset: Thu, 01 Jul 2027 00:00:00 GMT Link: <https://docs.shop.test/migrate-v2>; rel="deprecation"
@1788134400 is a Unix timestamp: the version was deprecated on August 31, 2026, and it stops working ten months later. The deprecation date always comes before the sunset date. Announce it in the changelog and by email, watch which keys still call the old version, and contact them before the sunset date.
Two dates tell a client when a version is on the way out and when it stops. The Deprecation header carries a Unix timestamp after an @.
from datetime import datetime, timezone from email.utils import parsedate_to_datetime deprecation = "@1788134400" sunset = "Thu, 01 Jul 2027 00:00:00 GMT" deprecated_on = datetime.fromtimestamp(int(deprecation[1:]), timezone.utc) sunset_on = parsedate_to_datetime(sunset) print(deprecated_on.date(), sunset_on.date()) print("deprecation first:", deprecated_on < sunset_on) print("days of notice:", (sunset_on - deprecated_on).days)
The version was deprecated on 2026-08-31 and stops on 2027-07-01, 304 days later. If the sunset came first, the header would announce a version that was already gone.
Middleware gives each request an id and logs it as one JSON line. The id goes back to the client too.
import json, time, uuid LOG = [] def handler(request): return {"status": 200, "headers": {}, "body": {"ok": True}} def traced(request): rid = request["headers"].get("x-request-id") or uuid.uuid4().hex[:12] start = time.perf_counter() response = handler(request) response["headers"]["X-Request-Id"] = rid ms = round((time.perf_counter() - start) * 1000, 2) record = {"request_id": rid, "method": request["method"], "path": request["path"]} LOG.append(json.dumps({**record, "status": response["status"], "ms": ms})) return response req = {"method": "GET", "path": "/v1/orders", "headers": {"x-request-id": "edge-7f3a"}} print(traced(req)["headers"]) print(LOG[-1])
An id that arrives from an upstream proxy is reused, so the trail continues across services. Otherwise a new one is made. The client gets it back in X-Request-Id, and the log line is JSON, so it's searchable. The exercise turns this into proper middleware, with CORS alongside.
A user or support agent can quote it, and you can find that exact request in the logs
"Request req_7f3 failed" turns a vague complaint into one log search.
Write a sentence or two, then compare it with a good answer in the lesson.
A service that calls a model has the same journey with one extra stop: your handler waits on the model API. Three habits carry over. The request id travels: a model API puts a request-id header on every reply, so log it beside your own id, and quote it when you report a failure to the provider. Never cache a reply that depends on who asked, and that includes model answers: a reply built from one user's documents, or one that quotes their account, must be private or no-store. A public prompt with a fixed answer, such as a product description, may be cached. Health means more than the process: readiness should include the dependencies you cannot work without, and a model API that is overloaded is a reason to degrade, not to restart.
The pager rings for four reasons. A new front end reports a CORS error, and the cause is an origin missing from the allowlist. A cached private page, a CDN serving one customer's data to others, is caused by a missing private. A deploy that cuts users off comes from a server with no graceful shutdown. And "it failed" tickets with no trail come from logs without a request id. Each is a header or a habit you can check in a code review. Goes deeper in: A web framework, from the inside builds the middleware that adds the id and the CORS headers, Caches, queues and background jobs adds Redis, and System design fundamentals draws the load balancer and the edge in a full design.
Write a sentence or two, then compare it with a good answer in the lesson.
Start with a short baseline or choose guided, independent, or AI-assisted practice.
What is a CORS preflight?
575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.
Go from your first line of code to working as a Python developer: projects, testing, data, databases, web apps and APIs, all in your browser.
Design, test, deploy, and operate an HTTP API that another engineer can use.
Never trained an AI? Teach a small one to write, right in your browser. It takes about 20 seconds and needs no account. Teach it to write