Get Started with Datadog

Engineering

Scaling metrics queries for AI workloads with Distributed DataFusion

Published

Read time

12m

Scaling metrics queries for AI workloads with Distributed DataFusion
Jayant Shrivastava

Jayant Shrivastava

Senior Software Engineer

Gene Bordegaray

Gene Bordegaray

Software Engineer

Nga Tran

Nga Tran

Staff Engineer

Xavier Lee

Xavier Lee

Senior Software Engineer

Justin O'Dwyer

Justin O'Dwyer

Software Engineer II

Some of the largest metrics queries at Datadog fan out across millions of timeseries and scan terabytes of data. As data sizes and cardinalities grow, we distribute queries across machines and reduce the cost of grouping by string-valued tags to optimize query latency. At the same time, we account for coordination and network shuffle overhead.

With the rise of AI-driven development, we see more source data being produced, along with more queries and larger individual queries. Queries not only power dashboards but may also need to return millions of points for LLMs to analyze. To support these workloads, we built and shipped a distributed execution model based on Apache DataFusion and Substrait. In a local benchmark, distributing a representative query improved performance by 2.5× per core, reducing latency from approximately 420 ms on four cores to 42.2 ms on 16 cores.

In this post, we’ll explain how we distributed DataFusion query plans, how we made them scale near linearly with resources, and how we optimized them for high-cardinality timeseries queries.

Designing a query engine with DataFusion

To build this new execution model, we first separated query planning from execution. We represented each query in relational algebra as a series of well-defined operations, such as scans, filters, projections, joins, aggregations, and unions.

We chose Apache DataFusion, an extensible query engine written in Rust, for three reasons:

  • Streaming execution: DataFusion streams Apache Arrow record batches through the execution plan. Processing batches incrementally instead of materializing entire result sets helps the engine handle larger volumes of data.

  • Open source and extensibility: DataFusion gave us an existing foundation for relational query planning and execution. We could focus on our domain-specific logic by implementing custom plan nodes, user-defined functions (UDFs), and optimizer rules.

  • Parallel execution within a node: DataFusion partitions work across CPU cores, providing the parallel execution model we needed within each machine. 

We also adopted Substrait as the intermediate representation between our existing query planner and the DataFusion engine. As shown in Figure 1, the query planner converts a customer query into a Substrait logical plan, which it passes to DataFusion for execution.  

Flow diagram showing a customer query passing through the query planner to produce a Substrait logical plan. The plan is sent to the DataFusion query engine for execution across multiple workers that read from metrics storage.
Figure 1: Our existing query planner converts a customer query into a Substrait logical plan, which the DataFusion-based query engine executes across distributed workers that read from metrics storage.
Flow diagram showing a customer query passing through the query planner to produce a Substrait logical plan. The plan is sent to the DataFusion query engine for execution across multiple workers that read from metrics storage.
Figure 1: Our existing query planner converts a customer query into a Substrait logical plan, which the DataFusion-based query engine executes across distributed workers that read from metrics storage.

Extending beyond a single node

DataFusion parallelizes execution across CPU cores on a single node. To meet our latency targets for queries that scan multiple terabytes of data, however, we needed to distribute that work across machines.

To do this, we developed Distributed DataFusion, which takes a single-node DataFusion physical plan, inserts network boundaries where data must be repartitioned, and splits the plan into stages that it schedules across a pool of workers. Each worker executes standard DataFusion plans and streams Apache Arrow RecordBatch objects to downstream workers. This extends DataFusion’s streaming execution model across the network without materializing intermediate results between stages.

Optimizing timeseries queries with Distributed DataFusion

The following example shows how DataFusion executes one of our production timeseries queries. We use an artificial schema and dataset to illustrate the process.

Data layout

Individual timeseries points can be represented by the schema (timestamp: u64, value: f64, <tag>: str, <tag>: str ...). For example, the points in Table 1 could be produced by a hypothetical service named agent-platform. In this example, each unique tag set defines a series, identified by its series_id. The number of distinct series for a metric is known as its cardinality, also called tagset cardinality.

To process this data in parallel, we divide it into partitions that DataFusion can evaluate as independent streams. With more cores, we can create more partitions and process them in parallel, enabling query performance to scale with the available resources.

A natural first step is to partition by timestamp (ts). However, timestamp alone is not sufficient because a given time range may contain many unique series. To account for this cardinality, we add series_id as a second partitioning dimension.

In this example, the data is partitioned into 4‑hour blocks and two series_id ranges—[a–c] and [d–e]—resulting in four partitions shown in Table 1.

Table 1: Timeseries data

Partition P1: ([0-4h), [a-c])

series_idtsvaluehostservicemodelagent
a00:00:001.0 i-1234 agent-platformscout-1.0 sre
a00:00:302.0 i-1234 agent-platformscout-1.0 sre
a00:01:303.0 i-1234 agent-platformscout-1.0 sre
a00:01:314.0 i-1234 agent-platformscout-1.0 sre
a00:02:00 5.0 i-1234 agent-platformscout-1.0 sre
a00:02:30 6.0 i-1234 agent-platformscout-1.0 sre
b00:02:005.0i-4567agent-platformgpt-6.1-sol swe
b00:03:001.0i-4567agent-platformgpt-6.1-sol swe
c00:00:001.0i-1234agent-platformfable-5.2alert-investigator
c00:03:003.0i-1234agent-platformfable-5.2alert-investigator

Partition P2: ([0-4h), [d-e])

series_idtsvaluehostservicemodelagent
d00:02:008.0i-8912agent-platformgpt-6.1-solswe
d00:02:302.0i-8912agent-platformgpt-6.1-solswe
d00:03:304.0i-8912agent-platformgpt-6.1-solswe
e00:02:001.0i-6789agent-platformgpt-6.1-solswe
e00:03:159.0i-6789agent-platformgpt-6.1-solswe

Partition P3: ([4-8h), [a-c])

series_idtsvaluehostservicemodelagent
c04:20:002.0i-1234 agent-platformfable-5.2alert-investigator
c04:20:304.0i-1234 agent-platformfable-5.2alert-investigator

Partition P4: ([4-8h), [d-e])

series_idtsvaluehostservicemodelagent
e04:15:002.0i-6789agent-platformgpt-6.1-solswe
e04:15:30 7.0i-6789agent-platformgpt-6.1-solswe

Query and query plan

The following query counts the distinct (agent, model) groups produced by the agent-platform service in 60-second intervals. In production, it is represented as a Substrait logical plan. For simplicity, we show the equivalent in SQL:

SELECT time_bin, count(*)
FROM (
SELECT DISTINCT date_bin(INTERVAL '60s', ts) AS time_bin, model, agent
FROM "agent-platform"
) AS base
GROUP BY time_bin

Single-node query plan

Figure 2 shows the single‑node query plan for the query above. Reading bottom to top: 

  • A DataSourceExec scans the timestamp, value, model, and agent columns. 

  • A ProjectionExec converts each timestamp into a time_bin representing the start of its 60‑second interval. 

  • A two-step AggregateExec identifies distinct (time_bin, model, agent) groups. 

  • A second two-step AggregateExec counts those groups within each time_bin.

Bottom-up query plan in which timestamps from four data partitions are assigned to time bins, deduplicated by (model, agent), and counted per bin.
Figure 2: Single-node query plan for counting distinct (model, agent) groups within each 60-second interval.
Bottom-up query plan in which timestamps from four data partitions are assigned to time bins, deduplicated by (model, agent), and counted per bin.
Figure 2: Single-node query plan for counting distinct (model, agent) groups within each 60-second interval.

DataFusion’s execution model streams columnar record batches through pipelined operators across four partitions in parallel. Operators within a partition are pipelined unless they encounter a pipeline breaker. For example, aggregations over unsorted data must consume all input before producing output. We’ll return to this when we discuss our optimizations.

The first step is to assign each datapoint to a time bin. The ProjectionExec applies date_bin to each timestamp, converting it to the start of its time_bin.

Table 2a: P1.1 output from ProjectionExec

series_idtime_binmodelagent
a00:00:00scout-1.0sre
a00:00:00scout-1.0sre
a00:01:00scout-1.0sre
a00:01:00scout-1.0sre
a00:02:00scout-1.0sre
a00:02:00scout-1.0sre
b00:02:00gpt-6.1-solswe
b00:03:00gpt-6.1-solswe
c00:00:00fable-5.2alert-investigator
c00:03:00fable-5.2alert-investigator

Table 2b: P2.1 output from ProjectionExec

series_idtime_binmodelagent
d00:02:00gpt-6.1-sol swe
d00:02:00 gpt-6.1-sol swe
d00:03:00 gpt-6.1-sol swe
e00:02:00 gpt-6.1-solswe
e00:03:00 gpt-6.1-solswe

Next, we determine the distinct tag groups in each time_bin by grouping on (time_bin, model, agent). The tuple (00:02:00, gpt-6.1-sol, swe) appears in both partitions above, so we need to aggregate across partitions.

DataFusion handles this by inserting a RepartitionExec and another AggregateExec, as shown in Figure 3. The RepartitionExec routes rows with the same (time_bin, model, agent) grouping key to the same partition. Table 3 shows the output of this aggregation.

Partial aggregation, repartitioning by time_bin, model, and agent, and final aggregation across four partitions.
Figure 3: DataFusion repartitions rows by (time_bin, model, agent) before completing the distinct aggregation.
Partial aggregation, repartitioning by time_bin, model, and agent, and final aggregation across four partitions.
Figure 3: DataFusion repartitions rows by (time_bin, model, agent) before completing the distinct aggregation.

Table 3: Output of the distinct aggregation (X1–X4)

time_binmodelagent
00:00:00scout-1.0sre
00:00:00fable-5.2alert-investigator
00:01:00scout-1.0sre
00:02:00scout-1.0sre
00:02:00gpt-6.1-solswe
00:03:00gpt-6.1-solswe
00:03:00fable-5.2alert-investigator
04:15:00gpt-6.1-solswe
04:20:00fable-5.2alert-investigator

Finally, we count the distinct (model, agent) tuples in each time_bin. Because the data is not partitioned by time_bin, DataFusion inserts another RepartitionExec, as shown in Figure 4.

Partial count aggregation, repartitioning by time_bin, and final count aggregation across four partitions.
Figure 4: DataFusion repartitions rows by time_bin before completing the count aggregation.
Partial count aggregation, repartitioning by time_bin, and final count aggregation across four partitions.
Figure 4: DataFusion repartitions rows by time_bin before completing the count aggregation.

Table 4: Output of the final count aggregation (Y1–Y4)

time_bincount
00:00:002
00:01:001
00:02:002
00:03:002
04:15:001
04:20:001

We benchmarked this query locally with Criterion, using four cores and 1.8 MB of compressed data. The query took approximately 420 ms. The following sections show how we reduced this execution time. 

Distributing the query plan

In production, we run queries that scan terabytes of data and generate plans with thousands of partitions. Figure 5 shows one of these plans on a single node.

Single-node query plan with repeated operators and many parallel partition paths.
Figure 5: A single-node query plan with more partitions than the machine has available cores.
Single-node query plan with repeated operators and many parallel partition paths.
Figure 5: A single-node query plan with more partitions than the machine has available cores.

Consider a query with 256 partitions running on a machine with 32 cores. With core DataFusion, we could either execute all 256 partitions concurrently on that machine or merge them into 32 partitions. Executing more partitions than there are cores adds overhead, while merging them reduces parallelism.

Distributed DataFusion distributes work across cores on multiple machines, enabling more partitions to execute in parallel. 

At a repartition boundary, Distributed DataFusion introduces a NetworkShuffleExec that moves data between workers, as shown in Figure 6.

A single-node repartition converted into producer and consumer stages connected by network shuffles.
Figure 6: A NetworkShuffleExec redistributes data across workers at a repartition boundary.
A single-node repartition converted into producer and consumer stages connected by network shuffles.
Figure 6: A NetworkShuffleExec redistributes data across workers at a repartition boundary.

Applying this transformation converts the single-node plan into the distributed plan shown in Figure 7. Statistics and adaptive query execution determine the number of workers at each stage. For more details, see How we extended Apache DataFusion to execute one query across many machines.

Four-stage plan in which 16 workers scan data, eight and four workers aggregate shuffled results, and one worker coalesces the final output.
Figure 7: The distributed plan assigns progressively fewer workers to each of its four stages.
Four-stage plan in which 16 workers scan data, eight and four workers aggregate shuffled results, and one worker coalesces the final output.
Figure 7: The distributed plan assigns progressively fewer workers to each of its four stages.

We reran the Criterion benchmark on 16 cores, using four in-process workers with four cores each. The query completed in 188.01 ms, a reduction of approximately 55% compared with the single-node query. Perfect linear scaling from four to 16 cores would reduce execution time by 75%. The result fell short of that ideal because of transport and coordination overhead, as well as synchronization points such as repartitions and shuffles.

Although distributing the plan reduced execution time substantially, it still performed two shuffles and grouped data using string-valued tags. We next focused on eliminating one shuffle and making the grouping keys cheaper to process.

Eliminating a shuffle and reducing grouping-key costs

Recall the two main aggregations in the query:

  • Aggregation 1: Group by time_bin, model, agent

  • Aggregation 2: Group by time_bin and compute count(*)

Executing these aggregates in sequence requires six operations, including two repartitions, as shown in Figure 8.

Six-operator plan containing two partial aggregations, two repartitions, and two final aggregations.
Figure 8: Each aggregation uses partial and final operators separated by a repartition.
Six-operator plan containing two partial aggregations, two repartitions, and two final aggregations.
Figure 8: Each aggregation uses partial and final operators separated by a repartition.

If the data is partitioned by time_bin, we do not need to repartition it by time_bin, model, agent. Rows with the same complete grouping key also share the same time_bin, so they are already colocated. We contributed a subset satisfaction rule to DataFusion that recognizes when an existing partitioning key is a subset of the aggregation’s grouping key and eliminates the unnecessary repartition.

Using this subset relationship, we implemented an optimizer rule that changes the first RepartitionExec to partition only by time_bin. The second aggregation can then reuse that partitioning, eliminating the second RepartitionExec, as shown in Figure 9.

Optimized plan in which both aggregations share one repartition by `time_bin`.
Figure 9: Repartitioning by time_bin satisfies both aggregations and removes the second repartition.
Optimized plan in which both aggregations share one repartition by `time_bin`.
Figure 9: Repartitioning by time_bin satisfies both aggregations and removes the second repartition.

Eliminating a RepartitionExec from the single-node plan also eliminates the corresponding network shuffle in Distributed DataFusion. 

We also wanted to reduce the cost of grouping by string-valued tags. A query that calculates distinct groups across tags such as model, agent, gpu_id, host, service, datacenter, and pod_name must hash several strings and transfer those values over the network. To reduce that work, the ProjectionExec hashes the tags into a u64 grouping key before partitioning, as shown in Figure 10.

Optimized plan that adds `time_bin` and a hashed grouping key before repartitioning and aggregation.
Figure 10: The ProjectionExec hashes (model, agent) into a u64 grouping key before repartitioning.
Optimized plan that adds `time_bin` and a hashed grouping key before repartitioning and aggregation.
Figure 10: The ProjectionExec hashes (model, agent) into a u64 grouping key before repartitioning.

Together, shuffle elimination and early hashing reduced the distributed plan’s execution time to 42.2 ms. This represents a 77.6% reduction from the initial distributed result of 188.01 ms and an approximately 90% reduction from the initial single-node result of approximately 420 ms. 

Table 5 summarizes the local Criterion benchmark across all three plans. Each run used 1.8 MB of compressed data. The distributed runs used four in-process workers with four cores each.

Table 5: Local Criterion benchmark across all three plans

Query planCoresExecution time
Single-node baseline4~420 ms
Initial distributed plan16188.01 ms
Distributed plan with shuffle elimination and early hashing1642.2 ms

Relative throughput per core is calculated by dividing the product of the single-node baseline’s execution time and core count by the product of each plan’s execution time and core count.

Results

We benchmarked DataFusion-based execution on a large OLAP-style query designed to stretch the limits of our current system. Distributed DataFusion continued to complete queries as query range increased. This result is consistent with the benefits of its streaming execution model.

Latency rises with query range; current-system results cover sub-month ranges, while DataFusion results extend to eight months.
Figure 11: Latency for the current and DataFusion-based systems as the query time range increases.
Latency rises with query range; current-system results cover sub-month ranges, while DataFusion results extend to eight months.
Figure 11: Latency for the current and DataFusion-based systems as the query time range increases.

For smaller queries, the current system still has lower latency because it has been highly optimized for those workloads.

In another experiment, we measured query speedup as we increased the number of machines. Adding machines reduced latency, with the greatest speedups appearing for the longest query ranges. In practice, network and coordination overhead, along with synchronization points such as repartitions, prevent perfect linear scaling. 

Line chart showing greater speedup for longer queries as node count increases, with a dashed line representing ideal linear scaling.
Figure 12: Observed speedup across query ranges compared with ideal linear scaling.
Line chart showing greater speedup for longer queries as node count increases, with a dashed line representing ideal linear scaling.
Figure 12: Observed speedup across query ranges compared with ideal linear scaling.

Looking ahead

We’re continuing to expand DataFusion-based execution at Datadog. Here are three areas we’re currently exploring.

Series per row and data sketches

So far, we’ve discussed ways to count distinct groups without mentioning HyperLogLog (HLL), a compact representation for approximating distinct counts. Because our use case requires exact results, HLL is not a fit. However, compact sketches such as HLL and DDSketch are useful for queries that can tolerate approximate results. 

We experimented with a compact data type called  presence_bitmap to record whether a value exists at each timestamp aligned to a 60-second interval (Table 6).

Table 6: Example timeseries data represented with presence bitmaps

series_idmodelagentpresence_bitmap
ascout-1.0sre1110 ... 0 ... 0
bgpt-6.1-solswe0011 ... 0 ... 0
cfable-5.2alert-investigator1001 ... 0 ... 1
dgpt-6.1-solswe0011 ... 0 ... 0
egpt-6.1-solswe0011 ... 1 ... 0

In local benchmarks, this representation reduced compute and memory use by up to 90% in some operators. Hash joins and aggregations hash every input row, so fewer rows means fewer hashes. Using a bitmap allowed us to reduce row cardinality, producing substantial savings.

Reducing shuffles with range partitioning

DataFusion uses hash shuffles, in which any row can land in any output partition. With thousands of partitions, an N-to-N shuffle becomes very expensive. Because aggregations over unsorted data must consume all rows before completing, a large shuffle can become a pipeline breaker for the entire query.

One way to avoid shuffling is to use unions. The input data is partitioned by time, and the output typically is too. We can then attempt to run queries as unions of independent subqueries over disjoint time ranges.

A UnionExec combines subqueries for consecutive four-hour time ranges.
Figure 13: A UnionExec combines independent subqueries over disjoint 4-hour ranges.
A UnionExec combines subqueries for consecutive four-hour time ranges.
Figure 13: A UnionExec combines independent subqueries over disjoint 4-hour ranges.

This approach breaks down when an aggregation spans time partitions, for example, when 4-hour input partitions feed a 6-hour aggregation window. To address this, we contributed to DataFusion’s native range-partitioning support and are now exploring how to use it to optimally shuffle data in Distributed DataFusion. 

Extending dynamic filtering across workers

Dynamic filtering reduces the amount of data scanned by reader nodes, producing performance gains throughout the rest of the query plan. It works by sharing filter state between an operator, such as a join, and the data sources below it, allowing the data source to prune rows before they reach the join. 

In a distributed plan, however, shared-memory state does not cross network boundaries. As a result, a filter produced on one worker cannot reach a data source running on another worker.

A filter from a hash join stops at the network boundary before reaching the probe-side data source.
Figure 14: A dynamic filter produced by `HashJoinExec` cannot reach a data source on another worker.
A filter from a hash join stops at the network boundary before reaching the probe-side data source.
Figure 14: A dynamic filter produced by `HashJoinExec` cannot reach a data source on another worker.

To support this use case, we contributed upstream support for serializing and deduplicating dynamic filters in PR #21807 and for propagating dynamic-filter expressions across network boundaries in PR #24018. Doing so enabled us to implement distributed dynamic filtering support in Distributed DataFusion. 

Continuing to scale metrics query execution

AI-driven development is changing both the volume of software being produced and the systems engineers need to observe. For Datadog, that means supporting higher-cardinality data and increasingly large, complex queries while continuing to serve the smaller dashboard queries our metrics platform was originally optimized for.

To handle these new workloads, we shipped a distributed execution model based on Apache DataFusion and Substrait. We also optimized query plans to eliminate a network shuffle and reduce grouping-key costs. In a local benchmark, those optimizations reduced the distributed plan’s execution time from 188.01 ms to 42.2 ms on 16 cores. In a separate experiment, adding machines reduced latency, with the greatest speedups for longer query ranges. We’re continuing to improve DataFusion-based execution, including by exploring bitmap-based representations and range partitioning.

If you’d like to help us solve these kinds of distributed systems problems, explore open roles on Datadog’s Engineering team.

Start monitoring your metrics in minutes