python-websockets / websockets

Library for building WebSocket servers and clients in Python
https://websockets.readthedocs.io/
BSD 3-Clause "New" or "Revised" License
5.06k stars 505 forks source link

Sync version of broadcast #1466

Open Phlogistique opened 1 month ago

Phlogistique commented 1 month ago

The library includes a broadcast utility, with detailed documentation and motivation here.

However, today that utility only works with the asyncio API of WebSockets.

That leaves users of the sync API with two possibilities, if they want to broadcast a message without risk of blocking the thread if some client's buffer is full:

It would be nice if the sync API of this library included a ready-made broadcast utility.

aaugustin commented 1 month ago

Yes, that would be nice.

As long as it doesn't exist in the library, I'd recommend against your first option.

Your second option can be implemented quite easily with a ThreadPoolExecutor that will handle the queuing and consuming for you. Given enough threads and a short enough timeout on send(), you can guarantee that the operation will complete within a certain time frame e.g. if you have 50 connections, use 25 threads and a timeout at 5 seconds and you will finish within 10 seconds.

If you have 5000 connections you shouldn't be using the thread-based implementation in the first place :-)

aaugustin commented 1 month ago

Marking as a potential improvement.