Python websockets connection closes with a ping timeout
websockets.exceptions.ConnectionClosedErrorShort 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.
Fix it fast
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)2Match what you see, then jump to its fix
- 1
The drop happens after a slow request, a sleep or CPU-heavy work in a handlerA blocking call freezes the event loopFix - 2
The drop appears under heavy traffic, on a fast producer and a slow consumerOne side sends faster than the other can processFix - 3
Drops happen on mobile or long-distance links and not on localhostPacket loss or high latency on the networkFix
- 1
What does the error look like?
websockets.exceptions.ConnectionClosedErrorThe 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.py2Fix
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.pyConfirmed by websockets.readthedocs.io
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.py2Fix
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.pyConfirmed by websockets.readthedocs.io
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.com2Fix
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.pyConfirmed by websockets.readthedocs.io
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:
- stegnor.comMy company site: 804 pages from a Python and Jinja generator, with 15 free browser tools.
- MenuloA restaurant discovery platform in Germany, kept current by a Python ingestion pipeline.
- ShopGoAn e-commerce aggregator with a Python scraping engine behind its catalog, past 10K Google Play downloads.
Related fixes
Back end
Airflow SSHOperator stops a long script with SSH command timed out
airflow.exceptions.AirflowException: SSH command timed out
SSHOperator waits only 10 seconds for a command by default.
3 causes, each with a fixBack end
Python asyncio: Task was destroyed but it is pending
RuntimeWarning: coroutine '...' was never awaited
A task was still unfinished when Python threw it away.
4 causes, each with a fixBack end
Celery in a Django project does not connect to Redis or ignores the broker URL
kombu.exceptions.InconsistencyError: ... _kombu.binding.celery
Celery talks to Redis through a client library and reads its broker URL from your Django settings.
4 causes, each with a fixBack end
Django form POST returns 403 Forbidden: CSRF verification failed
CSRF verification failed. Request aborted.
Django rejects an unsafe request when the CSRF cookie or the form token is missing or wrong, or when the Origin or Referer check fails.
5 causes, each with a fixBack end
Django cannot import corsheaders (django-cors-headers)
ImportError: No module named corsheaders
The pip package is django-cors-headers, but the module Django imports is corsheaders.
3 causes, each with a fixBack end
Django raises NoReverseMatch when building a URL
NoReverseMatch
NoReverseMatch means Django looked for a named URL pattern that fits the name and arguments you gave and found none.
4 causes, each with a fix