Debian Codegraph @

docs/topics/keepalive.rst

raw
1 Keepalive and latency
2 =====================
3
4 .. currentmodule:: websockets
5
6 Long-lived connections
7 ----------------------
8
9 Since the WebSocket protocol is intended for real-time communications over
10 long-lived connections, it is desirable to ensure that connections don't
11 break, and if they do, to report the problem quickly.
12
13 Connections can drop as a consequence of temporary network connectivity issues,
14 which are very common, even within data centers.
15
16 Furthermore, WebSocket builds on top of HTTP/1.1 where connections are
17 short-lived, even with ``Connection: keep-alive``. Typically, HTTP/1.1
18 infrastructure closes idle connections after 30 to 120 seconds.
19
20 As a consequence, proxies may terminate WebSocket connections prematurely when
21 no message was exchanged in 30 seconds.
22
23 .. _keepalive:
24
25 Keepalive in websockets
26 -----------------------
27
28 To avoid these problems, websockets runs a keepalive and heartbeat mechanism
29 based on WebSocket Ping_ and Pong_ frames, which are designed for this purpose.
30
31 .. _Ping: https://datatracker.ietf.org/doc/html/rfc6455.html#section-5.5.2
32 .. _Pong: https://datatracker.ietf.org/doc/html/rfc6455.html#section-5.5.3
33
34 It sends a Ping frame every 20 seconds. It expects a Pong frame in return within
35 20 seconds. Else, it considers the connection broken and terminates it.
36
37 This mechanism serves three purposes:
38
39 1. It creates a trickle of traffic so that the TCP connection isn't idle and
40 network infrastructure along the path keeps it open ("keepalive").
41 2. It detects if the connection drops or becomes so slow that it's unusable in
42 practice ("heartbeat"). In that case, it terminates the connection and your
43 application gets a :exc:`~exceptions.ConnectionClosed` exception.
44 3. It measures the :attr:`~asyncio.connection.Connection.latency` of the
45 connection. The time between sending a Ping frame and receiving a matching
46 Pong frame approximates the round-trip time.
47
48 Timings are configurable with the ``ping_interval`` and ``ping_timeout``
49 arguments of :func:`~asyncio.client.connect` and :func:`~asyncio.server.serve`.
50 Shorter values will detect connection drops faster but they will increase
51 network traffic and they will be more sensitive to latency.
52
53 Setting ``ping_interval`` to :obj:`None` disables the whole keepalive and
54 heartbeat mechanism, including measurement of latency.
55
56 Setting ``ping_timeout`` to :obj:`None` disables only timeouts. This enables
57 keepalive, to keep idle connections open, and disables heartbeat, to support large
58 latency spikes.
59
60 .. admonition:: Why doesn't websockets rely on TCP keepalive?
61 :class: hint
62
63 TCP keepalive is disabled by default on most operating systems. When
64 enabled, the default interval is two hours or more, which is far too much.
65
66 Keepalive in browsers
67 ---------------------
68
69 Browsers don't enable a keepalive mechanism like websockets by default. As a
70 consequence, they can fail to notice that a WebSocket connection is broken for
71 an extended period of time, until the TCP connection times out.
72
73 In this scenario, the ``WebSocket`` object in the browser doesn't fire a
74 ``close`` event. If you have a reconnection mechanism, it doesn't kick in
75 because it believes that the connection is still working.
76
77 If your browser-based app mysteriously and randomly fails to receive events,
78 this is a likely cause. You need a keepalive mechanism in the browser to avoid
79 this scenario.
80
81 Unfortunately, the WebSocket API in browsers doesn't expose the native Ping and
82 Pong functionality in the WebSocket protocol. You have to roll your own in the
83 application layer.
84
85 Read this `blog post <https://making.close.com/posts/reliable-websockets/>`_ for
86 a complete walk-through of this issue.
87
88 Application-level keepalive
89 ---------------------------
90
91 Some servers require clients to send a keepalive message with a specific content
92 at regular intervals. Usually they expect Text_ frames rather than Ping_ frames,
93 meaning that you must send them with :attr:`~asyncio.connection.Connection.send`
94 rather than :attr:`~asyncio.connection.Connection.ping`.
95
96 .. _Text: https://datatracker.ietf.org/doc/html/rfc6455.html#section-5.6
97
98 In websockets, such keepalive mechanisms are considered as application-level
99 because they rely on data frames. That's unlike the protocol-level keepalive
100 based on control frames. Therefore, it's your responsibility to implement the
101 required behavior.
102
103 You can run a task in the background to send keepalive messages:
104
105 .. code-block:: python
106
107 import itertools
108 import json
109
110 from websockets.exceptions import ConnectionClosed
111
112 async def keepalive(websocket, ping_interval=30):
113 for ping in itertools.count():
114 await asyncio.sleep(ping_interval)
115 try:
116 await websocket.send(json.dumps({"ping": ping}))
117 except ConnectionClosed:
118 break
119
120 async def main():
121 async with connect(...) as websocket:
122 keepalive_task = asyncio.create_task(keepalive(websocket))
123 try:
124 ... # your application logic goes here
125 finally:
126 keepalive_task.cancel()
127
128 Latency issues
129 --------------
130
131 The :attr:`~asyncio.connection.Connection.latency` attribute stores latency
132 measured during the last exchange of Ping and Pong frames::
133
134 latency = websocket.latency
135
136 Alternatively, you can measure the latency at any time by calling
137 :attr:`~asyncio.connection.Connection.ping` and awaiting its result::
138
139 pong_received = await websocket.ping()
140 latency = await pong_received
141
142 Latency between a client and a server may increase for two reasons:
143
144 * Network connectivity is poor. When network packets are lost, TCP attempts to
145 retransmit them, which manifests as latency. Excessive packet loss makes
146 the connection unusable in practice. At some point, timing out is a
147 reasonable choice.
148
149 * Traffic is high. For example, if a client sends messages on the connection
150 faster than a server can process them, this manifests as latency as well,
151 because data is waiting in :doc:`buffers <memory>`.
152
153 If the server is more than 20 seconds behind, it doesn't see the Pong before
154 the default timeout elapses. As a consequence, it closes the connection.
155 This is a reasonable choice to prevent overload.
156
157 If traffic spikes cause unwanted timeouts and you're confident that the server
158 will catch up eventually, you can increase ``ping_timeout`` or you can set it
159 to :obj:`None` to disable heartbeat entirely.
160
161 The same reasoning applies to situations where the server sends more traffic
162 than the client can accept.