How It Works Features Pricing Blog Error Guides
Log In Start Free Trial
FastAPI · Python

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

Traceback (most recent call last): File "/app/venv/lib/python3.11/site-packages/uvicorn/protocols/websockets/wsproto_impl.py", line 244, in run_asgi result = await self.app(self.scope, self.receive, self.send) File "/app/venv/lib/python3.11/site-packages/starlette/routing.py", line 677, in __call__ await route.handle(scope, receive, send) File "/app/venv/lib/python3.11/site-packages/starlette/routing.py", line 275, in handle await self.app(scope, receive, send) File "/app/venv/lib/python3.11/site-packages/starlette/routing.py", line 75, in app await func(session) File "/app/src/routes/chat.py", line 22, in websocket_chat data = await websocket.receive_text() File "/app/venv/lib/python3.11/site-packages/starlette/websockets.py", line 131, in receive_text await self.receive() starlette.websockets.WebSocketDisconnect: 1000

Here's what each line means:

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.

Before (broken)
@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}")
After (fixed)
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:

  1. Notice the error alert or see it in your monitoring tool
  2. Open the error dashboard and read the stack trace
  3. Identify the file and line number from the stack trace
  4. Open your IDE and navigate to the file
  5. Read the surrounding code to understand context
  6. Reproduce the error locally
  7. Identify the root cause
  8. Write the fix
  9. Run the test suite locally
  10. Fix any failing tests
  11. Write new tests covering the edge case
  12. Run the full test suite again
  13. Create a new git branch
  14. Commit and push your changes
  15. Open a pull request
  16. Wait for code review
  17. Merge and deploy to production
  18. 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:

  1. Captures the stack trace and request context
  2. Pulls the relevant source files from your GitHub repo
  3. Analyzes the error and understands the code context
  4. Generates a minimal, verified fix
  5. Runs your existing test suite
  6. Pushes through your CI/CD pipeline
  7. 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)

  1. Run the test suite locally to confirm WebSocket connections and disconnections are handled.
  2. Open a pull request with the disconnect handling fix.
  3. Wait for CI checks to pass on the PR.
  4. Have a teammate review and approve the PR.
  5. 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.