How do you inspect WebSocket close codes in FastAPI?

Tests WebSocket lifecycle handling in FastAPI. Strong answers catch the disconnect exception, read its code attribute, and log 1000 for normal closures versus 1001/1006 for crashes.
WHAT THIS TESTS: This question tests whether you understand the WebSocket lifecycle beyond the basic send-and-receive loop. Interviewers want to see that you know how FastAPI surfaces connection teardowns, that you have operational awareness around observability, and that you can distinguish between clean client shutdowns and infrastructure or client failures.
A GOOD ANSWER COVERS: First, state that the server detects a closed WebSocket by catching the disconnect exception inside the endpoint's message loop. Second, explain that the exception object carries a code attribute that contains the WebSocket close code sent by the client or generated by the server framework. Third, mention common codes: 1000 means a normal closure initiated by the client, 1001 means the endpoint is going away, and 1006 indicates an abnormal drop where no close frame was received. Fourth, connect this to logging by saying you would emit structured logs with the code and client identifier so that dashboards can alert on 1006 spikes while ignoring routine 1000 disconnects.
COMMON WRONG ANSWERS: A major red flag is claiming that FastAPI does not expose the close code and that you must track connection state manually with ping-pong messages. Another is catching a generic Exception instead of the specific disconnect exception, which obscures the code and makes debugging harder. Some candidates also conflate HTTP status codes with WebSocket close codes, suggesting you would return a 404 or 500 response from a WebSocket endpoint.
LIKELY FOLLOW-UPS: The interviewer might ask how you would handle a burst of 1006 codes from many clients simultaneously, which tests whether you consider rate limiting or circuit breakers. They might also ask how to send a specific close code from the server side when shutting down intentionally, or how this integrates with ASGI lifespan events during deployment rollouts.
ONE CONCRETE EXAMPLE: Imagine a chat application where mobile clients disconnect when users lock their phones. If you log all disconnects as errors, your on-call rotation will burn out. Instead, you catch the disconnect exception, check if the code is 1000, and log that at INFO level. If you see 1006, you log at WARNING and increment a metric, because it suggests the client crashed or the load balancer dropped the connection unexpectedly.
Read the original → fastapi.tiangolo.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.