| 1 |
Memory usage |
| 2 |
============ |
| 3 |
|
| 4 |
.. currentmodule:: websockets |
| 5 |
|
| 6 |
In most cases, memory usage of a WebSocket server is proportional to the |
| 7 |
number of open connections. When a server handles thousands of connections, |
| 8 |
memory usage can become a bottleneck. |
| 9 |
|
| 10 |
Memory usage of a single connection is the sum of: |
| 11 |
|
| 12 |
1. the baseline amount of memory websockets requires for each connection, |
| 13 |
2. the amount of data held in buffers before the application processes it, |
| 14 |
3. any additional memory allocated by the application itself. |
| 15 |
|
| 16 |
Baseline |
| 17 |
-------- |
| 18 |
|
| 19 |
Compression settings are the main factor affecting the baseline amount of |
| 20 |
memory used by each connection. |
| 21 |
|
| 22 |
With websockets' defaults, on the server side, a single connections uses |
| 23 |
70 KiB of memory. |
| 24 |
|
| 25 |
Refer to the :doc:`topic guide on compression <../topics/compression>` to |
| 26 |
learn more about tuning compression settings. |
| 27 |
|
| 28 |
Buffers |
| 29 |
------- |
| 30 |
|
| 31 |
Under normal circumstances, buffers are almost always empty. |
| 32 |
|
| 33 |
Under high load, if a server receives more messages than it can process, |
| 34 |
bufferbloat can result in excessive memory usage. |
| 35 |
|
| 36 |
By default websockets has generous limits. It is strongly recommended to adapt |
| 37 |
them to your application. When you call :func:`~server.serve`: |
| 38 |
|
| 39 |
- Set ``max_size`` (default: 1 MiB, UTF-8 encoded) to the maximum size of |
| 40 |
messages your application generates. |
| 41 |
- Set ``max_queue`` (default: 32) to the maximum number of messages your |
| 42 |
application expects to receive faster than it can process them. The queue |
| 43 |
provides burst tolerance without slowing down the TCP connection. |
| 44 |
|
| 45 |
Furthermore, you can lower ``read_limit`` and ``write_limit`` (default: |
| 46 |
64 KiB) to reduce the size of buffers for incoming and outgoing data. |
| 47 |
|
| 48 |
The design document provides :ref:`more details about buffers <buffers>`. |