Skip to the page

Django and DRF · core

A request inside Django, and writing middleware

The server hands the request to Django, which runs middleware top to bottom, resolves the URL, runs the view and sends the response back up through the middleware bottom to top.

The notes

What you must know

  • A WSGI server (Gunicorn, uWSGI) or an ASGI server (Uvicorn, Daphne, Granian) calls Django's handler, which builds an HttpRequest and sends the request_started signal.
  • Middleware is a chain of wrappers around get_response. On the way in it runs top to bottom in the MIDDLEWARE list; on the way out, bottom to top.
  • Order matters: SessionMiddleware must come before AuthenticationMiddleware, which sets request.user lazily.
  • A middleware can answer early without calling get_response (a rate limiter, a maintenance page). The inner middleware and the view never run, but the outer middleware still sees the response.
  • After the middleware: URL resolution (ROOT_URLCONF), process_view hooks (CsrfViewMiddleware checks the token here), the view, then template rendering for a TemplateResponse.
  • If a view raises, process_exception hooks run bottom to top; if none returns a response, Django makes a 500 (or 404 or 403) and logs it. Then request_finished fires.
  • A request id middleware: reuse a valid X-Request-ID only from a trusted proxy, else uuid4().hex; keep it in a contextvars.ContextVar and add a logging.Filter so every log line has it; time with perf_counter in try/finally; send it back in the X-Request-ID header; put it near the top of MIDDLEWARE.
  • Under ASGI, middleware can be sync or async. A sync middleware in front of an async view costs a thread switch on every request. Never log tokens, cookies or full bodies.

The red pen

Common traps: mistake → fix

  • Mistake: Middleware runs only on the way in

    Fix: it runs in on the way in and out on the way out, in reverse order.

  • Mistake: A thread-local is fine for a request id

    Fix: it does not work with async views; use ContextVar.

  • Mistake: The order of MIDDLEWARE does not matter

    Fix: sessions must come before authentication.

Easy to hard

Questions interviewers ask, easy to hard

  1. What happens inside Django from the moment a request arrives until the response leaves?
  2. In what order does middleware run in and out?
  3. Where does the CSRF check happen?
  4. Why must SessionMiddleware come before AuthenticationMiddleware?
  5. Write a middleware that adds a request id and logs the time taken, for sync and async.

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview