Skip to content

stream: reuse pooled output buffer in Writer to eliminate O(N^2) write allocations - #176

Closed
AliDatadog wants to merge 3 commits into
1.xfrom
ali.b/opt-stream-writer-allocs
Closed

AliDatadog wants to merge 3 commits into
1.xfrom
ali.b/opt-stream-writer-allocs

Conversation

@AliDatadog

@AliDatadog AliDatadog commented Nov 25, 2026 •

Copy link
Copy Markdown

Problem

In production Go allocation profiling of the internal Datadog Agent fleet (service:datadog-agent, 4-hour alloc-size profile, 267 MiB/min total), streaming zstd compression accounts for 15.32% of all Agent Go heap allocations:

  • 8.75% in log batching (streaming small ~300–500 byte log lines into a new writer per batch).
  • 6.57% in metrics serialization (streaming large chunks + flushing).

Across internal Go backend services (language:go env:prod), google.golang.org/grpc zstd compression ((*Writer).Write:167) also accounts for 9.28% of all DataDog/zstd allocations (~19 MiB/min).

Today, a streaming writer starts with a ~1.5 KiB output buffer (CompressBound(1024)). When a caller streams small writes until libzstd flushes a full compressed block (typically 20–50 KiB), the output buffer fills mid-write and grows repeatedly by only CompressBound(remaining_input) (~400 bytes at a time), copying the entire buffer on each step — O(N²) reallocation and copying (~7.7 MB of garbage to compress 200 KB of logs). On large writes, every writer also allocates a fresh CompressBound(len(p)) output buffer instead of streaming through a bounded buffer.

Solution

  • Borrow a pooled output buffer sized to ZSTD_CStreamOutSize() (~128 KiB, libzstd's recommended streaming output size, matching the existing reader pool pattern in this file) when creating a writer, and return it to the pool on close.
  • In Write, Flush, and Close, flush compressed chunks directly to the underlying io.Writer whenever bytes_written > 0 instead of accumulating and reallocating the output buffer.
  • Guard Write and Flush after Close with an explicit closed-writer error, and skip zero-byte writes to the underlying io.Writer.

Proven Results

End-to-End Datadog Agent Single Machine Performance (SMP)

Tested end-to-end on datadog-agent via spike PR DataDog/datadog-agent#61387 (SMP Regression Detector report, Job ID 493e0946-2b62-4991-83cf-4c93f529e0de, baseline 07dd2ae9de):

  • Optimization goals: ✅ Improvement detected, zero regressions across all 11 experiments.
  • quality_gate_logs (% CPU utilization): −5.05% (90% CI [−6.10%, −3.99%]).
  • dsd_uds_10mb_3k_timestamped_contexts_cpu (% CPU utilization): −0.87% (90% CI [−1.15%, −0.59%]).
  • quality_gate_metrics_logs (memory utilization): −0.46% (90% CI [−0.68%, −0.24%]).
  • dsd_uds_10mb_3k_timestamped_contexts_memory (memory utilization): −0.33% (90% CI [−0.52%, −0.13%]).
  • All Linux amd64/arm64 Agent unit tests passed.

Local Microbenchmarks

Measured locally on Apple M4 Max (arm64) with go test -bench=BenchmarkStreamWriter -benchmem -count=5 (medians):

Scenario Before (1.x) After Delta
Small writes (500 × 400 B semi-compressible log lines per writer) 1,511,013 ns/op, 7,679,137 B/op, 269 allocs/op 857,854 ns/op, 236 B/op, 2 allocs/op −43.2% time, −99.997% B/op, −99.3% allocs
Large writes (4 × 256 KiB + Flush per writer) 139,516 ns/op, 271,624 B/op, 4 allocs/op 139,225 ns/op, 168 B/op, 2 allocs/op −99.94% B/op, −50.0% allocs

All existing tests plus new tests for Write/Flush after Close and NewWriterLevelDict + SetNbWorkers(2) multi-chunk round-trip pass under go test -race ./... and all 11 CI jobs (golang-1.24/1.25/1.26, external-libzstd, efence, i386).

Why This Approach

  • Chosen: Streaming chunks directly to the underlying writer through a pooled ZSTD_CStreamOutSize() buffer. This matches libzstd's streaming contract and the existing reader pool pattern in zstd_stream.go, eliminates O(N²) buffer growth on small writes and per-writer buffer allocations on large writes, and adds no API changes.
  • Not chosen: Growing the buffer exponentially (2×) without pooling, which would still allocate ~128–256 KiB per short-lived writer.

Remaining Limits

  • Callers that never call Close() will not return the pooled buffer (it is garbage-collected normally with no leak).
  • Standard io.Writer contract requires the underlying writer not to retain the slice passed to Write (already relied on by Flush and Close).

Internal production baseline notebook (Datadog employees): https://app.datadoghq.com/notebook/16529155

🤖 Generated with Claude Code

…ng in Writer

Stream compressed output directly to the underlying writer through a
pooled ZSTD_CStreamOutSize() buffer instead of growing dstBuffer in an
O(N^2) loop during small writes or allocating CompressBound(len(p)) on
large writes.

Co-Authored-By: Claude <noreply@anthropic.com>
@AliDatadog
AliDatadog marked this pull request as ready for review November 25, 2026 14:50
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-25T15:27:51.305133Z 8c43f38 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

…ound-trip

Co-Authored-By: Claude <noreply@anthropic.com>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 8c43f3828a

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread zstd_stream_test.go
Comment on lines +442 to +443
if err := w.SetNbWorkers(2); err != nil {
t.Fatalf("SetNbWorkers failed: %v", err)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Skip the worker test when parallel compression is unsupported

When testing with the supported external_libzstd build tag against a libzstd compiled without multithreading, SetNbWorkers(2) returns ErrNoParallelSupport, so this new test fails even though compression remains functional. The existing testCompressionDecompression helper explicitly skips this configuration. Handle ErrNoParallelSupport with t.Skip here as well, while retaining the failure for other errors, so the test suite continues to support single-threaded external libraries.

Useful? React with 👍 / 👎.

@AliDatadog

Copy link
Copy Markdown
Author

Closing for now; after measuring the org2 fleet impact (~0.3–0.6% CPU across the Agent fleet), not worth chasing right now.

@AliDatadog AliDatadog closed this Nov 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant