Skip to content

perf(datastreams): reduce allocations in base64 pathway propagation - #5986

Open
darccio wants to merge 1 commit into
mainfrom
darccio/perf-datastreams-base64-propagation
Open

darccio wants to merge 1 commit into
mainfrom
darccio/perf-datastreams-base64-propagation

Conversation

@darccio

@darccio darccio commented Nov 25, 2026

Copy link
Copy Markdown
Member

What does this PR do?

Reduces heap allocations and latency on the Data Streams Monitoring base64 propagation and context hot path in internal/datastreams:

  • Pathway.EncodeBase64 encodes into stack buffers using binary.AppendVarint and base64.StdEncoding.Encode. It allocates only the returned string.
  • DecodeBase64 decodes headers up to 64 bytes into a stack buffer instead of calling base64.StdEncoding.DecodeString.
  • ContextWithPathway returns a dedicated pathwayContext type instead of context.WithValue. This avoids boxing Pathway into any and gives PathwayFromContext a direct type-assertion fast path.
  • Adds benchmarks for EncodeBase64, DecodeBase64, and pathwayHash.

Motivation

Production Go Continuous Profiler data (language:go env:prod) shows datastreams.ExtractFromBase64Carrier, datastreams.InjectToBase64Carrier, Pathway.EncodeBase64, and ContextWithPathway as top heap allocation sources in dd-trace-go.

Benchmarks (5-run medians, Apple M5 Pro, Go 1.27.4):

Benchmark Latency Bytes Allocs
BenchmarkEncodeBase64 41.4 -> 22.2 ns/op (-46.4%) 56 -> 32 B/op (-42.9%) 2 -> 1 (-50.0%)
BenchmarkDecodeBase64 54.6 -> 38.2 ns/op (-30.0%) 136 -> 80 B/op (-41.2%) 3 -> 1 (-66.7%)
BenchmarkSetCheckpoint 216.6 -> 205.2 ns/op (-5.3%) 400 -> 368 B/op (-8.0%) 4 -> 3 (-25.0%)

Verified with go test -race ./internal/datastreams/... ./datastreams/... and make lint/errlog.

Reviewer Checklist

  • Changed code has unit tests for its functionality at or near 100% coverage.
  • System-Tests covering this feature have been added and enabled with the va.b.c-dev version tag.
  • There is a benchmark for any new code, or changes to existing code.
  • If this interacts with the agent in a new way, a system test has been added.
  • New code is free of linting errors.
  • New code does not break existing tests.
  • Add an appropriate team label so this PR gets put in the right place for the release notes.
  • All generated files are up to date.
  • Non-trivial go.mod changes are reviewed by @DataDog/dd-trace-go-guild.

Use stack buffers with binary.AppendVarint in Pathway.EncodeBase64 and
base64.StdEncoding.Decode in DecodeBase64. Replace context.WithValue
with a dedicated pathwayContext type to avoid boxing Pathway into any.

Benchmarks (5-run medians, Apple M5 Pro, Go 1.27.4):
- BenchmarkEncodeBase64: 41.4 -> 22.2 ns/op (-46.4%), 56 -> 32 B/op, 2 -> 1 alloc/op
- BenchmarkDecodeBase64: 54.6 -> 38.2 ns/op (-30.0%), 136 -> 80 B/op, 3 -> 1 alloc/op
- BenchmarkSetCheckpoint: 216.6 -> 205.2 ns/op (-5.3%), 400 -> 368 B/op, 4 -> 3 allocs/op
@darccio
darccio requested a review from a team as a code owner November 25, 2026 15:32
@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:33:56.175839Z eebe8cb PR opened
🔒 Security Review ✅ Completed 2026-11-25T15:38:26.328924Z eebe8cb PR opened
ℹ️ 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.

@datadog-official

datadog-official Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Pipelines  Tests

❌ Errors

Your PR has failed checks. Please review the issues below and take necessary action before merging.

🚦 1 Pipeline job failed

Check Pull Request CI Status | all-jobs-are-green

View more details · View in GitHub Actions

ℹ️ Info

No other issues found (see more)

🧪 All tests passed
❄️ No new flaky tests detected

🎯 Code Coverage (details)
• Patch Coverage: 80.77%
• Overall Coverage: 74.18% (+7.04%)

Useful? React with 👍 / 👎

This comment will be updated automatically if new data arrives.
🔗 Commit SHA: eebe8cb | Docs | View more details | Give us feedback!

@datadog-official datadog-official Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Bits Code Review: FAIL

Wrapping a pathway context in a cancellation, value, or span context makes each subsequent pathway lookup allocate a fresh boxed Pathway, introducing a performance regression on repeated lookups.

Open Bits AI session

🤖 Bits Code Review · Commit eebe8cb


func (c *pathwayContext) Value(key any) any {
if key == activePathwayKey {
return c.pathway

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Avoid boxing the pathway on every wrapped-context lookup

When a pathway context is wrapped with context.WithCancel, context.WithValue, or tracer.ContextWithSpan, PathwayFromContext misses its direct assertion and reaches this return. Converting c.pathway to any allocates a fresh boxed copy on every lookup; previously, context.WithValue reused the value boxed during insertion. Repeated injection, merging, and checkpoint lookups therefore incur an additional allocation, undermining this hot-path optimization. Return an internal reference here and update PathwayFromContext to dereference it.

React: 👍 useful · 👎 wrong · 😕 unclear · 👀 right, but not acting on it

What each reaction means
  • 👍 Useful: correct, and you're fixing it or will.
  • 👎 Wrong: the finding is incorrect, for example the bug can't happen or the code was misread.
  • 😕 Unclear: you can't tell what it means or why it matters.
  • 👀 Right, not acting: correct, but intended, out of scope for this PR, a known risk, or too minor.

🤖 Bits Code Review · Open Bits AI session

@pr-commenter

pr-commenter Bot commented Nov 25, 2026

Copy link
Copy Markdown

Benchmarks

Benchmark execution time: 2026-11-25 16:04:40

Comparing candidate commit eebe8cb in PR branch darccio/perf-datastreams-base64-propagation with baseline commit 3fa83b0 in branch main.

📊 Benchmarking dashboard

Found 3 performance improvements and 0 performance regressions! Performance is the same for 413 metrics, 0 unstable metrics.

Explanation

This is an A/B test comparing a candidate commit's performance against that of a baseline commit. Performance changes are noted in the tables below as:

  • 🟩 = significantly better candidate vs. baseline
  • 🟥 = significantly worse candidate vs. baseline

We compute a confidence interval (CI) over the relative difference of means between metrics from the candidate and baseline commits, considering the baseline as the reference.

If the CI is entirely outside the configured SIGNIFICANT_IMPACT_THRESHOLD (or the deprecated UNCONFIDENCE_THRESHOLD), the change is considered significant.

Feel free to reach out to #apm-benchmarking-platform on Slack if you have any questions.

More details about the CI and significant changes

You can imagine this CI as a range of values that is likely to contain the true difference of means between the candidate and baseline commits.

CIs of the difference of means are often centered around 0%, because often changes are not that big:

---------------------------------(------|---^--------)-------------------------------->
                              -0.6%    0%  0.3%     +1.2%
                                 |          |        |
         lower bound of the CI --'          |        |
sample mean (center of the CI) -------------'        |
         upper bound of the CI ----------------------'

As described above, a change is considered significant if the CI is entirely outside the configured SIGNIFICANT_IMPACT_THRESHOLD (or the deprecated UNCONFIDENCE_THRESHOLD).

For instance, for an execution time metric, this confidence interval indicates a significantly worse performance:

----------------------------------------|---------|---(---------^---------)---------->
                                       0%        1%  1.3%      2.2%      3.1%
                                                  |   |         |         |
       significant impact threshold --------------'   |         |         |
                      lower bound of CI --------------'         |         |
       sample mean (center of the CI) --------------------------'         |
                      upper bound of CI ----------------------------------'

scenario:BenchmarkSetCheckpoint

  • 🟩 allocated_mem [-32 bytes; -32 bytes] or [-8.000%; -8.000%]
  • 🟩 allocations [-1; -1] or [-25.000%; -25.000%]
  • 🟩 execution_time [-59.897ns; -52.523ns] or [-6.109%; -5.357%]

@dd-octo-sts dd-octo-sts Bot mentioned this pull request Nov 25, 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