Debian Codegraph @

docs/topics/compression.rst

raw
1 Compression
2 ===========
3
4 .. currentmodule:: websockets.extensions.permessage_deflate
5
6 Most WebSocket servers exchange JSON messages because they're convenient to
7 parse and serialize in a browser. These messages contain text data and tend to
8 be repetitive.
9
10 This makes the stream of messages highly compressible. Compressing messages
11 can reduce network traffic by more than 80%.
12
13 websockets implements WebSocket Per-Message Deflate, a compression extension
14 based on the Deflate_ algorithm specified in :rfc:`7692`.
15
16 .. _Deflate: https://en.wikipedia.org/wiki/Deflate
17
18 :func:`~websockets.asyncio.client.connect` and
19 :func:`~websockets.asyncio.server.serve` enable compression by default because
20 the reduction in network bandwidth is usually worth the additional memory and
21 CPU cost.
22
23 Configuring compression
24 -----------------------
25
26 To disable compression, set ``compression=None``::
27
28 connect(..., compression=None, ...)
29
30 serve(..., compression=None, ...)
31
32 To customize compression settings, enable the Per-Message Deflate extension
33 explicitly with :class:`ClientPerMessageDeflateFactory` or
34 :class:`ServerPerMessageDeflateFactory`::
35
36 from websockets.extensions import permessage_deflate
37
38 connect(
39 ...,
40 extensions=[
41 permessage_deflate.ClientPerMessageDeflateFactory(
42 server_max_window_bits=11,
43 client_max_window_bits=11,
44 compress_settings={"memLevel": 4},
45 ),
46 ],
47 )
48
49 serve(
50 ...,
51 extensions=[
52 permessage_deflate.ServerPerMessageDeflateFactory(
53 server_max_window_bits=11,
54 client_max_window_bits=11,
55 compress_settings={"memLevel": 4},
56 ),
57 ],
58 )
59
60 The Window Bits and Memory Level values in these examples reduce memory usage
61 at the expense of compression rate.
62
63 Compression parameters
64 ----------------------
65
66 When a client and a server enable the Per-Message Deflate extension, they
67 negotiate two parameters to guarantee compatibility between compression and
68 decompression. These parameters affect the trade-off between compression rate
69 and memory usage for both sides.
70
71 * **Context Takeover** means that the compression context is retained between
72 messages. In other words, compression is applied to the stream of messages
73 rather than to each message individually.
74
75 Context takeover should remain enabled to get good performance on
76 applications that send a stream of messages with similar structure,
77 that is, most applications.
78
79 This requires retaining the compression context and state between messages,
80 which increases the memory footprint of a connection.
81
82 * **Window Bits** controls the size of the compression context. It must be an
83 integer between 9 (lowest memory usage) and 15 (best compression). Setting it
84 to 8 is possible but rejected by some versions of zlib and not very useful.
85
86 On the server side, websockets defaults to 12. Specifically, the compression
87 window size (server to client) is always 12 while the decompression window
88 (client to server) size may be 12 or 15 depending on whether the client
89 supports configuring it.
90
91 On the client side, websockets lets the server pick a suitable value, which
92 has the same effect as defaulting to 15.
93
94 :mod:`zlib` offers additional parameters for tuning compression. They control
95 the trade-off between compression rate, memory usage, and CPU usage for
96 compressing. They're transparent for decompressing.
97
98 * **Memory Level** controls the size of the compression state. It must be an
99 integer between 1 (lowest memory usage) and 9 (best compression).
100
101 websockets defaults to 5. This is lower than zlib's default of 8. Not only
102 does a lower memory level reduce memory usage, but it can also increase
103 speed thanks to memory locality.
104
105 * **Compression Level** controls the effort to optimize compression. It must
106 be an integer between 1 (lowest CPU usage) and 9 (best compression).
107
108 websockets relies on the default value chosen by :func:`~zlib.compressobj`,
109 ``Z_DEFAULT_COMPRESSION``.
110
111 * **Strategy** selects the compression strategy. The best choice depends on
112 the type of data being compressed.
113
114 websockets relies on the default value chosen by :func:`~zlib.compressobj`,
115 ``Z_DEFAULT_STRATEGY``.
116
117 To customize these parameters, add keyword arguments for
118 :func:`~zlib.compressobj` in ``compress_settings``.
119
120 Default settings for servers
121 ----------------------------
122
123 By default, websockets enables compression with conservative settings that
124 optimize memory usage at the cost of a slightly worse compression rate:
125 Window Bits = 12 and Memory Level = 5. This strikes a good balance for small
126 messages that are typical of WebSocket servers.
127
128 Here's an example of how compression settings affect memory usage per
129 connection, compressed size, and compression time for a corpus of JSON
130 documents.
131
132 =========== ============ ============ ================ ================
133 Window Bits Memory Level Memory usage Size vs. default Time vs. default
134 =========== ============ ============ ================ ================
135 15 8 316 KiB -10% +10%
136 14 7 172 KiB -7% +5%
137 13 6 100 KiB -3% +2%
138 **12** **5** **64 KiB** **=** **=**
139 11 4 46 KiB +10% -4%
140 10 3 37 KiB +70% -40%
141 9 2 33 KiB +130% -90%
142 — — 14 KiB +350% —
143 =========== ============ ============ ================ ================
144
145 Window Bits and Memory Level don't have to move in lockstep. However, other
146 combinations don't yield significantly better results than those shown above.
147
148 websockets defaults to Window Bits = 12 and Memory Level = 5 to stay away from
149 Window Bits = 10 or Memory Level = 3 where performance craters, raising doubts
150 on what could happen at Window Bits = 11 and Memory Level = 4 on a different
151 corpus.
152
153 Defaults must be safe for all applications, hence a more conservative choice.
154
155 Optimizing settings
156 -------------------
157
158 Compressed size and compression time depend on the structure of messages
159 exchanged by your application. As a consequence, default settings may not be
160 optimal for your use case.
161
162 To compare how various compression settings perform for your use case:
163
164 1. Create a corpus of typical messages in a directory, one message per file.
165 2. Run the `compression/benchmark.py`_ script, passing the directory in
166 argument.
167
168 The script measures compressed size and compression time for all combinations of
169 Window Bits and Memory Level. It outputs two tables with absolute values and two
170 tables with values relative to websockets' default settings.
171
172 Pick your favorite settings in these tables and configure them as shown above.
173
174 .. _compression/benchmark.py: https://github.com/python-websockets/websockets/blob/main/experiments/compression/benchmark.py
175
176 Default settings for clients
177 ----------------------------
178
179 By default, websockets enables compression with Memory Level = 5 but leaves
180 the Window Bits setting up to the server.
181
182 There's two good reasons and one bad reason for not optimizing Window Bits on
183 the client side as on the server side:
184
185 1. If the maintainers of a server configured some optimized settings, we don't
186 want to override them with more restrictive settings.
187
188 2. Optimizing memory usage doesn't matter very much for clients because it's
189 uncommon to open thousands of client connections in a program.
190
191 3. On a more pragmatic and annoying note, some servers misbehave badly when a
192 client configures compression settings. `AWS API Gateway`_ is the worst
193 offender.
194
195 .. _AWS API Gateway: https://github.com/python-websockets/websockets/issues/1065
196
197 Unfortunately, even though websockets is right and AWS is wrong, many users
198 jump to the conclusion that websockets doesn't work.
199
200 Until the ecosystem levels up, interoperability with buggy servers seems
201 more valuable than optimizing memory usage.
202
203 Decompression
204 -------------
205
206 The discussion above focuses on compression because it's more expensive than
207 decompression. Indeed, leaving aside small allocations, theoretical memory
208 usage is:
209
210 * ``(1 << (windowBits + 2)) + (1 << (memLevel + 9))`` for compression;
211 * ``1 << windowBits`` for decompression.
212
213 CPU usage is also higher for compression than decompression.
214
215 While it's always possible for a server to use a smaller window size for
216 compressing outgoing messages, using a smaller window size for decompressing
217 incoming messages requires collaboration from clients.
218
219 When a client doesn't support configuring the size of its compression window,
220 websockets enables compression with the largest possible decompression window.
221 In most use cases, this is more efficient than disabling compression both ways.
222
223 If you are very sensitive to memory usage, you can reverse this behavior by
224 setting the ``require_client_max_window_bits`` parameter of
225 :class:`ServerPerMessageDeflateFactory` to ``True``.
226
227 Further reading
228 ---------------
229
230 This `blog post by Ilya Grigorik`_ provides more details about how compression
231 settings affect memory usage and how to optimize them.
232
233 .. _blog post by Ilya Grigorik: https://www.igvita.com/2013/11/27/configuring-and-optimizing-websocket-compression/
234
235 This `experiment by Peter Thorson`_ recommends Window Bits = 11 and Memory
236 Level = 4 for optimizing memory usage.
237
238 .. _experiment by Peter Thorson: https://mailarchive.ietf.org/arch/msg/hybi/F9t4uPufVEy8KBLuL36cZjCmM_Y/