GZipMiddleware does not flush compressed bytes for streaming response chunk #3231
Unanswered
janbjorge
asked this question in
Potential Issue
Replies: 2 comments 2 replies
-
|
MRE with Starlette please |
Beta Was this translation helpful? Give feedback.
1 reply
-
|
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
GZipMiddlewarenever callsgzip_file.flush()for intermediate streaming chunks (more_body=True). The zlib compressor holds output in its internal buffer and only releases bytes when its ~32KB threshold is exceeded or the stream closes. This effectively destroys progressive delivery for streaming responses.Minimal Reproducible Example
Output:
Chunk 0 emits only the 10-byte gzip header. Chunks 1-9 produce 0 bytes — all compressed data is released only when the stream closes.
Proposed fix
Add
self.gzip_file.flush()for intermediate chunks.GzipFile.flush()issues a zlibZ_SYNC_FLUSH, which forces all pending compressed bytes to be emitted:References
Z_SYNC_FLUSH: "all pending output is flushed to the output buffer and the output is aligned on a byte boundary, so that the decompressor can get all input data available so far"GzipFile.flush()defaults tozlib_mode=zlib.Z_SYNC_FLUSHBeta Was this translation helpful? Give feedback.
All reactions