Request timing middleware helps you know how long each web request takes. This is useful to find slow parts and improve your app.
Request timing middleware in FastAPI
Start learning this pattern below
Jump into concepts and practice - no test required
from fastapi import FastAPI, Request import time app = FastAPI() @app.middleware("http") async def timing_middleware(request: Request, call_next): start_time = time.time() response = await call_next(request) duration = time.time() - start_time response.headers["X-Process-Time"] = str(duration) return response
The middleware function uses @app.middleware("http") decorator.
call_next(request) calls the next handler and returns the response.
from fastapi import FastAPI, Request import time app = FastAPI() @app.middleware("http") async def add_process_time_header(request: Request, call_next): start = time.time() response = await call_next(request) process_time = time.time() - start response.headers["X-Process-Time"] = str(process_time) return response
from fastapi import FastAPI, Request import time app = FastAPI() @app.middleware("http") async def log_request_time(request: Request, call_next): start = time.time() response = await call_next(request) duration = time.time() - start print(f"Request to {request.url.path} took {duration:.4f} seconds") return response
This FastAPI app has middleware that measures how long each request takes. It adds the time in seconds as a header called X-Process-Time. The root endpoint returns a simple greeting.
from fastapi import FastAPI, Request import time app = FastAPI() @app.middleware("http") async def timing_middleware(request: Request, call_next): start_time = time.time() response = await call_next(request) duration = time.time() - start_time response.headers["X-Process-Time"] = str(duration) return response @app.get("/") async def read_root(): return {"message": "Hello, world!"}
Middleware runs for every request before and after the main handler.
Use time.time() to get current time in seconds.
Adding timing info in headers helps clients see performance without changing response body.
Request timing middleware measures how long each request takes.
It uses @app.middleware("http") and call_next(request).
Timing info can be added to response headers or logged for monitoring.
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
