Repository navigation
dogstatsd-http: constant-time Sketch recording and a lock-free SketchRecorder - #356
Merged
Merged
Conversation
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 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".
This comment has been minimized.
This comment has been minimized.
iksaif
force-pushed
the
corentin.chary/http-sketch-fast
branch
3 times, most recently
from
November 30, 2026 13:38
6fb5848 to
caf9fc1
Compare
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
force-pushed
the
corentin.chary/http-sketch-fast
branch
from
November 30, 2026 15:58
caf9fc1 to
a0b250e
Compare
vickenty
approved these changes
Dec 1, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Why
#354 lets applications accumulate observations into a
Sketch, but leaves two problems for real recording paths:Sketch.addis slow: it computes aMath.logand binary-searches sorted bins, costing 16–55 ns per observation on an M4 Max.Sketchis not thread safe, and a single lock shared by recording threads collapses under contention.What
addandbuildbecome a key computation plus an array increment, andbuildno 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.Math.log. The key is a sum of table lookups: one for the exponent, one forlog(c)over the top 8 mantissa bits, and a 3-termlog1pseries for the rest. Rounding uses the1.5 × 2^52trick. There are no int-to-double conversions, divisions orMath.floor/rintcalls, which are slow on x86. When the estimate is within 1e-7 of a rounding boundary, it falls back toMath.log, so keys are bit-identical to the reference computation. The tests check 5M random values and ±4 ulps around every rounding boundary.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.SketchRecorder, a thread-safe, lock-free recorder for one timeseries:AtomicLongArraypages;DoubleAdderis Java 8, and the module targets Java 7);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.drainTotakes each bin withgetAndSet(0), so every observation is counted in exactly one drain, and the drained count always matches the bins.exactKey, andShort.MIN_VALUEis never produced as a key.Benchmarks
JMH with log-normal values, on two machines:
Math.logcost a lot more.Recording one observation (
SketchRecorderBenchmark, ns peradd, per thread, all threads recording into one timeseries):Sketch, thread-ownedSketchbehind a lockSketchRecorderFor comparison,
Sketch.addon #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):exactKey(Math.log)keyaddwithexactKeyaddPer flush interval (
SketchBenchmark, ARM, #354 → this PR):accumulate(add, then clear)collectThenBuildsampleThenBuild(1 in 10)Memory:
To run them, use
mvn -f dogstatsd-http/pom.xml -pl core -P benchmarks test-compile exec:exec -Djmh.args='SketchRecorderBenchmark', orSketchAddBreakdownBenchmarkorSketchBenchmark -prof gc. Each takes a couple of minutes.Testing
SketchTest:drainTo, also after an overflowingbuild;keyagainstexactKeyon random values and around every boundary;Short.MIN_VALUEnever being produced;SketchRecorderTest:Sketchfor the same observations, past the bin limit, shuffled;mvn -f dogstatsd-http/pom.xml clean install: all tests pass, javadoc clean. Java 7 compatible.🤖 Generated with Claude Code