.NET 11 Zstandard Compression in C# with ZstandardStream
.NET 11 provides ZstandardStream in System.IO.Compression. Write data through a compression stream, dispose it so the frame is finalized, and use a decompression stream to recover the bytes. Limit decoded output whenever the input is untrusted.
Where does Zstandard fit?
Zstandard, often called Zstd, is a lossless compression format. It is a candidate for logs, export files and transfers where both ends support it. Choose a format based on interoperability, payload size, CPU budget and measured compression ratio.
| Format | .NET stream | Selection question |
|---|---|---|
| Gzip | GZipStream | Does the existing client or file workflow require Gzip? |
| Brotli | BrotliStream | Does the receiver support Brotli and is the workload suitable? |
| Zstandard | ZstandardStream | Can both sides consume a Zstd frame with the chosen options? |
A compressed stream is a byte format. HTTP content negotiation, intermediaries, and client support are separate concerns. Changing an HTTP response’s compression format requires a deliberate compatibility check.
Round-trip a payload in C
The sample uses .NET 11 without a separate compression package. It leaves the backing stream open while finalizing the encoder. After rewinding the backing stream, it reads the decoded output in chunks and enforces a one-million-byte limit before writing each chunk.
Run dotnet run and expect a verified round-trip message. Change the limit to a small value and confirm the program rejects the decoded output. For large files, replace the in-memory streams with file streams or a bounded destination. Write to a temporary destination and publish the final file only after decoding and validation succeed.
What happens when data is invalid or incomplete?
Reject data from the wrong format and handle decoding errors according to the caller contract. A failed decode can leave partial bytes in the destination. If the input crosses a trust boundary, add limits for input size, decompressed output, duration, and concurrency. Pass cancellation tokens in request-bound code. Keep an application-specific format or version marker where data may be stored and read across deployments.
Compression does not provide cryptographic integrity or confidentiality. If the application requires either, define a separate integrity or authentication mechanism. Avoid compressing attacker-controlled strings together with secrets in an observable security-sensitive response.
Measure your real payloads
Compare the same representative files with the same runtime and machine. Record original bytes, compressed bytes, compression and decompression duration, allocations, and the levels selected for each format. Include very small records, repeated text, and already-compressed data. Report the test setup. A single repeated string demonstrates correctness and says little about production throughput.
Prepare an interoperability check
Keep a known compressed fixture from the other system and decode it with this implementation. Then encode an independent fixture and decode it on the receiver. Exercise empty input, partial writes, a truncated frame and a decoded payload over the configured limit. If the workflow uses dictionaries, record which dictionary was used and test the receiver’s behavior with a missing or incorrect one.
A stream boundary does not tell you which records are safe to process after a failure. For workflows that require atomic import, stage the decoded output, verify the complete input and only then commit the results. The local console check restored 1,700 bytes exactly. It did not benchmark throughput or verify a third-party decoder.
Separate file format, transport and protocol
For an internal export job, choose an extension and document the format so operators know what to use to decode it. For a storage pipeline, record whether the stored blob is compressed and how the consumer discovers the format. For HTTP, check the client and proxy contract before enabling an encoding. A raw compressed file and an HTTP response with content encoding involve different expectations about who performs decompression.
If the receiver already uses Gzip, add a compatibility negotiation or versioned storage contract before switching. A format change can break existing backups and consumers even if the encoder round-trips its own output. Keep fixtures produced by each supported encoder and verify them after runtime upgrades.
Bound resources at every layer
The cap in the example limits how much decompressed data enters the output stream. An application accepting uploads should also bound compressed input and its total processing time. Handle cancellation around network reads and long-running operations. Run concurrent requests under an explicit concurrency limit when expensive decoding could otherwise exhaust CPU.
For files larger than memory, stream into a temporary file in a controlled directory. If decoding fails, discard the partial file and return an error appropriate to the caller. If decoding succeeds, use the application’s normal safe publication step to move the verified file into place. Decide how to clean up interrupted jobs and leave enough temporary space for the worst allowed input.
To test the output limit, choose a limit below 1,700 bytes. The sample should fail before it writes the chunk that would push output over the limit. To test application behavior on a bad frame, keep known invalid fixtures and assert that no partial output becomes an accepted import. A unit test for payload equality and an integration test for cleanup cover different failure modes.
FAQ
Why does decompression see no bytes? Finalize the writer and rewind a seekable stream before reading it.
What does leaveOpen do? It keeps the underlying stream available after disposing the wrapper. The wrapper still must be disposed.
Can I use ZstandardStream in a browser build? Check the platform annotations for the API. The documented stream is unsupported on browser and WASI.
See Zstandard in .NET 11 libraries and the ZstandardStream API.
For the broader platform context, read the ASP.NET PB .NET 11 release overview.
Comments
Post a Comment