Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
508573e
Add self-serve PetClinic macro-benchmark harness
dougqh Jul 15, 2026
13e2f67
Gate wrk on a real HTTP 200 + abort on socket connect errors
dougqh Jul 16, 2026
11c53ee
Fix ps process lookup to target PID directly in run-perf-test.sh
dougqh Jul 21, 2026
0d6b891
Add repeats support to run-perf-test.sh for less-noisy throughput
dougqh Jul 21, 2026
1a74ef7
Discard the benchmarked server's stdout so error-endpoint stack trace…
dougqh Nov 3, 2026
2a4747b
Download released agents from GitHub releases, falling back to Maven …
dougqh Nov 3, 2026
d45a924
Add a Datadog Agent stub for macro benchmarks
dougqh Nov 3, 2026
3e76ca5
Report p99 and young GCs per endpoint, and support upstream headers a…
dougqh Nov 3, 2026
54bc17a
Run PetClinic against the Agent stub with upstream headers by default
dougqh Nov 3, 2026
0534818
Drop agent CPU and RSS columns the harness never measured, and tidy r…
dougqh Nov 3, 2026
fa9a364
Find the built PetClinic jar in one place
dougqh Nov 3, 2026
74452e8
Weight JFR allocation samples by their bytes in analyze-jfr.sh
dougqh Nov 3, 2026
e26ff36
Fix the shared perf runner for the Jetty and Play apps, JDK 8 and Linux
dougqh Nov 3, 2026
2e622d2
Pick up JAVA_HOME or the java on PATH for PetClinic, and narrow the i…
dougqh Nov 3, 2026
eacf000
Attribute JFR samples to the tracer by any datadog frame on the stack…
dougqh Nov 4, 2026
c0b250e
Report KB allocated per request per endpoint, from the GC log
dougqh Nov 4, 2026
a9d91b3
Run PetClinic sweeps in multiple fresh-JVM passes with rotated varian…
dougqh Nov 4, 2026
b116bf9
Own JFR samples by the first non-JDK frame, not any datadog frame on …
dougqh Nov 4, 2026
a621a97
Pass Play's JVM options to it intact
dougqh Nov 9, 2026
adf2000
Send the Agent state header from the Agent stub
dougqh Nov 9, 2026
9bd7f8b
Stop the PetClinic sweep when an agent jar can't be built or downloaded
dougqh Nov 9, 2026
6874d24
Make the perf runner stop cleanly when a run goes wrong
dougqh Nov 9, 2026
1d0f89f
Keep whole thread names and count the perf-test apps as app in analyz…
dougqh Nov 9, 2026
a6d5878
Keep agent jar paths with spaces as one JVM argument
dougqh Nov 9, 2026
6fa5537
Resolve PERF_SETTINGS to an absolute path before the sweep
dougqh Nov 9, 2026
80bdb64
Count JFR events without a stack in analyze-jfr totals
dougqh Nov 9, 2026
78d1efa
Run PetClinic extracted with the resource chain off, so it isn't lock…
dougqh Nov 11, 2026
44aa8b1
Don't run PetClinic's /oups error endpoint by default
dougqh Nov 11, 2026
0dd05fe
Read macOS CPU time correctly and tighten the Agent stub's Javadoc
dougqh Nov 12, 2026
50abb1a
Group PetClinic run medians by a stable variant ID, not by version
dougqh Nov 12, 2026
64543dd
Keep variant IDs from splitting CSV fields
dougqh Nov 13, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
149 changes: 149 additions & 0 deletions dd-java-agent/benchmark-integration/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,152 @@ cp /tmp/perf_results.csv ~/somewhere_else/
/usr/local/bin/bash ./run-perf-test.sh play-zip play-perftest/build/distributions/main-*.zip NoAgent ~/Downloads/dd-java-agent-0.18.0.jar ~/Downloads/dd-java-agent-0.19.0.jar
cp /tmp/perf_results.csv ~/somewhere_else/
```

## PetClinic macro benchmark (self-serve)
Comment thread
dougqh marked this conversation as resolved.
Resolved

`run-petclinic.sh` is the one-command version of the above against **Spring PetClinic** — a real
Spring MVC app that exercises a broad slice of the agent's instrumentation. It downloads and builds
PetClinic, runs it under load with the agent, captures a JFR per variant, and prints **throughput**
plus the **tracer-overhead split** (CPU + sampled allocation, bucketed foreground/background and
instrumentation/core). The goal is that any developer — not just perf specialists — can reproduce the
macro measurement that keeps micro benchmarks honest.

This is the fast, **local, dev-iteration** tool. It complements, and does not replace, the org's
automated benchmarking platform (the GitLab `apm-sdks-benchmarks-java-slo` track).

### Extra dependencies
On top of `wrk` and `nc`: `git`, a JDK (provides the `jfr` CLI), and `curl`. Maven is supplied by
PetClinic's own wrapper. First run needs network access (clone + build + optional release download).

### Running PetClinic without a class loader lock
Out of the box, PetClinic can't use more than about one core: every request's Thymeleaf links
(`@{/resources/...}`, `@{/webjars/...}`) go through Spring's resource chain, which looks each one up
on the class path, and the lookup isn't cached when it finds nothing. Every request thread then
queues on one lock: Spring Boot's nested-jar cache (`UrlJarFiles$Cache`) when run as a fat jar, or
the JDK's `URLClassPath` when extracted. Throughput stays flat as connections go up and only latency
grows, and that queueing hides tracer overhead.

So the harness runs PetClinic **extracted** (`fetch-petclinic.sh` runs `-Djarmode=tools extract` on
the fat jar) with **the resource chain off** (`SPRING_WEB_RESOURCES_CHAIN_ENABLED=false`, set by
`run-petclinic.sh`). Pages render the same, except asset links aren't rewritten to versioned URLs,
and wrk doesn't fetch assets.

NoAgent on `/` at 64 connections (M1 Max):

| PetClinic run as | req/s | p90 |
|---|---|---|
| fat jar | ~1,300 | 61 ms |
| extracted | ~4,200 | 23 ms |
| extracted, resource chain off | ~17,500 | 4.3 ms |

### Trace destination — what actually gets measured
By default, `run-petclinic.sh` starts a local **Agent stub** (`agent-stub/AgentStub.java`, a
single-file Java program) on `PETCLINIC_STUB_PORT` (default 8137) and points the agent variants at
it. The stub serves a real Agent's `/info` (so client-side stats, dropping unsampled traces and peer
tags are discovered as with a real Agent), accepts and discards payloads immediately, and counts what
it received. After each agent variant the harness checks the stub received traces, and **aborts** if
it got none.

Why not the local Datadog Agent: if it's slow, or rejecting payloads (an expired API key answers
every payload with 403), the tracer's writer backs up and holds traces in the heap. That changes the
GC behavior being measured, and nothing in the results shows it — it looks like a noisy or
unrepeatable benchmark. The stub takes that variable out.

`PETCLINIC_AGENT=real` uses the Agent on `TRACE_AGENT_PORT` (default 8126) instead. Then the harness
auto-detects it and picks the writer accordingly:
- **Agent reachable** (`DDAgentWriter`) — the *full pipeline*: span work on the request threads **and**
the background serializer.
- **Agent unreachable** (`LoggingWriter`) — traces are discarded, so you measure the **agent-down
regime**: foreground overhead only, no serializer.

The harness prints a `>> REGIME:` banner so the choice is never silent, and re-checks before every
variant. Set `EXPECT_AGENT=up` (or `down`) to make it **fail fast** if reality differs (the stub mode
sets `up`).

### Upstream trace headers
By default every request carries the headers a traced upstream service would send
(`wrk-upstream-headers.lua`: W3C `traceparent`/`tracestate`, Datadog headers and propagation tags,
`baggage`), so each request goes through extraction and continues a distributed trace, as most
services' requests do. `PETCLINIC_UPSTREAM_HEADERS=false` sends plain requests; `PERF_WRK_SCRIPT`
passes any other wrk Lua script.

### Usage
```
# NoAgent vs the current checkout:
./run-petclinic.sh

# A version sweep for the historic curve — each token is a jar path, `current` (builds this
# checkout's shadow jar), or a release version (downloaded from GitHub releases, else Maven Central):
./run-petclinic.sh 1.54.0 1.58.0 1.62.0 current
```
Artifacts (throughput CSV, per-variant JFRs and GC logs) are copied to
`build/petclinic-results/results-<ts>/`. Per endpoint, the CSV reports mean latency, p99 latency,
throughput (mean and stdev across repeats), young GCs per 1,000 requests, and KB allocated per
request, both inside the measured window.

**KB/req is the allocation number to compare.** It comes from the GC log (each GC's heap before,
minus the heap after the previous one), so it counts everything the process allocated, on every
thread, with no sampling. The tracer's allocation cost is a variant's KB/req minus NoAgent's.
Analyze any recording on its own with `./analyze-jfr.sh <recording.jfr>`.

#### Heap regime (ample vs tight)
Server heap is a fixed `Xms=Xmx` knob (default 256m) — the regime where allocation overhead turns
into throughput cost. Set one heap with `server_heap=` in the `.rc` (or `PERF_HEAP=`), or **sweep**
several by passing a list — the full variant sweep runs once per heap:
```
PETCLINIC_HEAPS="64m 256m 512m" ./run-petclinic.sh 1.54.0 1.58.0 current
```
Results land in per-heap subdirs (`heap-64m/`, …) plus a combined `throughput-grid.csv` (leading
`Heap` column). **Runtime is heaps × variants** — a heap list multiplies the wall clock, so size the
version list accordingly.

#### Runs (fresh JVMs, rotated order)
`PETCLINIC_RUNS=N` (default 1) runs the whole variant sweep N times per heap, each a fresh JVM per
variant, with the variant order (NoAgent included) rotated every run, so drift over a long sweep
spreads across variants instead of always landing on whichever runs first. Each run's artifacts go
in `heap-<h>/run-<n>/`, the combined grid gets `Run` and `Variant` columns, and with more than one
run a `median-grid.csv` of per-variant medians (throughput and KB/req per endpoint) is printed at
the end. `Variant` is a stable ID per variant as given (`v2:current`, `v3:1.62.0`, …): two builds
can report the same version, so medians are grouped by it rather than by version.
```
PETCLINIC_RUNS=3 PETCLINIC_HEAPS="72m 256m" ./run-petclinic.sh current
```
Prefer runs over repeats for comparisons: repeats share one JVM, so they can't show JVM-to-JVM
(e.g. JIT) variation, which is often the larger part of the noise.

#### Repeats (noise vs. a single sample)
Throughput on a shared dev box is noisy -- a single wrk run per endpoint can swing several percent
run to run. Set `PETCLINIC_REPEATS=N` to warm up once per endpoint and then measure N back-to-back
windows (no server restart between them); the CSV reports the mean and stdev of throughput across
the repeats (`<endpoint> Throughput`, `<endpoint> Throughput Stdev`), so you can see the noise band
instead of a single point estimate:
```
PETCLINIC_REPEATS=5 ./run-petclinic.sh 1.58.0 1.62.0 current
```
Default is 1 repeat (no change in behavior/runtime from before this knob existed). Repeats multiply
runtime the same way heaps do -- factor them into the total when combined with a heap sweep.

PetClinic is pinned to a specific commit in `fetch-petclinic.sh` (bump deliberately); JFR is opt-in in
`run-perf-test.sh` via `PERF_JFR=1`, and endpoints/load live in `perf-test-petclinic-settings.rc`.

### Reading the results honestly
- **Allocation is the anchor; throughput is directional.** Allocation trends are stable across runs;
throughput on a shared dev box is noisy and swings with the CPU-contention regime — read it as a
direction, not a precise number.
- Allocation here is **sampled** by JFR (`jdk.ObjectAllocationSample`, throttled); the analyzer
weights each sample by the bytes it stands for, so the splits (which thread, which package) are
by estimated bytes, not by sample count, and the total is an estimate. That's sufficient for a
macro trend.
- Young GCs and KB per request need JDK 9+ (unified GC logging); on JDK 8 those columns are empty.
- In the JFR split, a sample is owned by the first non-JDK frame from the leaf, so work the tracer
does through JDK code (e.g. `HashMap.resize`) counts as tracer, while app code running inside an
instrumented filter counts as app. Advice woven into an app method doing work inline, without
calling a `datadog.*` method, still counts as app, so the tracer share is a lower bound; KB/req vs
NoAgent is the total.
- Run on an otherwise-**quiet machine**, and respect the warmup (the harness warms each endpoint
before measuring). Results depend on the machine's core count / heap regime.

### Known limitations (follow-ups)
- No containerization yet — no pinned cores/heap, so cross-machine comparisons are approximate.
- `run-perf-test.sh` is still lightly macOS-flavored (`/usr/bin/time`, `lsof`, `nc`); there is a basic
Linux guard but not full cross-platform hardening.
138 changes: 138 additions & 0 deletions dd-java-agent/benchmark-integration/agent-stub/AgentStub.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicLongArray;

/**
* Local Datadog Agent stub for benchmarks. It reads and discards payloads so Agent processing and
* rejection do not affect the tracer's writer and heap measurements by default.
*
* <p>Serves {@code agent-info.json}, captured from Agent 7.80.3, for feature discovery, including
* client-side stats, unsampled-trace dropping and peer tags. Remote Config is not advertised. Every
* response includes {@code Datadog-Agent-State}, the SHA-256 of that file, so trace responses match
* the discovered state and do not trigger repeated discovery.
*
* <p>{@code GET /_stats} reports received requests and bytes per endpoint as {@code <path>
* <requests> <bytes>}. The runner uses this to check that each agent variant delivered traces.
*
* <pre>java AgentStub.java [port] [agent-info.json]</pre>
*
* <p>Defaults: port 8126 and {@code ./agent-info.json}. {@code STUB_SAMPLE_RATE} sets the {@code
* rate_by_service} response (default 1). {@code STUB_DELAY_MS} delays trace and stats responses;
* {@code STUB_ERROR_CODE} sets their response status to simulate a degraded Agent.
*/
Comment thread
dougqh marked this conversation as resolved.
Resolved
public class AgentStub {
private static final Map<String, AtomicLongArray> RECEIVED = new ConcurrentHashMap<>();
private static String agentState;

public static void main(String[] args) throws IOException {
int port = args.length > 0 ? Integer.parseInt(args[0]) : 8126;
byte[] info = Files.readAllBytes(Path.of(args.length > 1 ? args[1] : "agent-info.json"));
agentState = sha256Hex(info);
double sampleRate = Double.parseDouble(env("STUB_SAMPLE_RATE", "1"));
long delayMs = Long.parseLong(env("STUB_DELAY_MS", "0"));
int errorCode = Integer.parseInt(env("STUB_ERROR_CODE", "0"));
byte[] tracesResponse =
("{\"rate_by_service\":{\"service:,env:\":" + sampleRate + "}}")
.getBytes(StandardCharsets.UTF_8);

HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", port), 64);
server.setExecutor(Executors.newFixedThreadPool(8));
server.createContext(
"/",
exchange -> {
try (exchange) {
String path = exchange.getRequestURI().getPath();
if ("GET".equals(exchange.getRequestMethod())) {
if (path.equals("/info")) {
reply(exchange, 200, info);
} else if (path.equals("/_stats")) {
reply(exchange, 200, stats());
} else {
reply(exchange, 404, new byte[0]);
}
return;
}
long bytes = drain(exchange.getRequestBody());
AtomicLongArray counts = RECEIVED.computeIfAbsent(path, p -> new AtomicLongArray(2));
counts.incrementAndGet(0);
counts.addAndGet(1, bytes);
boolean payload = path.endsWith("/traces") || path.endsWith("/stats");
if (payload && delayMs > 0) {
Thread.sleep(delayMs);
}
if (payload && errorCode != 0) {
reply(exchange, errorCode, "{\"error\":\"stub degraded mode\"}".getBytes());
} else if (path.endsWith("/traces")) {
reply(exchange, 200, tracesResponse);
} else if (path.startsWith("/telemetry/") || path.startsWith("/evp_proxy/")) {
reply(exchange, 202, new byte[0]);
} else {
reply(exchange, 200, new byte[0]);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
server.start();
System.out.println("agent stub listening on 127.0.0.1:" + port);
}

private static byte[] stats() {
StringBuilder out = new StringBuilder();
new TreeMap<>(RECEIVED)
.forEach((path, c) -> out.append(path).append(' ').append(c.get(0)).append(' ')
.append(c.get(1)).append('\n'));
return out.toString().getBytes(StandardCharsets.UTF_8);
}

private static long drain(InputStream body) throws IOException {
byte[] buffer = new byte[64 * 1024];
long total = 0;
for (int n; (n = body.read(buffer)) > 0; ) {
total += n;
}
return total;
}

private static void reply(HttpExchange exchange, int status, byte[] body) throws IOException {
exchange.getResponseHeaders().set("Content-Type", "application/json");
exchange.getResponseHeaders().set("Datadog-Agent-State", agentState);
exchange.sendResponseHeaders(status, body.length == 0 ? -1 : body.length);
Comment thread
dougqh marked this conversation as resolved.
Resolved
if (body.length > 0) {
try (OutputStream out = exchange.getResponseBody()) {
out.write(body);
}
}
}

/** Lowercase hex, matching how the tracer hashes the {@code /info} body. */
private static String sha256Hex(byte[] bytes) {
try {
StringBuilder hex = new StringBuilder(64);
for (byte b : MessageDigest.getInstance("SHA-256").digest(bytes)) {
hex.append(Character.forDigit((b >> 4) & 0xF, 16)).append(Character.forDigit(b & 0xF, 16));
}
return hex.toString();
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(e);
}
}

private static String env(String name, String fallback) {
String value = System.getenv(name);
return value == null || value.isEmpty() ? fallback : value;
}
}
Loading
Loading