Debian Codegraph @

docs/topics/broadcast.rst

raw
1 Broadcasting
2 ============
3
4 .. currentmodule:: websockets
5
6 .. admonition:: If you want to send a message to all connected clients,
7 use :func:`~asyncio.server.broadcast`.
8 :class: tip
9
10 If you want to learn about its design, continue reading this document.
11
12 For the legacy :mod:`asyncio` implementation, use
13 :func:`~legacy.server.broadcast`.
14
15 WebSocket servers often send the same message to all connected clients or to a
16 subset of clients for which the message is relevant.
17
18 Let's explore options for broadcasting a message, explain the design of
19 :func:`~asyncio.server.broadcast` in the :mod:`asyncio` implementation, and
20 discuss alternatives.
21
22 For each option, we'll provide a connection handler called ``handler()`` and a
23 function or coroutine called ``broadcast()`` that sends a message to all
24 connected clients.
25
26 Integrating them is left as an exercise for the reader. You could start with::
27
28 import asyncio
29 from websockets.asyncio.server import serve
30
31 async def handler(websocket):
32 ...
33
34 async def broadcast(message):
35 ...
36
37 async def broadcast_messages():
38 while True:
39 await asyncio.sleep(1)
40 message = ... # your application logic goes here
41 await broadcast(message)
42
43 async def main():
44 async with serve(handler, "localhost", 8765):
45 await broadcast_messages() # runs forever
46
47 if __name__ == "__main__":
48 asyncio.run(main())
49
50 ``broadcast_messages()`` must yield control to the event loop between each
51 message, or else it will never let the server run. That's why it includes
52 ``await asyncio.sleep(1)``.
53
54 A complete example is available in the `experiments/broadcast`_ directory.
55
56 .. _experiments/broadcast: https://github.com/python-websockets/websockets/tree/main/experiments/broadcast
57
58 The naive way
59 -------------
60
61 The most obvious way to send a message to all connected clients consists in
62 keeping track of them and sending the message to each of them.
63
64 Here's a connection handler that registers clients in a global variable::
65
66 CLIENTS = set()
67
68 async def handler(websocket):
69 CLIENTS.add(websocket)
70 try:
71 await websocket.wait_closed()
72 finally:
73 CLIENTS.remove(websocket)
74
75 This implementation assumes that the client will never send any messages. If
76 you'd rather not make this assumption, you can change::
77
78 await websocket.wait_closed()
79
80 to::
81
82 async for _ in websocket:
83 pass
84
85 Here's a coroutine that broadcasts a message to all clients::
86
87 from websockets.exceptions import ConnectionClosed
88
89 async def broadcast(message):
90 for websocket in CLIENTS.copy():
91 try:
92 await websocket.send(message)
93 except ConnectionClosed:
94 pass
95
96 There are two tricks in this version of ``broadcast()``.
97
98 First, it makes a copy of ``CLIENTS`` before iterating it. Else, if a client
99 connects or disconnects while ``broadcast()`` is running, the loop would fail
100 with::
101
102 RuntimeError: Set changed size during iteration
103
104 Second, it ignores :exc:`~exceptions.ConnectionClosed` exceptions because a
105 client could disconnect between the moment ``broadcast()`` makes a copy of
106 ``CLIENTS`` and the moment it sends a message to this client. This is fine: a
107 client that disconnected doesn't belongs to "all connected clients" anymore.
108
109 The naive way can be very fast. Indeed, if all connections have enough free
110 space in their write buffers, ``await websocket.send(message)`` writes the
111 message and returns immediately, as it doesn't need to wait for the buffer to
112 drain. In this case, ``broadcast()`` doesn't yield control to the event loop,
113 which minimizes overhead.
114
115 The naive way can also fail badly. If the write buffer of a connection reaches
116 ``write_limit``, ``broadcast()`` waits for the buffer to drain before sending
117 the message to other clients. This can cause a massive drop in performance.
118
119 As a consequence, this pattern works only when write buffers never fill up,
120 which is usually outside of the control of the server.
121
122 If you know for sure that you will never write more than ``write_limit`` bytes
123 within ``ping_interval + ping_timeout``, then websockets will terminate slow
124 connections before the write buffer can fill up.
125
126 Don't set extreme values of ``write_limit``, ``ping_interval``, or
127 ``ping_timeout`` to ensure that this condition holds! Instead, set reasonable
128 values and use the built-in :func:`~asyncio.server.broadcast` function.
129
130 The concurrent way
131 ------------------
132
133 The naive way didn't work well because it serialized writes, while the whole
134 point of asynchronous I/O is to perform I/O concurrently.
135
136 Let's modify ``broadcast()`` to send messages concurrently::
137
138 async def send(websocket, message):
139 try:
140 await websocket.send(message)
141 except ConnectionClosed:
142 pass
143
144 def broadcast(message):
145 for websocket in CLIENTS:
146 asyncio.create_task(send(websocket, message))
147
148 We move the error handling logic in a new coroutine and we schedule
149 a :class:`~asyncio.Task` to run it instead of executing it immediately.
150
151 Since ``broadcast()`` no longer awaits coroutines, we can make it a function
152 rather than a coroutine and do away with the copy of ``CLIENTS``.
153
154 This version of ``broadcast()`` makes clients independent from one another: a
155 slow client won't block others. As a side effect, it makes messages
156 independent from one another.
157
158 If you broadcast several messages, there is no strong guarantee that they will
159 be sent in the expected order. Fortunately, the event loop runs tasks in the
160 order in which they are created, so the order is correct in practice.
161
162 Technically, this is an implementation detail of the event loop. However, it
163 seems unlikely for an event loop to run tasks in an order other than FIFO.
164
165 If you wanted to enforce the order without relying this implementation detail,
166 you could be tempted to wait until all clients have received the message::
167
168 async def broadcast(message):
169 if CLIENTS: # asyncio.wait doesn't accept an empty list
170 await asyncio.wait([
171 asyncio.create_task(send(websocket, message))
172 for websocket in CLIENTS
173 ])
174
175 However, this doesn't really work in practice. Quite often, it will block
176 until the slowest client times out.
177
178 Backpressure meets broadcast
179 ----------------------------
180
181 At this point, it becomes apparent that backpressure, usually a good practice,
182 doesn't work well when broadcasting a message to thousands of clients.
183
184 When you're sending messages to a single client, you don't want to send them
185 faster than the network can transfer them and the client accept them. This is
186 why :meth:`~asyncio.server.ServerConnection.send` checks if the write buffer is
187 above the high-water mark and, if it is, waits until it drains, giving the
188 network and the client time to catch up. This provides backpressure.
189
190 Without backpressure, you could pile up data in the write buffer until the
191 server process runs out of memory and the operating system kills it.
192
193 The :meth:`~asyncio.server.ServerConnection.send` API is designed to enforce
194 backpressure by default. This helps users of websockets write robust programs
195 even if they never heard about backpressure.
196
197 For comparison, :class:`asyncio.StreamWriter` requires users to understand
198 backpressure and to await :meth:`~asyncio.StreamWriter.drain` after each
199 :meth:`~asyncio.StreamWriter.write` — or at least sufficiently frequently.
200
201 When broadcasting messages, backpressure consists in slowing down all clients
202 in an attempt to let the slowest client catch up. With thousands of clients,
203 the slowest one is probably timing out and isn't going to receive the message
204 anyway. So it doesn't make sense to synchronize with the slowest client.
205
206 How do we avoid running out of memory when slow clients can't keep up with the
207 broadcast rate, then? The most straightforward option is to disconnect them.
208
209 If a client gets too far behind, eventually it reaches the limit defined by
210 ``ping_timeout`` and websockets terminates the connection. You can refer to the
211 discussion of :doc:`keepalive <keepalive>` for details.
212
213 How :func:`~asyncio.server.broadcast` works
214 -------------------------------------------
215
216 The built-in :func:`~asyncio.server.broadcast` function is similar to the naive
217 way. The main difference is that it doesn't apply backpressure.
218
219 This provides the best performance by avoiding the overhead of scheduling and
220 running one task per client.
221
222 Also, when sending text messages, encoding to UTF-8 happens only once rather
223 than once per client, providing a small performance gain.
224
225 Per-client queues
226 -----------------
227
228 At this point, we deal with slow clients rather brutally: we disconnect then.
229
230 Can we do better? For example, we could decide to skip or to batch messages,
231 depending on how far behind a client is.
232
233 To implement this logic, we can create a queue of messages for each client and
234 run a task that gets messages from the queue and sends them to the client::
235
236 import asyncio
237
238 CLIENTS = set()
239
240 async def relay(queue, websocket):
241 while True:
242 # Implement custom logic based on queue.qsize() and
243 # websocket.transport.get_write_buffer_size() here.
244 message = await queue.get()
245 await websocket.send(message)
246
247 async def handler(websocket):
248 queue = asyncio.Queue()
249 relay_task = asyncio.create_task(relay(queue, websocket))
250 CLIENTS.add(queue)
251 try:
252 await websocket.wait_closed()
253 finally:
254 CLIENTS.remove(queue)
255 relay_task.cancel()
256
257 Then we can broadcast a message by pushing it to all queues::
258
259 def broadcast(message):
260 for queue in CLIENTS:
261 queue.put_nowait(message)
262
263 The queues provide an additional buffer between the ``broadcast()`` function
264 and clients. This makes it easier to support slow clients without excessive
265 memory usage because queued messages aren't duplicated to write buffers
266 until ``relay()`` processes them.
267
268 Publish–subscribe
269 -----------------
270
271 Can we avoid centralizing the list of connected clients in a global variable?
272
273 If each client subscribes to a stream a messages, then broadcasting becomes as
274 simple as publishing a message to the stream.
275
276 Here's a message stream that supports multiple consumers::
277
278 class PubSub:
279 def __init__(self):
280 self.waiter = asyncio.get_running_loop().create_future()
281
282 def publish(self, value):
283 waiter = self.waiter
284 self.waiter = asyncio.get_running_loop().create_future()
285 waiter.set_result((value, self.waiter))
286
287 async def subscribe(self):
288 waiter = self.waiter
289 while True:
290 value, waiter = await waiter
291 yield value
292
293 __aiter__ = subscribe
294
295 PUBSUB = PubSub()
296
297 The stream is implemented as a linked list of futures. It isn't necessary to
298 synchronize consumers. They can read the stream at their own pace,
299 independently from one another. Once all consumers read a message, there are
300 no references left, therefore the garbage collector deletes it.
301
302 The connection handler subscribes to the stream and sends messages::
303
304 async def handler(websocket):
305 async for message in PUBSUB:
306 await websocket.send(message)
307
308 The broadcast function publishes to the stream::
309
310 def broadcast(message):
311 PUBSUB.publish(message)
312
313 Like per-client queues, this version supports slow clients with limited memory
314 usage. Unlike per-client queues, it makes it difficult to tell how far behind
315 a client is. The ``PubSub`` class could be extended or refactored to provide
316 this information.
317
318 The ``for`` loop is gone from this version of the ``broadcast()`` function.
319 However, there's still a ``for`` loop iterating on all clients hidden deep
320 inside :mod:`asyncio`. When ``publish()`` sets the result of the ``waiter``
321 future, :mod:`asyncio` loops on callbacks registered with this future and
322 schedules them. This is how connection handlers receive the next value from
323 the asynchronous iterator returned by ``subscribe()``.
324
325 Performance considerations
326 --------------------------
327
328 The built-in :func:`~asyncio.server.broadcast` function sends all messages
329 without yielding control to the event loop. So does the naive way when the
330 network and clients are fast and reliable.
331
332 For each client, a WebSocket frame is prepared and sent to the network. This
333 is the minimum amount of work required to broadcast a message.
334
335 It would be tempting to prepare a frame and reuse it for all connections.
336 However, this isn't possible in general for two reasons:
337
338 * Clients can negotiate different extensions. You would have to enforce the
339 same extensions with the same parameters. For example, you would have to
340 select some compression settings and reject clients that cannot support
341 these settings.
342
343 * Extensions can be stateful, producing different encodings of the same
344 message depending on previous messages. For example, you would have to
345 disable context takeover to make compression stateless, resulting in poor
346 compression rates.
347
348 All other patterns discussed above yield control to the event loop once per
349 client because messages are sent by different tasks. This makes them slower
350 than the built-in :func:`~asyncio.server.broadcast` function.
351
352 There is no major difference between the performance of per-client queues and
353 publish–subscribe.