0
0
FastAPIframework~10 mins

Request timing middleware in FastAPI - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Request timing middleware
Incoming HTTP Request
Middleware Start Timer
Pass Request to Endpoint
Endpoint Processes Request
Middleware Stops Timer
Add Timing Info to Response
Send Response Back to Client
The middleware starts a timer when a request arrives, lets the endpoint handle the request, then stops the timer and adds the elapsed time to the response.
Execution Sample
FastAPI
from fastapi import FastAPI, Request
import time

app = FastAPI()

@app.middleware("http")
async def timing_middleware(request: Request, call_next):
    start = time.time()
    response = await call_next(request)
    duration = time.time() - start
    response.headers["X-Process-Time"] = str(duration)
    return response
This middleware measures how long each request takes and adds that time in seconds to the response headers.
Execution Table
StepActionTimer Value (seconds)Response Header AddedNotes
1Request received by middlewarestart = current time (e.g. 100.0)NoTimer starts
2Middleware calls endpoint handlerstart = 100.0NoWaiting for endpoint response
3Endpoint processes requeststart = 100.0NoEndpoint runs user code
4Endpoint returns responsestart = 100.0NoResponse ready to send back
5Middleware calculates durationduration = current time - start (e.g. 0.123)NoElapsed time computed
6Middleware adds header 'X-Process-Time'duration = 0.123Yes: 'X-Process-Time': '0.123'Timing info added to response
7Response sent to clientduration = 0.123YesRequest cycle complete
💡 Request processing finished; response sent with timing header
Variable Tracker
VariableStartAfter Step 2After Step 5Final
startundefined100.0 (time at request start)100.0100.0
durationundefinedundefined0.123 (elapsed seconds)0.123
response.headers['X-Process-Time']undefinedundefinedundefined'0.123'
Key Moments - 2 Insights
Why do we call 'await call_next(request)' inside the middleware?
Because 'call_next(request)' runs the next step (the endpoint) and returns its response. We must wait for it to finish to measure total time, as shown in execution_table step 2 and 3.
When is the timing header added to the response?
After the endpoint finishes and returns the response, the middleware calculates duration and adds the header before sending back, as in execution_table step 6.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what happens at step 5?
AThe endpoint processes the request
BThe middleware starts the timer
CThe middleware calculates how long the request took
DThe response is sent to the client
💡 Hint
Check the 'Action' and 'Timer Value' columns at step 5 in the execution_table
At which step is the 'X-Process-Time' header added to the response?
AStep 2
BStep 6
CStep 4
DStep 7
💡 Hint
Look at the 'Response Header Added' column in the execution_table
If the endpoint takes longer, how does the 'duration' variable change in variable_tracker?
AIt becomes larger
BIt becomes smaller
CIt stays the same
DIt becomes zero
💡 Hint
Duration measures elapsed time, so longer endpoint processing means larger duration value in variable_tracker
Concept Snapshot
Request timing middleware in FastAPI:
- Use @app.middleware("http") decorator
- Start timer before calling next handler
- Await call_next(request) to get response
- Calculate elapsed time after response
- Add timing info to response headers
- Return modified response
This tracks how long each request takes.
Full Transcript
This visual execution trace shows how FastAPI request timing middleware works. When a request arrives, the middleware records the current time. It then calls the next handler (the endpoint) and waits for it to finish. After the endpoint returns a response, the middleware calculates how much time passed. It adds this duration as a header named 'X-Process-Time' to the response. Finally, it sends the response back to the client. The execution table breaks down each step, showing when the timer starts, when the endpoint runs, and when the header is added. The variable tracker follows the timer start and duration values. Key moments clarify why we await the next handler and when the header is added. The quiz tests understanding of these steps. This middleware helps measure request processing time simply and clearly.