Ordering backend project · Chapter 12 of 12
Hardening and the take-home
By the end of this chapter you can write what every API needs before it faces the internet: a limit on login tries that answers 429 with Retry-After, the security headers a JSON API sends, and one log line per request with an id a support message can quote. Then you take the whole codebase home, ready to push to GitHub. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.
- Part: Ready for production
- 3 tasks
- Python
- In the all labs plan
The first 2 chapters of Ordering backend project are free. This one comes with the all labs plan.
Why you need this
Launch week starts on Monday 2 November, and DabbaDrop's API goes public: the app calls it from every member's phone, and anyone on the internet can call it too. Three things are missing, and Kunal has a story for each.
Guessing passwords. Login checks a bcrypt hash, about 73 ms a try on the lab's machine. Nothing stops a script from trying Advait's email with a list of common passwords, all day. Here are six wrong tries in a row on chapter 11's code:
401
401
401
401
401
401
Every one is answered, and the seventh would be too.
Headers. Chapter 11's /health answers with no security headers at all:
HTTP/1.1 200 OK
date: Sat, 24 Oct 2026 03:44:33 GMT
content-length: 105
content-type: application/json
A browser is left to guess what it may do with the answer: sniff its type, show it inside another site's frame, send the full address of the page that called it to the next site.
Logs. When Rafiq forwards a member's message ("I paid and got an error at 12:14"), nobody can find that request: uvicorn prints one access line per request with no id, no timing and no user. And when someone adds logging in a hurry, the first version logs the query string, with its tokens, or the body, with its passwords.
What you build: 3 tasks
Each task has tests. You write the code in the lab's editor and press Check.
- Task 1 · interview question
Interview: rate_limit.py, a limit on login tries
In app/middleware/rate_limit.py, write RateLimiter.hit(key): it counts one hit for key and returns None when the hit may go through, or, once the key has used its limit hits, the whole seconds until the key's window ends, rounded up and at least 1. The window is fixed: the key's first hit starts it at self.clock(), and once window seconds have passed since then, the key starts again from zero. Keep (window start, count) for each key in self.hits, and never read the time except through self.clock.
Write limit_by_client(name): it returns a dependency check(request) that takes the RateLimiter at getattr(request.app.state, name), counts a hit for client_key(request) (given), and raises too_many_requests(wait) (429, with the header Retry-After) when hit returns a wait. Until it is written, POST /auth/login answers 500.
The Check drives a RateLimiter(5, 60) with a clock of its own: five hits go through, the sixth says 60, another key is not affected, 30.2 seconds in it says 30, half a second before the end it says 1, at 60 seconds a new window starts and counts to 5 again. Then five wrong logins answer 401, the sixth try answers 429 too_many_requests with Retry-After from 1 to 60 even with the right password, and a new app counts its own tries.
Kunal will ask: the limit lives in this process's memory. What happens with two servers, and what would you use instead?
- Task 2
security_headers.py: the headers every answer carries
In app/middleware/security_headers.py, make the middleware that security_headers(production) returns set these headers on every response: X-Content-Type-Options nosniff, X-Frame-Options DENY, Content-Security-Policy "default-src 'none'; frame-ancestors 'none'" (except on the paths in DOCS_PATHS), Referrer-Policy no-referrer, Cross-Origin-Resource-Policy same-origin, and, only when production is True, Strict-Transport-Security "max-age=31536000; includeSubDomains".
The Check reads the headers of GET /health, a 404 and a 401 from the real app (development: no HSTS) and of /docs (no CSP, but nosniff), then of a tiny app of its own with security_headers(production=True), which must also send HSTS.
- Task 3
request_log.py: one log line per request
In app/middleware/request_log.py, make the middleware that request_log(write, clock) returns write one line of JSON per request with write(...), with exactly the keys id, method, path, status, ms and user_id. id is the request's X-Request-Id header when REQUEST_ID fully matches it (1 to 64 letters, digits, - or _), else uuid.uuid4().hex, and the response carries it back as X-Request-Id. path is request.url.path, never the query string. status is the response's status, or 500 when the route raised. ms is (clock() after minus clock() before) times 1000, rounded to 1 decimal place. user_id is request.state.user.id when a route's current_user set it, else None, read after the request has run. Write the line even when the request raised (try and finally), and never a body or a cookie.
The Check runs it on a tiny app of its own with a clock that moves 0.25 seconds: GET /menu?q=secret-word with X-Request-Id req-123 must write {"id": "req-123", "method": "GET", "path": "/menu", "status": 200, "ms": 250.0, "user_id": null} and answer with that id; a bad id and no id each get a new, different one; a login body's password and a session cookie's token never appear; Tara's request has user_id 2; a 401 and a route that raised are logged as 401 and 500.
What you will learn
- Factories: a function that takes options and returns a dependency or a middleware, with state that lives as long as the app.
- Rate limiting: fixed windows, 429 Too Many Requests and Retry-After, and an injected clock that makes it testable.
- FastAPI middleware: call_next, the order they run in, and changing every response in one place.
- Security headers: what each one tells the browser, and why Strict-Transport-Security is for production only.
- Request logs: a request id, timing, try and finally, and what never goes in a log.
- The take-home: DabbaDrop's reference codebase, run on your own machine.
More in Ready for production
Build "Hardening and the take-home" yourself
DabbaDrop delivers tiffins across Mumbai. You build its ordering API, one module a chapter, and take the whole codebase home. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.
The first 2 chapters of Ordering backend project are free. This one comes with the all labs plan.