Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Node.js, PHP and APIs

Python websockets connection closes with a ping timeout

Errorwebsockets.exceptions.ConnectionClosedError

Short answer

The websockets library sends a ping every 20 seconds and closes the connection if no pong comes back within 20 seconds. Pongs stop when your handler blocks the event loop, when one side is flooded and falls behind, or when the network drops packets. Remove blocking calls first; raise ping_timeout only as a last step.

  • Applies to Python 3.12, websockets 15
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 1Find out which cause you have

    Catch ConnectionClosed and print the close frames. They show who closed the connection and with which code.

    try:
        async for message in websocket:
            ...
    except websockets.exceptions.ConnectionClosed as e:
        print("rcvd:", e.rcvd, "sent:", e.sent)
  2. 2Match what you see, then jump to its fix

    1. 1The drop happens after a slow request, a sleep or CPU-heavy work in a handlerA blocking call freezes the event loopFix
    2. 2The drop appears under heavy traffic, on a fast producer and a slow consumerOne side sends faster than the other can processFix
    3. 3Drops happen on mobile or long-distance links and not on localhostPacket loss or high latency on the networkFix

What does the error look like?

  • websockets.exceptions.ConnectionClosedError
  • The connection closes while the peer is busy or the network is unstable

Cause 1 of 3

A blocking call freezes the event loop

1Check

While the loop is blocked nothing can answer a ping, so the pong never leaves. Look in the handler for time.sleep, synchronous HTTP or database calls, and long computations.

grep -n "time.sleep\|requests\." server.py

2Fix

Replace blocking calls with asynchronous ones. A loop that only awaits send() may never yield, so add await asyncio.sleep(0) inside it.

# before: time.sleep(1)
await asyncio.sleep(1)

for item in items:
    await websocket.send(item)
    await asyncio.sleep(0)

3Verify

Run the same workload for a minute. The connection stays open past several ping intervals.

python server.py

Confirmed by websockets.readthedocs.io

Did this fix it?

Cause 2 of 3

One side sends faster than the other can process

1Check

Data waits in buffers when a sender outruns its peer. If the receiver falls more than 20 seconds behind, it does not see the pong before the timeout.

grep -n "await .*send" server.py

2Fix

Slow the sender down or speed up the consumer. If traffic spikes are brief and the server does catch up, raise ping_timeout.

async with websockets.connect(uri, ping_timeout=60) as ws:
    ...

3Verify

Repeat the load. The connection survives the spike.

python client.py

Confirmed by websockets.readthedocs.io

Did this fix it?

Cause 3 of 3

Packet loss or high latency on the network

1Check

Packet loss causes TCP retransmissions that look like latency, and enough of it makes the connection unusable.

ping -c 20 example.com

2Fix

Fix the network path if you can. Otherwise raise ping_timeout to ride out slow stretches; ping_timeout=None keeps the pings but never closes on a missing pong, so dead connections go unnoticed.

async with websockets.connect(uri, ping_interval=20, ping_timeout=60) as ws:
    ...

3Verify

Repeat the run on the poor link. The connection no longer closes on short slow stretches.

python client.py

Confirmed by websockets.readthedocs.io

Did this fix it?

How do I stop it coming back?

  • Keep handlers fully asynchronous; move CPU-heavy work to a thread or process executor.
  • Leave the default keepalive on so dead connections are found.
  • Log rcvd and sent from ConnectionClosed so you can see who closed the connection.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Which stack is behind this page?

Projects of mine built on the same technologies:

Related fixes

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.