Skip to content

dogstatsd-http: constant-time Sketch recording and a lock-free SketchRecorder - #356

Merged
vickenty merged 11 commits into
DataDog:masterfrom
iksaif:corentin.chary/http-sketch-fast
Dec 1, 2026
Merged

vickenty merged 11 commits into
DataDog:masterfrom
iksaif:corentin.chary/http-sketch-fast

Conversation

@iksaif

@iksaif iksaif commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

Follows #354, now merged. This PR is rebased on master and only contains its own commits.

The counters and the recorder's concurrency are mapping-agnostic. They live in package-private Bins and AtomicBins, indexed by a 32-bit index, with Sketch and SketchRecorder adding the DDSketch key mapping and summaries on top, so other bucketed sketches such as OTel base-2 exponential histograms can reuse them. There is no public API for that yet.

Why

#354 lets applications accumulate observations into a Sketch, but leaves two problems for real recording paths:

  1. Sketch.add is slow: it computes a Math.log and binary-searches sorted bins, costing 16–55 ns per observation on an M4 Max.
  2. No safe multi-threaded recording: Sketch is not thread safe, and a single lock shared by recording threads collapses under contention.

What

  1. Dense bins. Bin counts live in pages of 256 counters indexed by key, allocated as observations reach them, with a bitmask of the pages in use. add and build become a key computation plus an array increment, and build no longer sorts. The 4096-bin limit is applied when bins are read, by folding the lowest bins into the lowest reported one, as before. The bins sent are unchanged, and all of dogstatsd-http: let applications accumulate observations into a Sketch #354's equivalence tests pass as they are.
  2. Bin keys without Math.log. The key is a sum of table lookups: one for the exponent, one for log(c) over the top 8 mantissa bits, and a 3-term log1p series for the rest. Rounding uses the 1.5 × 2^52 trick. There are no int-to-double conversions, divisions or Math.floor/rint calls, which are slow on x86. When the estimate is within 1e-7 of a rounding boundary, it falls back to Math.log, so keys are bit-identical to the reference computation. The tests check 5M random values and ±4 ulps around every rounding boundary.
  3. Sketch.drainTo(dst), from dogstatsd-http: let applications accumulate observations into a Sketch #354, swaps the paged counters, still in constant time and without allocating.
  4. SketchRecorder, a thread-safe, lock-free recorder for one timeseries:
SketchRecorder latency = new SketchRecorder();   // kept per timeseries
latency.add(12.5);                               // any thread, on every observation

Sketch scratch = new Sketch();                   // owned by the flushing thread
latency.drainTo(scratch);                        // takes everything recorded so far
client.distribution("req.latency", scratch, ts, tags);
  • Recording uses atomic operations only:
    • bins are counters in lazily created AtomicLongArray pages;
    • the sum is a striped cell, kept as a single cell until threads contend (DoubleAdder is Java 8, and the module targets Java 7);
    • min and max use CAS loops that only write when the value changes.
  • Bins are striped on contention, like LongAdder. Threads update one shared table with a CAS until one fails. From then on, each thread records into its own table, picked by thread id, with one per CPU up to 16. Only contended timeseries pay for the extra tables.
  • Bin counts are exact. drainTo takes each bin with getAndSet(0), so every observation is counted in exactly one drain, and the drained count always matches the bins.
  • Summaries are exact up to drain boundaries. If an observation is recorded while a drain is running, its sum may be reported in the previous or next drain, and is never lost. A drain that finds no bins hands the summary it took back to the next drain. A drained min or max is kept only if it falls in the lowest or highest drained bin; otherwise it is estimated from that bin, within the sketch's relative accuracy. So the min and max of a drained sketch always fall in its own bins.
  • NaN maps to key 0, as in the reference exactKey, and Short.MIN_VALUE is never produced as a key.

Benchmarks

JMH with log-normal values, on two machines:

  • ARM: M4 Max laptop, JDK 17.
  • x86: Xeon 8259CL, JDK 21, where atomics and Math.log cost a lot more.

Recording one observation (SketchRecorderBenchmark, ns per add, per thread, all threads recording into one timeseries):

ARM ×1 ARM ×4 ARM ×16 x86 ×1 x86 ×4 x86 ×16
plain Sketch, thread-owned 3.3 n/a n/a 14.6 n/a n/a
one Sketch behind a lock 5.1 270 682 30.2 365 1385
SketchRecorder 8.2 10.1 28 24.2 105 173
reference: Dropwizard-style uniform reservoir (1028 samples, lossy) 4.1 69 674 24.3 285 730

For comparison, Sketch.add on #354 costs 57 ns on ARM with ~900 bins, before any locking. Uncontended, a sampling reservoir is about as fast as the recorder or faster: it does almost nothing per value and keeps only a sample. Under contention its shared counter becomes the bottleneck, and the recorder is 3–25× faster while keeping every observation.

Key computation (SketchAddBreakdownBenchmark, ns):

ARM x86
exactKey (Math.log) 4.1 15.5
key 1.6 8.8
add with exactKey 14.1 23.7
add 3.5 17.6

Per flush interval (SketchBenchmark, ARM, #354 → this PR):

N=10 N=1,000 N=100,000
accumulate (add, then clear) 0.097 → 0.081 µs 16.9 → 3.9 µs 5.5 → ~0.5 ms
collectThenBuild 0.085 → 0.085 µs 15.7 → 4.1 µs 5.4 → ~0.4 ms
sampleThenBuild (1 in 10) 0.015 → 0.040 µs 1.16 → 0.44 µs 0.24 → 0.04 ms

Memory:

  • A sketch has a 256-entry page table (~1 KB), plus 2 KB per page of 256 keys reached. Typical latencies spanning ~4 orders of magnitude touch 3–4 pages.
  • A recorder is the same until threads collide. After that, each striped thread table adds the same again, plus ~2 KB of sum cells.

To run them, use mvn -f dogstatsd-http/pom.xml -pl core -P benchmarks test-compile exec:exec -Djmh.args='SketchRecorderBenchmark', or SketchAddBreakdownBenchmark or SketchBenchmark -prof gc. Each takes a couple of minutes.

Testing

  • SketchTest:
  • SketchRecorderTest:
    • same bins as a Sketch for the same observations, past the bin limit, shuffled;
    • drain semantics, both shared and striped;
    • deterministic interleavings of an add's steps with drains: a drain that finds no bins hands the summary back, and min and max stay within the drained bins;
    • infinities, argument validation, and saturation, including single observations after a weighted add saturated a bin, with shared and striped tables;
    • 4 threads recording 800k observations while the main thread drains continuously. Every drained sketch must have bins adding up to its count and its min and max within its bins. The total bins and count must match a single-threaded build exactly.
  • mvn -f dogstatsd-http/pom.xml clean install: all tests pass, javadoc clean. Java 7 compatible.

🤖 Generated with Claude Code

@iksaif
iksaif marked this pull request as ready for review November 30, 2026 09:52
@iksaif
iksaif requested a review from a team as a code owner November 30, 2026 09:52
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 30, 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-30T09:58:14.243141Z ccbc909 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: ccbc909af9

ℹ️ 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".

@datadog-datadog-prod-us1

This comment has been minimized.

@iksaif
iksaif force-pushed the corentin.chary/http-sketch-fast branch 3 times, most recently from 6fb5848 to caf9fc1 Compare November 30, 2026 13:38
iksaif and others added 10 commits November 30, 2026 16:57
Sketch.add binary-searched sorted bins, costing ~55 ns per observation
with ~900 bins, and recording from several threads required a lock
that collapses under contention.

Store bin counts in pages of 256 counters indexed by key, allocated as
observations reach them. add, build and merge become a key computation
plus an array increment (~8 ns per observation), and build no longer
sorts. The 4096-bin limit is applied when bins are read, folding the
lowest bins into the lowest reported one as before, so the bins sent
are unchanged.

Add Sketch.drainTo, which moves a sketch's content into another without
allocating, and SketchRecorder, a thread-safe recorder for one
timeseries. Recording uses atomic operations only: per-bin counters in
lazily created pages, a striped sum inflated on contention, and min/max
CAS loops that only write when they change. drainTo takes each bin with
getAndSet, so every observation is counted in exactly one drain and the
drained count always matches the bins.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Compare the cost of recording one observation from 1, 4 and 16 threads
into a plain Sketch, a Sketch behind a lock, a SketchRecorder and, for
reference, a Dropwizard-style uniform sampling reservoir.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Math.log dominated Sketch.add: ~14 ns per add with it, ~3.5 ns without
on an M4 Max; key computation drops from 15.5 to 8.8 ns on a Xeon
8259CL. Sum table lookups instead: the exponent's contribution, log(c)
for the top 8 mantissa bits, and a 3-term log1p series for the rest,
rounding with the 1.5 * 2^52 trick. It avoids int to double
conversions, divisions and Math.floor/rint, which are slow on x86.

The estimate is within 4e-9 keys of the Math.log one, so when it is more
than 1e-7 from a rounding boundary its rounding is exact; otherwise it
falls back to Math.log. Keys are always identical to the reference
computation, now exactKey, which the tests check on 5M random values and
around every rounding boundary.

Add SketchAddBreakdownBenchmark to measure the parts of an add.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Threads recording into one SketchRecorder kept bouncing the cache lines
of hot bins between cores: 40 ns per add at 4 threads and 190 ns at 16
on an M4 Max. Like LongAdder, update bins with a CAS on a shared table
until one fails, then give threads their own table picked by thread id,
one per CPU up to 16, drained together. Only contended timeseries pay
for the extra tables. Also space sum cells 128 bytes apart, the cache
line size on Apple silicon and the adjacent-line prefetch pair on x86.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
One fork, 2 warmup and 3 measurement iterations of 1s: a few seconds per
configuration, so a whole benchmark runs in a couple of minutes. Pass JMH
options through -Djmh.args for more precise runs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
clear(), bins() and merge() scanned all 256 page slots, which made tiny
intervals slower than with sorted bins: 0.16 us to record and clear 10
observations instead of 0.10. Track pages holding non-zero bins in a
256-bit mask, set when a bin goes from zero to non-zero, and only visit
those: 0.08 us.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- A drain that found no bins reset the sum, min and max anyway, losing
  the sum of observations whose bin was not written yet. Hand them back
  to the next drain instead.
- A drain could report a min or max outside its own bins when its
  summary and bins came from different observations. Keep the recorded
  min and max only when they fall in the lowest and highest drained
  bins, and otherwise estimate them from those bins.
- key() indexed past its exponent table for a NaN with the sign bit set,
  so build() threw on it. Map NaN to key 0, as exactKey() does.

Make the steps of add() package-private so tests can interleave them
with drains deterministically, and check that Short.MIN_VALUE, which
the backend reserves, is never produced as a key.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A weighted add or merge can saturate a bin, after which the
getAndIncrement fast path wrapped it negative. Use the saturating CAS
loop for every increment: same cost uncontended, and contended threads
use their own stripes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Move the paged counters, used-page mask, saturation, and the striped
lock-free counters with their getAndSet drain, out of Sketch and
SketchRecorder into package-private Bins and AtomicBins, indexed by an
int in [0, indexCount). Sketch and SketchRecorder keep the DDSketch key
mapping and summaries on top. Other bucketed sketches, such as OTel
base-2 exponential histograms, whose indexes are 32-bit, can reuse the
same machinery with their own mapping.

Sketch extends Bins rather than holding one, keeping the counters one
load away on the recording path: holding one cost ~25% on add-heavy
intervals. No public API change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Clients record with add and hand snapshots to the flushing code with
drainTo. Per-thread pre-aggregation merged into a recorder is not
needed either: contended threads already get their own bin tables. Drop
both merge methods and AtomicBins.addAll; tests accumulate drained
sketches with a package-private helper.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@iksaif
iksaif force-pushed the corentin.chary/http-sketch-fast branch from caf9fc1 to a0b250e Compare November 30, 2026 15:58
@vickenty
vickenty merged commit a2caf1d into DataDog:master Dec 1, 2026
14 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants