Skip to content

Read fetched Kafka headers without copying them first - #13600

Open
dougqh wants to merge 10 commits into
dougqh/field-accessorsfrom
dougqh/kafka-header-view
Open

dougqh wants to merge 10 commits into
dougqh/field-accessorsfrom
dougqh/kafka-header-view

Conversation

@dougqh

@dougqh dougqh commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

What Does This Do

The Kafka 3.8+ consumer's context extraction reads fetched record headers straight from the record-batch buffer, instead of through RecordHeader.key() and value():

  • a key whose bytes spell a known propagation header name (x-datadog-*, traceparent, tracestate, baggage, the DSM and time-in-queue headers) resolves to that name's constant, with no decoding;
  • every value decodes once, from the buffer's backing array, skipping Kafka's byte[] copy.

Extraction sees the same keys and values as before.

Motivation

A fetched RecordHeader holds slices of the fetch buffer and decodes lazily: key() builds a String and value() copies the bytes into a new array, for every header the tracer visits, and extraction then decodes that array into another String. Profiling a Kafka consumer (in-review dense-store and header stacks, 10% sampling) attributed about 11 GiB per run, a third of all tracer allocation, to those three steps (RecordHeader.value 3.4 GiB, RecordHeader.key 4.1 GiB, our value decode 3.5 GiB).

Additional Notes

  • Stacked on Add FieldAccessors to read a library class's private fields without reflection #13656, which adds FieldAccessors (reading a library class's private fields without reflection) and generates muzzle references for the fields it reads. This PR is its first user.

  • RecordHeaderInstrumentation declares BufferedHeaderFields (a new bootstrap interface) with getters for RecordHeader's key, keyBuffer, value and valueBuffer. A RecordHeader loaded before the agent, or with a different layout, keeps its structure, and its headers take the existing path.

  • RecordHeaderAccess reads those fields. It never writes them or moves a buffer's position, so the application's own key() / value() calls behave as before, and it doesn't keep any buffer reference past the call (each would keep the whole fetch buffer alive). Already-decoded fields, direct buffers, other Header implementations and Base64-encoded headers take the existing path.

  • Subclasses: a RecordHeader subclass inherits the accessor, but may override key() or value() (say, to decrypt). RecordHeaderAccess.bufferedFields checks for exactly RecordHeader first (the usual case, constant once compiled). Any other class with the accessor uses its fields only if it keeps Kafka's own key() and value(), computed once per class in a ClassValue. Otherwise the header is read through its overrides.

  • Muzzle checks RecordHeader's four fields across the whole Kafka range, generated from the installFieldAccessors call (Add FieldAccessors to read a library class's private fields without reflection #13656). The accessor install is its own module, so a version without the fields skips only it, and extraction falls back to key() / value().

  • Lockfile: the module's gradle.lockfile now locks the benchmark's JMH configurations.

  • Scope of the win: the savings apply with the default configuration. Other tracer code on the same record still calls the header's own key() / value() when it's enabled: Data Streams Monitoring's payload sizing (Utils.computePayloadSizeBytes, on every header), time-in-queue (extractTimeInQueueStart, via lastHeader), and DSM transaction extractors. With DSM on, most of the key and value savings go away again. A natural follow-up is for payload sizing to read the buffers' lengths through BufferedHeaderFields instead of materializing them.

  • One loop: TextMapExtractAdapter.forEachKey chooses the buffered path per header (a header with BufferedHeaderFields, when not decoding Base64) and otherwise takes the key() / value() path, so there's one loop for both. RecordHeaderAccess's known-keys list is only a fast path: a name missing from it costs a decode, never correctness.

  • Tests: RecordHeaderAccessTest covers the read logic over real RecordHeaders (fetched slices with offsets, already-materialized fields, missing and direct-buffer values, unknown keys, state left untouched) and the adapter's output against key()/value(). RecordHeaderInstrumentationForkedTest checks the installed accessor under the agent. A forked test checks that a subclass overriding value() is read through its override.

  • KafkaFetchedHeadersBenchmark (first commit; the module's first JMH benchmark) drains a poll batch through TracingIterator over headers in their fetched shape, rebuilt each op as each fetch builds them. headerShape: fetched is today's path; fetchedAccessor is the same headers with the accessor, as under the agent (JMH runs without it, so the getters are static final method handles there, which compile to the same field reads); built is pre-built headers like KafkaConsumeScenariosBenchmark's. appHeaders {0, 3} adds headers no propagator reads.

    Local smoke run (1 fork, JDK 21), per record:

    appHeaders fetched fetchedAccessor built
    0 1456 ns, 3828 B 1386 ns, 3100 B 1283 ns, 3100 B
    3 1645 ns, 4404 B 1585 ns, 3564 B 1401 ns, 3396 B

    A 3-fork run on an 8 vCPU VM confirmed the allocation (−734 B, −19% per record with no application headers; −867 B with three) but showed no clear time change there. With no application headers, fetched headers now allocate the same as pre-built ones. The remaining 168 B with three application headers is Kafka decoding keys nothing reads, which the classifier follow-up skips.

  • Kafka macrobenchmark (laptop): consumer and enricher on a local broker, 10% sampled upstream traces, 256m heap, v0.5 protocol, 3 reps; the in-review dense-store/TagLookup stack with and without these three commits (nothing else differs):

    workload throughput tracer µs per record young GCs per 1M records
    consumer 247k → 259k/s (+5.0%) 2.96 → 2.77 32 → 27
    enricher 160k → 173k/s (+8.2%) 4.72 → 4.25 60 → 56

    A JFR allocation profile of the consumer confirms the copies are gone: what the agent allocates under extraction's header loop drops from 6.7 GiB to 0.24 GiB (Kafka's header iterator), and tracer-attributed allocation per run from 31.7 to 24.2 GiB (−24%). The largest remaining site is the value strings themselves (RecordHeaderAccess.utf8Value, 5.3 GiB), which the follow-ups address.

  • Possible follow-up: BufferedHeaderFields could move from internal-api into the Kafka module. Add FieldAccessors to read a library class's private fields without reflection #13656 now injects a module's accessor interface as a helper, so it no longer has to be on the bootstrap class path.

  • Follow-ups, stacked on this:

    1. a header classifier (key → header id, or reject) so headers nothing reads are skipped before decoding, the first step of splitting carrier access from classification;
    2. one slot array indexed by header id in place of the two carrier caches, and parsing id headers from bytes.

🤖 Generated with Claude Code

@dougqh dougqh added tag: performance Performance related changes type: refactoring inst: kafka Kafka instrumentation tag: ai generated Largely based on code generated by an AI or LLM labels Nov 21, 2026
@datadog-prod-us1-6

datadog-prod-us1-6 Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

🎯 Code Coverage (details)
• Patch Coverage: 100.00%
• Overall Coverage: 59.33% (-0.01%)

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

@dougqh
dougqh force-pushed the dougqh/kafka-header-view branch from 1118e81 to 8d15876 Compare November 21, 2026 01:23
@dd-octo-sts

dd-octo-sts Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

🟢 Java Benchmark SLOs — All performance SLOs passed

Suite Status
Startup 🟢 pass

SLO thresholds are defined here based on automatically generated metrics. A warning is raised when results are within 5% of the threshold.

PR vs. master results
Scenario Candidate master Δ (95% CI of mean)
startup:insecure-bank:iast:Agent 14.78 s 14.71 s [-0.3%; +1.3%] (no difference)
startup:insecure-bank:tracing:Agent 13.62 s 13.72 s [-1.6%; +0.2%] (no difference)
startup:petclinic:appsec:Agent 17.90 s 17.82 s [-0.4%; +1.3%] (no difference)
startup:petclinic:iast:Agent 17.74 s 17.81 s [-1.4%; +0.6%] (no difference)
startup:petclinic:profiling:Agent 17.68 s 17.46 s [+0.1%; +2.5%] (maybe worse)
startup:petclinic:sca:Agent 17.92 s 17.77 s [-0.0%; +1.7%] (no difference)
startup:petclinic:tracing:Agent 16.94 s 17.02 s [-1.7%; +0.8%] (no difference)

Commit: cdee7363 · CI Pipeline · Benchmarking Platform UI


Load and DaCapo benchmarks can be triggered manually in the GitLab pipeline. Results will appear in the Benchmarking Platform UI after completion.

@dougqh
dougqh force-pushed the dougqh/kafka-header-view branch from 8d15876 to 49e3eee Compare November 21, 2026 01:44
@dougqh
dougqh changed the base branch from dougqh/w3c-traceparent-no-throw to master November 21, 2026 01:44
@pr-commenter

pr-commenter Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

Kafka / producer-benchmark

Parameters

Baseline Candidate
baseline_or_candidate baseline candidate
git_branch dougqh/field-accessors dougqh/kafka-header-view
git_commit_date 1795487553 1795487556
git_commit_sha cb89960 1fdefac
See matching parameters
Baseline Candidate
ci_job_date 1795488830 1795488830
ci_job_id 2293396887 2293396887
ci_pipeline_id 155992738 155992738
cpu_model Intel(R) Xeon(R) Platinum 8259CL CPU @ 2.50GHz Intel(R) Xeon(R) Platinum 8259CL CPU @ 2.50GHz
jdkVersion 11.0.31 11.0.31
jmhVersion 1.36 1.36
jvm /usr/lib/jvm/java-11-openjdk-amd64/bin/java /usr/lib/jvm/java-11-openjdk-amd64/bin/java
jvmArgs -Dhttp.proxyHost=127.0.0.1 -Dhttp.proxyPort=15002 -Dhttps.proxyHost=127.0.0.1 -Dhttps.proxyPort=15002 -Dhttp.nonProxyHosts=localhost *.localhost
kernel_version Linux runner-zfyrx7zua-project-304-concurrent-1-jewmmtat 6.8.0-1031-aws #33~22.04.1-Ubuntu SMP Thu Jun 26 14:22:30 UTC 2025 x86_64 x86_64 x86_64 GNU/Linux Linux runner-zfyrx7zua-project-304-concurrent-1-jewmmtat 6.8.0-1031-aws #33~22.04.1-Ubuntu SMP Thu Jun 26 14:22:30 UTC 2025 x86_64 x86_64 x86_64 GNU/Linux
vmName OpenJDK 64-Bit Server VM OpenJDK 64-Bit Server VM
vmVersion 11.0.31+11-post-1ubuntu1-22.04.2-Ubuntu 11.0.31+11-post-1ubuntu1-22.04.2-Ubuntu

Summary

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

See unchanged results
scenario Δ mean throughput
scenario:not-instrumented/KafkaProduceBenchmark.benchProduce same
scenario:only-tracing-dsm-disabled-benchmarks/KafkaProduceBenchmark.benchProduce same
scenario:only-tracing-dsm-enabled-benchmarks/KafkaProduceBenchmark.benchProduce same

@pr-commenter

pr-commenter Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

Kafka / consumer-benchmark

Parameters

Baseline Candidate
baseline_or_candidate baseline candidate
git_branch dougqh/field-accessors dougqh/kafka-header-view
git_commit_date 1795487553 1795487556
git_commit_sha cb89960 1fdefac
See matching parameters
Baseline Candidate
ci_job_date 1795488859 1795488859
ci_job_id 2293396888 2293396888
ci_pipeline_id 155992738 155992738
cpu_model Intel(R) Xeon(R) Platinum 8259CL CPU @ 2.50GHz Intel(R) Xeon(R) Platinum 8259CL CPU @ 2.50GHz
jdkVersion 11.0.31 11.0.31
jmhVersion 1.36 1.36
jvm /usr/lib/jvm/java-11-openjdk-amd64/bin/java /usr/lib/jvm/java-11-openjdk-amd64/bin/java
jvmArgs -Dhttp.proxyHost=127.0.0.1 -Dhttp.proxyPort=15002 -Dhttps.proxyHost=127.0.0.1 -Dhttps.proxyPort=15002 -Dhttp.nonProxyHosts=localhost *.localhost
kernel_version Linux runner-zfyrx7zua-project-304-concurrent-0-n3m2aeq2 6.8.0-1031-aws #33~22.04.1-Ubuntu SMP Thu Jun 26 14:22:30 UTC 2025 x86_64 x86_64 x86_64 GNU/Linux Linux runner-zfyrx7zua-project-304-concurrent-0-n3m2aeq2 6.8.0-1031-aws #33~22.04.1-Ubuntu SMP Thu Jun 26 14:22:30 UTC 2025 x86_64 x86_64 x86_64 GNU/Linux
vmName OpenJDK 64-Bit Server VM OpenJDK 64-Bit Server VM
vmVersion 11.0.31+11-post-1ubuntu1-22.04.2-Ubuntu 11.0.31+11-post-1ubuntu1-22.04.2-Ubuntu

Summary

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

See unchanged results
scenario Δ mean throughput
scenario:not-instrumented/KafkaConsumerBenchmark.benchConsume same
scenario:only-tracing-dsm-disabled-benchmarks/KafkaConsumerBenchmark.benchConsume same
scenario:only-tracing-dsm-enabled-benchmarks/KafkaConsumerBenchmark.benchConsume same

dougqh added a commit that referenced this pull request Nov 21, 2026
CarrierKeys.nameAscii read every byte through ByteBuffer.get and folded
its case, against the union of all propagators' names. For a heap buffer
it now compares the backing array's bytes exactly with each name's
precomputed lower-case ASCII bytes, and only compares ignoring case if the
key has an upper-case byte at all. In KafkaFetchedHeadersBenchmark this
more than halves the matcher's cost: fetched headers with the accessor go
from -3.6% to -8.3% against #13600 with three application headers.

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

dougqh commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 23, 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-24T21:32:43.490980Z cdee736 Draft marked ready
ℹ️ 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.

@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: 687bd775ca

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +65 to +67
jmh sourceSets.main_java17.output
jmh group: 'org.apache.kafka', name: 'kafka-clients', version: '3.8.0'
jmh project(':dd-trace-core')

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Regenerate the Kafka module's dependency lockfile

Adding the JMH plugin and these dependencies introduces new benchmark dependency configurations, but this commit leaves the module's gradle.lockfile unchanged, with no JMH configuration entries. The repository enables lockAllConfigurations(), and the sibling Kafka 0.11 module explicitly locks its JMH configurations. Regenerate and include the affected lockfiles so the new benchmark dependency graph is pinned, as required by the dependency-change rule in AGENTS.md.

AGENTS.md reference: AGENTS.md:L69-L70

Useful? React with 👍 / 👎.

Comment on lines +49 to +52
if (decoder == null && header instanceof BufferedHeaderFields) {
BufferedHeaderFields fields = (BufferedHeaderFields) header;
key = RecordHeaderAccess.key(header, fields);
value = RecordHeaderAccess.utf8Value(header, fields);

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 Preserve overridden accessors on RecordHeader subclasses

When a header subclasses RecordHeader and overrides key() or value(), it inherits BufferedHeaderFields from the instrumented superclass, so this branch bypasses those overrides and extracts the superclass's private fields instead. For example, a subclass initialized with trace-ID bytes "123" but overriding value() to return "456" previously extracted 456 and now extracts 123, associating the span with the wrong trace. Restrict the field-access fast path to the exact Kafka implementation, or otherwise ensure its accessors have not been overridden.

Useful? React with 👍 / 👎.

@dougqh
dougqh force-pushed the dougqh/kafka-header-view branch from 5bbdf4e to 4a70a9b Compare November 23, 2026 22:48
@dougqh
dougqh changed the base branch from master to dougqh/field-accessors November 23, 2026 22:49
@dougqh
dougqh force-pushed the dougqh/kafka-header-view branch from 4a70a9b to 41169b2 Compare November 23, 2026 23:36
@dougqh
dougqh force-pushed the dougqh/field-accessors branch from 307f5f9 to cb89960 Compare November 24, 2026 02:33
@dougqh
dougqh force-pushed the dougqh/kafka-header-view branch 2 times, most recently from 1fdefac to ca1a7a0 Compare November 24, 2026 20:10
dougqh and others added 5 commits November 24, 2026 15:47
KafkaFetchedHeadersBenchmark drains a poll batch through the 3.8
TracingIterator with headers that hold slices of a record-batch buffer,
as a fetch builds them, so Kafka's lazy key decode and value copy, which
extraction triggers, are measured. Params: headerShape (fetched / built)
and appHeaders (0 / 3).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
RecordHeaderInstrumentation installs BufferedHeaderFields on Kafka's
RecordHeader (a structural change, like TaskWrapper), with getters for its
key, keyBuffer, value and valueBuffer fields. Extraction reads fetched
headers through it: known propagation header keys resolve to their name
constants and values decode once from the fetch buffer, skipping
RecordHeader's key decode and value copy. Headers without the accessor
(loaded before the agent, other Header types) and Base64-encoded headers
take the existing path.

KafkaFetchedHeadersBenchmark gains a fetchedAccessor shape: the same
fetched headers with the accessor, as under the agent.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
RecordHeaderInstrumentation declares BufferedHeaderFields with getters for
RecordHeader's key, keyBuffer, value and valueBuffer, installed with
installFieldAccessors from a WithStructuralChange instrumentation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
forEachKey had a second, near-duplicate loop for UTF-8 headers. One loop now
takes the buffered path for a header the agent gave BufferedHeaderFields (when
not decoding Base64) and the key()/value() path otherwise. The known-keys list
uses PathwayContext's constant and says it's only a fast path.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A RecordHeader subclass inherits the accessor interface, but may override key()
or value(), which reading the raw fields would bypass. The buffered path now
requires exactly RecordHeader; other types, subclasses included, go through
key() and value(). Checking the exact class first also keeps the interface test
constant once compiled, instead of a secondary-supers lookup per header.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
dougqh and others added 5 commits November 24, 2026 15:47
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…afka's accessors

Requiring exactly RecordHeader was stricter than needed: what matters is whether
a subclass overrides key() or value(). RecordHeaderAccess.bufferedFields checks
exactly RecordHeader first (the usual case, constant once compiled), and for any
other class with the accessor, whether it keeps Kafka's own key() and value(),
computed once per class in a ClassValue declared as a helper.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ype directly

Use assertInstanceOf in the forked test and import its Kafka and java.util types:
imports don't load classes, so the nesting in UnderAgent is what keeps RecordHeader
unloaded until the agent is installed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
BufferedHeaderFields' getters are named for the fields they read, so the
getter/field pairs go.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@dougqh
dougqh force-pushed the dougqh/kafka-header-view branch from ca1a7a0 to cdee736 Compare November 24, 2026 21:00
@dougqh
dougqh marked this pull request as ready for review November 24, 2026 21:30
@dougqh
dougqh requested review from a team as code owners November 24, 2026 21:30
@dougqh
dougqh requested review from amarziali, jandro996 and mcculls and removed request for a team November 24, 2026 21:30

@datadog-prod-us1-6 datadog-prod-us1-6 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.

Bits Code Review: PASS

More details

Buffered extraction retains the existing key()/value() fallback for headers without accessors and for Base64 decoding. Static analysis identified no actionable defect; runtime behavior was not exercised.

Was this helpful? React 👍 or 👎

Open Bits AI session

🤖 Bits Code Review · Commit cdee736

@mcculls mcculls 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.

Came up with an alternative suggestion in #13656 (comment)

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

inst: kafka Kafka instrumentation tag: ai generated Largely based on code generated by an AI or LLM tag: performance Performance related changes type: refactoring

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants