Ivo Anjo Staff Engineer Scott Gerring Senior Technical Advocate A profiler can identify the hottest code and still be unable to tell you which request the code was handling. That’s because broad, consistent profiling coverage is often not enough to reconstruct context: By itself…
Jayant Shrivastava Senior Software Engineer Gene Bordegaray Software Engineer Nga Tran Staff Engineer Xavier Lee Senior Software Engineer Justin O'Dwyer Software Engineer II Some of the largest metrics queries at Datadog fan out across millions of timeseries and scan terabytes o…
Francisco Paulo Staff Engineer OpenTelemetry (OTel) gives observability data a common vocabulary through its semantic conventions, but the vocabulary continues to evolve. For example, when OpenTelemetry stabilized its HTTP semantic conventions, the http.method attribute became h…
Khayyam Guliyev Manager II, Engineering Each new generation of Datadog’s metrics aggregation system had to support roughly 10× the metrics volume of the generation before it. As volume grew, managing and recovering aggregation state became the system’s main scaling constraint. M…
Nicolas Couvrat Senior Software Engineer Formal specifications can help engineers reason about complex distributed systems and verify critical correctness properties. But they remain valuable only as long as they reflect reality. At Datadog, we encountered this challenge while w…
Callan Lamb Manager II, Security Engineering Brianna Heffernen Manager I, Engineering A malicious change introduced in source, a poisoned dependency, or a compromised build runner that swaps a base image can each produce an image with a valid signature. Container image signing c…
Gabriel Musat Mestre Staff Engineer As Datadog has moved toward open standards, we chose Apache DataFusion as a single composable query engine to replace previously specialized query systems. At Datadog scale, however, some queries must scan enormous amounts of data while still…
Thomas Kowalski Senior Software Engineer Scott Gerring Senior Technical Advocate We released the first version of the Datadog Python profiler almost 10 years ago. Since then, frameworks built on asyncio have become common, and asynchronous code has become the norm for many Pytho…
Björn Antonsson Staff Engineer Paul Le Grand des Cloizeaux Senior Software Engineer Scott Gerring Senior Technical Advocate When we started building more production services in Rust at Datadog, tracing was the part of our observability stack that needed to evolve alongside it th…
Mike Thompson Senior Staff Engineer Daniel Esponda Staff Engineer If you have ever watched a CI job sit on “Fetching repository …” while nothing seems to happen, you already know the unglamorous truth about continuous integration: Every job begins by getting the code, and gettin…
Startup performance is critical for users, developers, and cloud costs, but Java APM instrumentation must balance observability against the overhead of transforming classes. Datadog reduced class-matching overhead by 30% over four years by optimizing the first filtering stage: matching class-name prefixes. Its main innovation was encoding a prefix trie as a single JVM string constant, avoiding the startup cost of constructing a conventional trie.
## Java Instrumentation and Class Matching
- Java APM uses the Java Instrumentation API to intercept and transform classes as they load.
- Instrumentation adds method advice that records method execution and propagates tracing context.
- Instrumenting every method would be too expensive, so APM first identifies valuable classes.
- Applications may load tens or hundreds of thousands of classes, making efficient filtering important.
- Class-name and package-prefix checks are cheaper than structural or hierarchy-based checks because they avoid parsing class files.
- Datadog therefore begins with a curated ignore list of class and package prefixes.
## Startup Constraints in `premain`
- Agents register transformers in the JVM’s `premain` phase, before the application’s `main` method.
- At this point:
- Few classes have been loaded.
- The JIT compiler is cold or unavailable, especially on Java 8.
- Code runs interpreted and unoptimized.
- Loading or calling certain JDK classes can have irreversible side effects.
- For example, touching `java.util.logging` initializes `LogManager`, potentially preventing an application from configuring its own logging manager later.
- These constraints make ordinary data loading, parsing, and object construction undesirable during startup.
## Replacing a Hand-Written Matcher with a Trie
- Datadog’s earlier matcher used a complex nested code structure to represent prefixes.
- Although flexible, it was difficult to maintain and required special optimizations for Java 8 startup.
- A trie was a natural replacement because it shares common characters among prefixes and supports efficient lookup.
- A conventional trie would require:
- Locating and reading a resource.
- Parsing its contents.
- Constructing trie nodes.
- Loading additional code or dependencies.
- Those operations would impose unacceptable costs during `premain`.
## Encoding the Trie as a JVM Constant
- Datadog created `ClassNameTrie`, which stores the entire prefix trie in a Java string constant.
- The JVM loads the encoded data with a single `ldc` bytecode instruction.
- This approach avoids resource I/O and runtime trie construction.
- Embedding the data in the class also makes it resilient to repackaging.
- The compact representation improves cache locality and reduces startup work.
## Compact Node Representation
- Java strings contain 16-bit `char` values, allowing each character to encode one of 65,536 possible values.
- Each trie node stores:
- A character indicating the number of branches.
- Sorted branch characters, enabling binary search.
- One value character per branch.
- Value characters encode different outcomes:
- **Leaf:** returns a definitive result and ends the search.
- **Bud:** records a possible result but permits further matching.
- **Inline segment length:** indicates that additional prefix characters are stored directly.
- Buds and leaves can include a **glob bit**, allowing a match to apply even when extra characters remain in the class name.
- The encoding reserves the remaining value range for match results, with a maximum stored value of 8,191.
The broader lesson is that startup-sensitive JVM code may benefit from moving computation into class-loading time and representing lookup structures in compact constants. For Java agents, precomputed, dependency-free data structures can deliver trie-like performance without the initialization and JIT costs of building them at runtime.
Java Flight Recorder (JFR) provides low-overhead, production-safe diagnostics, but its `ExecutionSample` event can produce biased CPU profiles because it samples JVM-observed runnable threads rather than strictly measuring CPU time. For CPU-bound workloads—particularly reactive applications—this may obscure the real hotspots. Modern profilers therefore combine JFR with JVMTI, `SIGPROF`, `AsyncGetCallTrace`, and JVM-internal techniques, while the Java ecosystem works toward a supported CPU-sampling mechanism.
## How Sampling Profilers Work
- Continuous profilers repeatedly capture stack traces and aggregate them to reveal recurring behavior.
- CPU profilers commonly sample at fixed intervals, such as every 20 milliseconds.
- **CPU-time sampling** highlights code actively consuming processor cycles.
- **Wall-clock sampling** reveals latency sources, including I/O waits, lock contention, and blocked threads.
- Other profilers trigger on events such as allocations, garbage collection, thread parking, or lock contention.
- Regardless of the trigger, profilers capture a stack, associate it with an event, and aggregate the results.
## Limitations of JFR’s `ExecutionSample`
- JFR is integrated into the JVM and designed for low-overhead, always-on production use.
- Its `ExecutionSample` event captures stacks from a rotating subset of runnable threads.
- CPU-heavy threads tend to appear more often, but samples are not strictly proportional to actual CPU consumption.
- This can lead to incomplete or biased results on CPU-saturated systems.
- Reactive applications are a notable example: their scheduling behavior can cause thread CPU usage and hotspots to be underrepresented.
## CPU Sampling with `AsyncGetCallTrace`
- JVMTI agents can use operating-system signals such as `SIGPROF` to sample threads according to CPU time.
- The signal handler invokes HotSpot’s `AsyncGetCallTrace` to walk Java stacks asynchronously.
- This approach avoids safepoint bias and can capture stacks during arbitrary execution states.
- Tools such as `async-profiler` use this technique to produce profiles that more closely match actual CPU usage.
- The drawback is that `AsyncGetCallTrace` is an unsupported internal JVM API.
- Under heavy load, it can occasionally fault, requiring profilers to add extensive safeguards.
- Datadog also uses **vmstructs walking**, which reads internal JVM metadata to recover stack and runtime information unavailable through standard APIs.
## The Safety–Accuracy Tradeoff
- JFR offers stability, structured runtime telemetry, and low overhead.
- `AsyncGetCallTrace` and vmstructs walking offer more accurate CPU sampling.
- Relying on JVM internals creates maintenance and reliability risks because those interfaces are not officially stable.
- Consequently, modern profilers combine JFR with unsupported sampling mechanisms rather than choosing only one approach.
## Toward a Supported CPU Profiling Event
- Datadog, SAP, Amazon, and OpenJDK contributors recognized that this limitation affected the broader profiling ecosystem.
- JFR was already the natural foundation for safe, continuous profiling.
- The missing capability was a first-class CPU sampling event that could provide accurate CPU-based results without depending on unsupported JVM internals.
- Datadog participated in OpenJDK discussions to explain why existing sampling was insufficient and to help improve the platform’s profiling foundation.
Ultimately, accurate production CPU profiling requires both JFR’s safety and CPU-time-based sampling. A supported JFR CPU profiling event would remove the ecosystem’s dependence on fragile JVM internals while preserving the low-overhead behavior needed for continuous use.
Datadog built a real-time data-completeness system to ensure that every customer’s telemetry is available for dashboards, alerts, queries, and AI-driven decisions. Because ingestion spans hundreds of distributed paths and customers may send delayed or retried data, global or watermark-based tracking is unreliable. The system instead tracks payloads segment by segment, using idempotent create and acknowledgment events to identify losses and calculate end-to-end completeness.
## Defining Completeness at Datadog’s Scale
- Completeness means every ingested payload—metrics, logs, spans, or other telemetry—is ultimately available to customers.
- The system must measure completeness:
- Across hundreds of services and ingestion paths
- For each individual customer
- In real time
- With enough detail to identify where degradation occurred
- Customer traffic may take different routes because of partitioning, isolation, and traffic patterns.
- Metrics and APM pipelines can each involve hundreds or tens of distinct paths, creating a large number of possible failure points.
- The completeness system must remain independent of the services it monitors so it can provide trustworthy diagnostics during incidents.
## Tracking Completeness by Pipeline Segment
- Datadog considered watermark-based tracking, but delayed customer data, replayed traffic, and pipeline loops made predictable watermarks impractical.
- Pipelines are divided into segments representing steps within or between services.
- For example, intake-in to intake-out is one segment.
- Intake-out to processing-in is another.
- Each segment is measured independently, allowing engineers to locate degradation within a service or between services.
- Segment-level tracking also adapts to pipelines whose branches appear or disappear over time.
## Counting Creates and Acknowledgments
- When a payload enters a segment, the system records a create event.
- When it exits, the system records an acknowledgment using the payload’s unique identifier.
- Comparing creates with acknowledgments reveals whether payloads were lost in that segment.
- Events are organized into time buckets based on when the payload first entered Datadog, using a Datadog-controlled timestamp rather than the customer’s clock.
- Each identifier has a state per segment:
- Created
- Acknowledged
- Acknowledged before the create event arrived
- Duplicate create or acknowledgment events are ignored, making the system idempotent despite retries and event reordering.
## Calculating End-to-End Completeness
- Segment completeness is the ratio of payloads exiting a segment to those entering it.
- For sequential services, overall completeness is calculated by multiplying segment ratios.
- Parallel branches require a different approach:
- Treating branches as one pipeline would make completeness wait for the slowest branch.
- Instead, Datadog uses a weighted average, giving each branch influence proportional to the volume it processes.
- In the example, one branch reaches 94% completeness by multiplying 98% and 96% across two sequential services, while another branch reaches 100%.
- Combining these branch measurements produces a more accurate view of currently available data without incorrectly marking all data incomplete because one branch is slower.
## Practical Conclusion
Segment-level, identifier-based tracking gives Datadog a real-time and customer-specific view of data completeness. It both supports reliable end-to-end calculations and helps humans or automated systems quickly determine where ingestion problems are occurring.
Stream Router evolved from a small configuration file into a critical control-plane service routing Datadog’s massive metrics workload. Its original FoundationDB key-value model eventually hit transaction-size and performance limits because relational relationships were reconstructed in application code. Datadog redesigned the system around PostgreSQL and DuckDB, using AI-assisted, test-driven refactoring to accelerate the migration without disrupting production traffic.
## Stream Router’s Role in Datadog’s Metrics Pipeline
- Datadog processes more than a hundred trillion events per day.
- Stream Router determines which Kafka cluster, topic, partitions, and sharding strategy should handle each datapoint.
- It serves both producers and queriers but does not process Kafka messages itself.
- Routing decisions change frequently as infrastructure evolves, making correctness and historical tracking essential.
## From Configuration File to Control Plane
- In 2016, routing was managed through a small configuration file distributed to services.
- As the platform grew, the file expanded to thousands of lines and required manual edits and rollouts.
- Stream Router replaced this workflow with:
- A centralized gRPC service
- API-managed routes
- Automated, gradual rollouts
- The write path used FoundationDB, while the read path served static RocksDB snapshots restored into memory.
- This eventually became a bottleneck as routing tables and operational changes grew larger.
## Why the Key-Value Model Stopped Scaling
- Routes reference streams and sharding strategies, while rules reference routes.
- These relationships are inherently relational and require cross-entity validation.
- The KV implementation loaded tens of thousands of records into application processes and reconstructed database-like relationships in code.
- Some operations exceeded FoundationDB transaction-size limits.
- Moving to PostgreSQL without changing the access patterns would not solve the issue; certain operations were estimated to require 45 minutes because of thousands of sequential database round trips.
- The fundamental problem was the data model and application logic, not simply the choice of database.
## Designing the New Storage Architecture
- The team redesigned the schema manually before using AI tools.
- The relational model introduced explicit foreign keys between:
- Streams
- Sharding strategies
- Routes
- Rules
- PostgreSQL was selected for the write path because it provided the required relational semantics and transaction model.
- DuckDB was selected for the read path because:
- It is embeddable and suitable for snapshot-based serving
- It supports array columns
- Its SQL dialect is closely compatible with PostgreSQL
- Shared query logic could therefore work across both storage engines.
## AI-Assisted Refactoring
- Claude and Cursor were used to accelerate a systematic, test-driven migration.
- For each method, developers supplied:
- The old implementation
- The new schema
- A failing test
- AI generated an initial implementation, while tests determined whether it was correct.
- The models assisted with method-level refactoring rather than autonomously designing the architecture.
- Human expertise remained central to schema design, migration strategy, and evaluating system-level risks.
## Foundations for a Safe Migration
- The migration benefited from infrastructure already present at Datadog.
- Stream Router’s storage layer was isolated behind an internal `Controller` interface.
- This modularity helped contain storage changes and enabled incremental refactoring.
- Existing tests and clear boundaries provided confidence in generated implementations while production traffic continued.
The central lesson is that AI was most effective as an accelerator inside a disciplined engineering process. A well-designed relational schema, modular storage abstraction, and failing tests provided the safety mechanisms; AI helped implement the resulting changes faster, but did not replace human architectural judgment.
Datadog’s gameday testing exposed a PostgreSQL failure mode in which network latency caused replication lag to grow until no standby could be safely promoted. Although the clusters remained writable, they could not fail over without risking data loss, forcing operators to wait for connectivity and replicas to recover. Datadog’s solution was to redesign failover candidates around synchronous replication coordinated by Patroni, balancing stronger durability with acceptable write latency.
## The Zonal Failure That Exposed the Weakness
- A simulated availability-zone failure introduced network latency in a staging environment.
- Several Kubernetes-based PostgreSQL clusters had primary nodes in the affected zone.
- Communication between primaries and replicas degraded, causing:
- Rapidly increasing replication lag
- Stalled writes
- Applications serving stale data
- No replica being current enough for safe promotion
- The clusters prioritized continued writes over durability, leaving them writable but unable to fail over safely.
## Baseline PostgreSQL Architecture
- Each cluster uses a single-writer design:
- One active leader handles writes.
- Two standby nodes are reserved for failover and do not serve application traffic.
- A separate read-replica pool handles read-only traffic and scales independently.
- Read replicas are intentionally excluded from failover candidates.
- Patroni manages replication, leader elections, and failover.
- ZooKeeper acts as Patroni’s distributed configuration store, tracking:
- The current leader lock
- Cluster configuration
- Member replication state and latest LSN
- ZooKeeper’s ephemeral leader key ensures that only one node can become primary.
- During partitions, Patroni favors safety by pausing or demoting nodes that cannot verify cluster state.
## Why Failover Was Not Safe
- Patroni checks replication lag before promoting a standby using `maximum_lag_on_failover`.
- During the gameday, all eligible standbys exceeded that threshold.
- Patroni correctly rejected promotion because each candidate could have been missing committed transactions.
- The cluster therefore had no safe writable primary, even though the original leader was impaired.
- The failure was a consequence of asynchronous replication and network latency, not a failure in Patroni’s safety mechanisms.
## Asynchronous Versus Synchronous Replication
- **Asynchronous replication**, used originally:
- Lets the leader commit and respond without waiting for replicas.
- Provides low write latency and high throughput.
- Can lose transactions committed on the leader but not yet copied to a standby.
- **Synchronous replication**:
- Requires the leader to receive acknowledgment from at least one replica before confirming a transaction.
- Reduces the chance that a failover candidate is significantly behind.
- Provides stronger durability, but may increase write latency when replicas experience network or availability problems.
## The Redesigned Approach
- Datadog reworked its PostgreSQL deployment so failover candidates use synchronous replication.
- Patroni coordinates these replicas and continues to enforce safe leader election.
- The design aims to make failover both automatic and safe while limiting performance impact.
- Benchmarking and failure testing were used to evaluate the trade-off between durability and latency.
Datadog’s experience demonstrates that asynchronous replication can leave a system operational but unable to fail over during network disruption. For clusters where data durability and automatic recovery are critical, synchronous replication for designated failover candidates offers a safer architecture, provided its latency and availability costs are measured carefully.