How would you implement a custom middleware to log the time taken for every request, and what methods like process_view or process_response would you hook into?

Last updated 17 June 2026

  • Record time.monotonic() before calling get_response() and compute the delta after it returns. Then log it or add an X-Request-Duration header in the response phase.

  • process_view is optional: it runs after URL resolution with the view function, so use it to capture which view is being timed.

  • Register the class in MIDDLEWARE near the top so the timing covers the full middleware stack.

  • https://micropyramid.com/blog/understanding-middleware-functionality-in-django2/
  • https://docs.djangoproject.com/en/6.1/topics/http/middleware/
  • https://levelup.gitconnected.com/django-middleware-explained-with-5-production-ready-examples-c2e630c33038
  • https://dev.to/alansomathew/how-django-works-internally-the-complete-request-response-cycle-io8
All Django interview questions