Discover how one simple middleware can reveal hidden delays slowing down your app!
Why Request timing middleware in FastAPI? - Purpose & Use Cases
Start learning this pattern below
Jump into concepts and practice - no test required
Imagine you want to know how long each web request takes in your FastAPI app, so you can find slow parts and improve them.
You try adding timers inside every route handler manually.
Manually adding timers everywhere is tiring and easy to forget.
You might miss some routes or add inconsistent timing code.
This makes your code messy and hard to maintain.
Request timing middleware automatically measures how long every request takes, no matter which route it hits.
You add it once, and it works everywhere consistently.
start = time.time() response = await some_route_handler() elapsed = time.time() - start print(f"Request took {elapsed}s")
app.add_middleware(RequestTimingMiddleware)
# Middleware logs time for all requests automaticallyYou can easily monitor and improve your app's speed without cluttering your route code.
A developer adds request timing middleware to spot slow API calls and optimize database queries, improving user experience.
Manual timing is repetitive and error-prone.
Middleware centralizes timing logic for all requests.
This helps keep code clean and performance visible.
Practice
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 DQuick Check:
Request timing = measure duration [OK]
- Confusing timing middleware with authentication
- Thinking it serves static files
- Assuming it parses JSON data
Solution
Step 1: Check middleware decorator and signature
FastAPI HTTP middleware uses @app.middleware('http') and async def with (request, call_next).Step 2: Verify timing logic and response modification
It records start time, awaits call_next(request), calculates duration, adds header, and returns response.Final Answer:
Correct async HTTP middleware with timing and header addition -> Option CQuick Check:
@app.middleware('http') + call_next + timing [OK]
- Using @app.route instead of @app.middleware
- Missing async or call_next parameter
- Using websocket middleware for HTTP requests
import time
from fastapi import FastAPI
app = FastAPI()
@app.middleware('http')
async def add_process_time_header(request, call_next):
start_time = time.time()
response = await call_next(request)
process_time = time.time() - start_time
response.headers['X-Process-Time'] = str(process_time)
return responseSolution
Step 1: Analyze header addition in middleware
The code adds 'X-Process-Time' header with the calculated process_time value.Step 2: Confirm header content meaning
This header holds the duration in seconds the request took to process.Final Answer:
A header named 'X-Process-Time' with the request processing duration in seconds -> Option BQuick Check:
Header 'X-Process-Time' = duration seconds [OK]
- Confusing header names added by middleware
- Assuming no headers are added
- Thinking it adds request ID or content length
import time
from fastapi import FastAPI
app = FastAPI()
@app.middleware('http')
def timing_middleware(request, call_next):
start = time.time()
response = call_next(request)
duration = time.time() - start
response.headers['X-Time'] = str(duration)
return responseSolution
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 AQuick Check:
Async + await call_next required [OK]
- Forgetting async keyword on middleware function
- Not awaiting call_next(request)
- Using wrong decorator like @app.route
Solution
Step 1: Confirm async middleware and await call_next
Middleware must be async and await call_next(request) to work properly.Step 2: Check timing calculation and conditional logging
Duration is end time minus start time; log only if duration > 0.5 seconds.Step 3: Verify correct duration calculation and print statement
Code with start = time.time(), await call_next, duration = time.time() - start, if duration > 0.5: print(f'Request took {duration:.3f} seconds') correctly calculates duration and prints formatted message conditionally.Final Answer:
Async middleware with correct timing and conditional logging if duration > 0.5s -> Option AQuick Check:
Async + await + correct timing + conditional print [OK]
- Missing async or await in middleware
- Calculating duration incorrectly (start - end)
- Logging unconditionally or not at all
