Fix WebSocketDisconnect: starlette.websockets.WebSocketDisconnect: 1000 in FastAPI
This error occurs when a WebSocket client disconnects and the server tries to send or receive data on the closed connection without handling the disconnection. Fix it by wrapping your WebSocket receive/send loop in a try/except block that catches WebSocketDisconnect and performs cleanup instead of crashing.
Reading the Stack Trace
Here's what each line means:
- File "/app/src/routes/chat.py", line 22, in websocket_chat: The WebSocket endpoint is blocked waiting for receive_text() when the client disconnects, raising WebSocketDisconnect.
- File "/app/venv/lib/python3.11/site-packages/starlette/websockets.py", line 131, in receive_text: Starlette's receive_text raises WebSocketDisconnect when the underlying connection is closed by the client.
- starlette.websockets.WebSocketDisconnect: 1000: Code 1000 indicates a normal closure by the client. The server should handle this gracefully rather than letting it propagate as an unhandled exception.
Common Causes
1. No try/except around receive loop
The WebSocket receive loop does not catch WebSocketDisconnect, so a normal client disconnect crashes the handler.
@app.websocket("/ws/chat")
async def websocket_chat(websocket: WebSocket):
await websocket.accept()
while True:
data = await websocket.receive_text()
await websocket.send_text(f"Echo: {data}")
2. Missing client removal from connection manager
The WebSocket handler does not remove the client from the active connections list on disconnect, causing errors when broadcasting.
class ConnectionManager:
def __init__(self):
self.active_connections: list[WebSocket] = []
async def broadcast(self, message: str):
for connection in self.active_connections:
await connection.send_text(message) # Fails on disconnected clients
3. Sending after disconnect
The handler attempts to send a farewell message after catching the disconnect, which raises another error.
@app.websocket("/ws/chat")
async def websocket_chat(websocket: WebSocket):
await websocket.accept()
try:
while True:
data = await websocket.receive_text()
await websocket.send_text(f"Echo: {data}")
except WebSocketDisconnect:
await websocket.send_text("Goodbye") # Cannot send to closed socket
The Fix
Wrap the receive loop in a try/except that catches WebSocketDisconnect. On disconnect, remove the client from the connection manager and notify remaining clients. This prevents the unhandled exception and properly cleans up resources.
@app.websocket("/ws/chat")
async def websocket_chat(websocket: WebSocket):
await websocket.accept()
while True:
data = await websocket.receive_text()
await websocket.send_text(f"Echo: {data}")
from starlette.websockets import WebSocketDisconnect
@app.websocket("/ws/chat")
async def websocket_chat(websocket: WebSocket):
await websocket.accept()
manager.connect(websocket)
try:
while True:
data = await websocket.receive_text()
await manager.broadcast(f"Message: {data}")
except WebSocketDisconnect:
manager.disconnect(websocket)
await manager.broadcast("A user left the chat.")
Testing the Fix
import pytest
from fastapi.testclient import TestClient
from app.main import app
client = TestClient(app)
def test_websocket_connect_and_send():
with client.websocket_connect("/ws/chat") as websocket:
websocket.send_text("Hello")
data = websocket.receive_text()
assert "Hello" in data
def test_websocket_disconnect_handled_gracefully():
with client.websocket_connect("/ws/chat") as websocket:
websocket.send_text("Hello")
websocket.receive_text()
# No exception should be raised after the context manager closes
def test_websocket_multiple_messages():
with client.websocket_connect("/ws/chat") as websocket:
for i in range(5):
websocket.send_text(f"Message {i}")
data = websocket.receive_text()
assert f"Message {i}" in data
Run your tests:
pytest tests/test_websocket.py -v
Pushing Through CI/CD
git checkout -b fix/fastapi-websocket-disconnect,git add src/routes/chat.py tests/test_websocket.py,git commit -m "fix: handle WebSocketDisconnect with try/except and cleanup",git push origin fix/fastapi-websocket-disconnect
Your CI config should look something like this:
name: CI
on:
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: '3.11'
cache: 'pip'
- run: pip install -r requirements.txt
- run: pytest --tb=short -q
The Full Manual Process: 18 Steps
Here's every step you just went through to fix this one bug:
- Notice the error alert or see it in your monitoring tool
- Open the error dashboard and read the stack trace
- Identify the file and line number from the stack trace
- Open your IDE and navigate to the file
- Read the surrounding code to understand context
- Reproduce the error locally
- Identify the root cause
- Write the fix
- Run the test suite locally
- Fix any failing tests
- Write new tests covering the edge case
- Run the full test suite again
- Create a new git branch
- Commit and push your changes
- Open a pull request
- Wait for code review
- Merge and deploy to production
- Monitor production to confirm the error is resolved
Total time: 30-60 minutes. For one bug.
Or Let bugstack Fix It in Under 2 minutes
Every step above? bugstack does it automatically.
Step 1: Install the SDK
pip install bugstack
Step 2: Initialize
import bugstack
bugstack.init(api_key=os.environ["BUGSTACK_API_KEY"])
Step 3: There is no step 3.
bugstack handles everything from here:
- Captures the stack trace and request context
- Pulls the relevant source files from your GitHub repo
- Analyzes the error and understands the code context
- Generates a minimal, verified fix
- Runs your existing test suite
- Pushes through your CI/CD pipeline
- Deploys to production (or opens a PR for review)
Time from error to fix deployed: Under 2 minutes.
Human involvement: zero.
Try bugstack Free →No credit card. 5-minute setup. Cancel anytime.
Deploying the Fix (Manual Path)
- Run the test suite locally to confirm WebSocket connections and disconnections are handled.
- Open a pull request with the disconnect handling fix.
- Wait for CI checks to pass on the PR.
- Have a teammate review and approve the PR.
- Merge to main and verify WebSocket stability under load in staging.
Frequently Asked Questions
BugStack simulates client connections and disconnections, verifies the connection manager properly cleans up, and runs your full test suite to confirm no WebSocket exceptions leak.
BugStack never pushes directly to production. Every fix goes through a pull request with full CI checks, so your team can review the WebSocket handling changes before merging.
Code 1000 is a normal closure, 1001 means the endpoint is going away, 1006 means an abnormal closure (no close frame). Your handler should gracefully handle all of them.
Use an exponential backoff strategy in your frontend WebSocket client. When the connection drops, wait progressively longer before each reconnection attempt to avoid overwhelming the server.