Skip to content
Index Ai Academy
Phase 8 · Design at scale

Running APIs in production

Versioning, CORS, caching, request ids and health checks.

About 45 minutes · A free account opens the whole lesson.
Already have an account? Sign in to open this lesson

What it covers10

First principles

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.

  1. Starting point

    Client receives a 503 with request ID R31

  2. What changes

    Search structured logs for R31

  3. Result

    The associated trace shows where the dependency timed out

Compare all three steps
  1. Starting point

    Client receives a 503 with request ID R31

  2. What changes

    Search structured logs for R31

  3. Result

    The associated trace shows where the dependency timed out

Complete and reverse the trace

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.

Compare with the worked step

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.

Check one starting point

Client receives a 503 with request ID R31. Check that your implementation produces the result shown above.

Try it on a new case

What should support ask for if the failing request contains private content?

Show worked reasoning

Ask for the request ID and approximate time. Those locate the relevant logs while keeping private content out of the support message.

Run, change, and build

Check this when debugging. Thinking CORS protects an API from scripts or attackers (only browsers enforce it).

Trace the cause · HTTP request, job, and result
  1. Identify the request, response, and any durable state. Predict the status or stored result before following the trace.
  2. Change one request property and keep the client contract visible. Compare the response and job state to explain the observed behavior.
  3. Try the same reasoning on this case. What should support ask for if the failing request contains private content?

Why it matters

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.

What you'll be able to do

  • Explain CORS, answer browser preflight requests, and allow only trusted origins
  • Use HTTP caching headers and know what must never be cached
  • Trace every request with a request id and structured logs
  • Run health checks, shut down gracefully and deprecate versions with dates in the right order
Quick check
Your API works when called from Python, but a web page on another domain gets blocked calling it. What's the most likely reason?
  1. The browser enforces CORS, and the API didn't allow that origin
  2. Python and browsers speak different versions of HTTP
  3. The API refuses all requests that come from JavaScript
  4. The page needs to be served over a faster connection
Show the answer

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.

The idea: one request's journey

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.

Try it now

A hit costs 8 ms and the servers do nothing. A miss costs 8 + 120 = 128 ms.

Quick check
From the lesson on rate limits and retries: retry what may pass next time, with a wait that doubles up to a cap. What does this print: whether to retry a 503 and a 422, and the longest wait before each of six attempts?
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)])
  1. [True, False] [1, 2, 4, 8, 16, 30]
  2. [True, False] [1, 2, 3, 4, 5, 6]
  3. [True, True] [1, 2, 4, 8, 16, 32]
  4. [False, True] [1, 2, 4, 8, 16, 30]
Show the answer

[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.

CORS: browsers guarding their users

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:

  • Keep an allowlist of origins and echo back only a matching one.
  • Never combine 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.
  • CORS is enforced by browsers only. A script or curl ignores it entirely, so CORS is not a substitute for authentication.

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.

Quick check
What does this print?
allowed = {"https://app.shop.test"}
origin = "https://evil.test"
print(origin in allowed)
  1. False
  2. True
  3. None
  4. https://evil.test
Show the answer

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.

Quick check
A curl command can call your API, but the same request from a web page on another domain fails. Why?
  1. curl uses a different version of HTTP that the API supports
  2. The API blocks all requests that come from JavaScript code
  3. The browser enforces CORS, and your API didn't allow that origin
  4. The page is missing an API key that curl sends automatically
Show the answer

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.

Caching and request ids

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:

headermeaning
Cache-Control: public, max-age=300anyone may cache it for 5 minutes (a public product list)
Cache-Control: private, max-age=60only the user's own browser may cache it
Cache-Control: no-storenever 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.

Quick check
A page shows one customer's account balance. Which Cache-Control does the response need?
  1. public, immutable
  2. private or no-store
  3. none: browsers never cache
  4. public, max-age=3600
Show the answer

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.

Quick check
Which response must never be marked Cache-Control: public?
  1. GET /status, a public status page
  2. GET /me/orders, a logged-in user's own orders
  3. GET /products, the public catalog
  4. GET /docs/shipping, a help article
Show the answer

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.

In your own words
Which layer answers a cache hit, and what does the request id let you do?

Write a sentence or two, then compare it with a good answer in the lesson.

In Python: ETags, an attack and one id in every log line

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.

Worked example

A 304 saves the whole body

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))
It runs right here in your browser, with nothing to install.

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.

Drill

Answer 304 when nothing changed

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"'))
In the lesson, your code is checked as you write it.
Worked example

The practice API's ETag and 304

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))
In the lesson you can change this and run it.

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.

An attack to try: a wildcard origin with credentials

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.

Quick check
A request arrives with Origin: https://evil.test, which is not on your allowlist. What should the API's response carry?
  1. Access-Control-Allow-Credentials: true
  2. Access-Control-Allow-Origin: https://evil.test
  3. No Access-Control-Allow-Origin header
  4. Access-Control-Allow-Origin: *
Show the answer

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.

Health checks, shutdown and old versions

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.

Drill

A health check that tells the truth

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"}))
In the lesson, your code is checked as you write it.

Retiring old versions

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.

Worked example

Deprecation comes before sunset

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)
In the lesson you can change this and run it.

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.

Worked example

One request, traced

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])
In the lesson you can change this and run it.

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.

Quick check
Why return the request id in error responses as well as logging it?
  1. A user or support agent can quote it, and you can find that exact request in the logs
  2. Browsers need the request id in the response to apply their CORS rules
  3. It makes the error responses smaller, since the id replaces the full message
  4. It replaces authentication on the next request the client sends
Show the answer

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.

In your own words
Why is an allowlist of origins safer than echoing the origin back?

Write a sentence or two, then compare it with a good answer in the lesson.

In AI and ML systems: the edge in front of a model

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.

Where this shows up in an engineer's week

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.

In your own words
What must never be cached publicly, and why does that include some model replies?

Write a sentence or two, then compare it with a good answer in the lesson.

Choose how to practice

Start with a short baseline or choose guided, independent, or AI-assisted practice.

Practice what you just read

  • 5 code examples you can edit and run
  • a practice exercise that checks your code
  • a 5-question quiz
  • 9 review cards for spaced repetition

Try a quiz question

What is a CORS preflight?

  1. An OPTIONS request the browser sends first, asking whether the real cross-origin request is allowed
  2. A health check that the load balancer sends before it routes any traffic to a server
  3. A test that the server runs on itself before a new version is deployed to production
  4. The first request of every user session, used to set up cookies for those that follow

Answer it at the end of the lesson to see if you're right, and why.

Before this lesson

Keep learning

Where this lesson leads.

575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.

Phase 8 · about 23 hours of study

APIs

Design, build, secure and scale web APIs from first principles 27 lessons 1 free
  1. HTTP from the wire up FreeWhat really travels between client and server: bytes, headers and bodies.40 min
  2. API stylesREST, RPC, GraphQL, gRPC and streaming: what each is for.35 min
  3. Build an API server from scratchRouting, handlers and responses, with no framework.45 min
  4. A web framework, from the insideDecorators, middleware and error handling: how Flask and FastAPI work.40 min
  5. Designing a REST APIResources, methods, status codes, errors and pagination done well.45 min
  6. Validating requests with schemasCheck every request against a JSON Schema and say exactly what's wrong.45 min
  7. A database-backed APICRUD endpoints on SQLite, with safe concurrent updates.45 min
  8. Authentication and authorizationAPI keys, sessions, tokens and OAuth: who's calling, and what may they do?45 min
  9. Rate limits, retries and idempotencyKeep an API up under load and make retries safe.45 min
  10. Async HTTP clientsMany requests at once with asyncio and httpx: limits, timeouts and retries.45 min
  11. Webhooks and eventsPush events to other systems: signed, retried and deduplicated.45 min
  12. Documenting APIs with OpenAPIA machine-readable contract for docs, SDKs and AI tools.40 min
  13. Running APIs in productionVersioning, CORS, caching, request ids and health checks.45 min
  14. Project: a reviews APIAn authenticated, validated, paginated API with tests.45 min
  15. Web pages with FlaskRoutes, Jinja templates, a shared layout, links and error pages, tested with the test client.45 min
  16. Forms and redirectsGET and POST, validation messages, post/redirect/get, flash messages and CSRF tokens.45 min
  17. Accounts and loginsPassword hashing with bcrypt, sessions, pages that need a login, and safe logout.45 min
  18. Project: a trail log web appA multi-page app with a database, accounts, forms and tests.45 min
  19. JavaScript for Python programmersVariables, functions, arrays and objects mapped from Python, and the traps: truthy empty arrays, for...in and string sort.35 min
  20. Async JavaScript: promises, await and fetchThe event loop, async and await, fetch with res.ok checks, Promise.all, and timeouts with AbortController.35 min
  21. Modules, Node and reading TypeScriptimport and export, package.json, classes, and types as notes the compiler checks, read through a small tool server.30 min
  22. A chat front end in the browserThe DOM and events, model text kept out of innerHTML, a streamed reply parsed from server-sent events, and a Stop button.40 min
  23. APIs with FastAPITyped routes, pydantic models, automatic validation and docs, tested with httpx.45 min
  24. Streaming from the serverServer-sent events written by a server: an ASGI app that sends a body in pieces, FastAPI's StreamingResponse, heartbeats, and what a closed connection looks like.40 min
  25. Project: a FastAPI service with accountsA session per request, bcrypt sign-ups, signed tokens, ownership checks and tests on a fresh database.45 min
  26. Serving a model behind FastAPILoad once with lifespan, a typed predict route, a batch route, a cap on work in flight, 429 with Retry-After, a readiness route and a 202 job.45 min
  27. Capstone: a streaming chat serviceA FastAPI service with key auth, a per-user bucket, a token budget, request ids and an event-stream reply, tested on fresh state.45 min
Part of a free course 127 lessons

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.

Part of a free course 20 lessons

Build and Operate HTTP APIs

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