Jump into concepts and practice - no test required
or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Request timing middleware
📖 Scenario: You are building a web API using FastAPI. You want to measure how long each request takes to process. This helps you understand the speed of your API and find slow parts.
🎯 Goal: Create a middleware in FastAPI that records the time before and after handling a request. Then add a custom header X-Process-Time to the response showing the time taken in seconds.
📋 What You'll Learn
Create a FastAPI app instance called app
Create a middleware function called request_timing_middleware
Use time.perf_counter() to measure start and end times
Add a header X-Process-Time with the elapsed time to the response
Register the middleware with the FastAPI app using app.middleware('http')
💡 Why This Matters
🌍 Real World
Measuring request processing time helps developers monitor API performance and detect slow endpoints in real time.
💼 Career
Middleware skills are essential for backend developers working with FastAPI or similar frameworks to add cross-cutting features like logging, timing, and authentication.
Progress0 / 4 steps
1
Create the FastAPI app instance
Create a FastAPI app instance called app by importing FastAPI and calling FastAPI().
FastAPI
Hint
Import FastAPI from fastapi and create app = FastAPI().
2
Import time and define middleware function
Import the time module. Define a middleware function called request_timing_middleware that takes request and call_next as parameters.
FastAPI
Hint
Use import time and define the function header def request_timing_middleware(request, call_next):.
3
Measure request time and get response
Inside request_timing_middleware, use time.perf_counter() to record the start time in a variable called start_time. Then call call_next(request) and save the result in a variable called response. After that, record the end time in a variable called end_time using time.perf_counter() again.
FastAPI
Hint
Use start_time = time.perf_counter(), then response = call_next(request), then end_time = time.perf_counter().
4
Add header and register middleware
Calculate the elapsed time as end_time - start_time and convert it to a string. Add this as a header X-Process-Time to the response.headers. Return the response. Finally, register the middleware function with the FastAPI app using the decorator @app.middleware('http') above the middleware function definition.
FastAPI
Hint
Calculate process_time = str(end_time - start_time), add header with response.headers['X-Process-Time'] = process_time, return response, and decorate with @app.middleware('http').
Practice
(1/5)
1. What is the main purpose of a request timing middleware in FastAPI?
easy
A. To convert JSON data to Python objects
B. To handle user authentication automatically
C. To serve static files faster
D. To measure how long each HTTP request takes to process
Solution
Step 1: Understand middleware role
Middleware runs code before and after each request to add extra features.
Step 2: Identify timing middleware purpose
Request timing middleware specifically measures the time taken to process requests.
Final Answer:
To measure how long each HTTP request takes to process -> Option D
A. Missing async keyword and missing await before call_next(request)
B. Using time.time() instead of datetime.now()
C. Response headers cannot be modified in middleware
D. Middleware should be defined with @app.route decorator
Solution
Step 1: Check function signature and async usage
Middleware must be async and await call_next(request) because call_next is async.
Step 2: Identify missing await and async
Code lacks async def and await, causing runtime errors.
Final Answer:
Missing async keyword and missing await before call_next(request) -> Option A
Quick Check:
Async + await call_next required [OK]
Hint: Middleware must be async and await call_next(request) [OK]
Common Mistakes:
Forgetting async keyword on middleware function
Not awaiting call_next(request)
Using wrong decorator like @app.route
5. You want to create a request timing middleware that logs the duration only if it exceeds 0.5 seconds. Which code snippet correctly implements this behavior?
hard
A. @app.middleware('http')\nasync def timing_middleware(request, call_next):\n start = time.time()\n response = await call_next(request)\n duration = time.time() - start\n if duration > 0.5:\n print(f'Request took {duration:.3f} seconds')\n return response