Skip to content

Designing a Trace Query API with OpenSearch Aggregations

Interactive Diagram

새 탭 ↗

A distributed Runtime produces several Trace events for one execution. An operations view does not primarily need the event list; it needs one execution record answering which Interface ran, when it started and ended, and what its final state was. OpenSearch can build that execution list by aggregating events by guid.

Trying to answer list, detail, and Dashboard questions with one enormous query makes bucket count and response size grow quickly. Building on the identifier model in Designing Distributed Integration Tracing with GUID, UUID, HOP, and SEQ, this article defines concrete query boundaries and safe pagination for list and detail APIs.

A list view and a detail view ask different questions.

  • A list query creates one execution per guid within a bounded time range and Interface set. It returns only start/end time, final state, and error presence.
  • A detail query reads events for one selected guid, ordered by hop, time, and seq. It needs no grouping aggregation.
  • A raw-log query is separate and applies additional authorization and size limits when a large message is required.
PlantUML Diagram

The API does not inspect only the OpenSearch HTTP status. It checks timed_out and _shards.failed; if some shards failed, it must not hide an incomplete result behind 200 OK. Return a retryable error or an explicit partial-result state, and show the possibility of missing data in the operations view.

The list query first filters on interfaceId and time, then groups by guid. The minimum and maximum timestamps produce the execution interval, while the last event provides current state.

OpenSearch aggregationSQL-like meaningRole in the execution list
terms or compositeGROUP BY guidGroups events into one execution
top_hitsROW_NUMBER() OVER (PARTITION BY guid ORDER BY time DESC)Retrieves one last event
min / maxMIN(time) / MAX(time)Calculates start, end, and duration
cardinalityApproximate COUNT(DISTINCT value)Estimates unique executions
bucket_selectorHAVINGRetains only error or completed buckets
bucket_sortORDER BY plus slicing over grouped resultsSorts and limits buckets already created by its parent

durationMs = max(time) - min(time) is the observed interval between the first and last event under one guid. It is not necessarily pure target-service processing time: queueing, mapping, and retries may all be included. If a start or end event is missing, report the execution as incomplete rather than inventing a duration.

A top_hits aggregation should retrieve only fields required by the list, such as eventType, statusCode, time, hop, and seq. Large payloads and stack traces belong in the detail API.

This example limits a fictional inventory-sync-v1 Interface to a 15-minute window and reads at most 100 guid values per page. A composite aggregation exposes an after_key cursor and is suitable for traversing a high-cardinality set.

{
"size": 0,
"track_total_hits": false,
"query": {
"bool": {
"filter": [
{ "term": { "interfaceId": "inventory-sync-v1" } },
{ "range": { "time": { "gte": "2024-04-14T09:00:00Z", "lt": "2024-04-14T09:15:00Z" } } }
]
}
},
"aggs": {
"executions": {
"composite": {
"size": 100,
"sources": [
{ "guid": { "terms": { "field": "guid" } } }
]
},
"aggs": {
"started_at": { "min": { "field": "time" } },
"ended_at": { "max": { "field": "time" } },
"last_trace": {
"top_hits": {
"size": 1,
"sort": [{ "time": "desc" }, { "seq": "desc" }],
"_source": ["eventType", "statusCode", "time", "hop", "seq"]
}
},
"errors": { "filter": { "term": { "eventType": "ERR" } } }
}
}
}
}

The next page passes the response’s after_key unchanged.

{
"composite": {
"size": 100,
"after": { "guid": "g-demo-0200" },
"sources": [{ "guid": { "terms": { "field": "guid" } } }]
}
}

A composite aggregation pages in key order. It does not simultaneously provide arbitrary metric ordering, such as “most recently completed,” and deep pagination over the entire set. If newest-first listing is essential, enforce short time slices or write terminal events into an execution-summary index that supports ordinary search pagination. bucket_sort sorts only buckets already created by its parent; it is not an unbounded solution that creates every bucket and then safely slices the result.

Setting search.max_buckets to a near-unbounded value such as 2147483647 is an anti-pattern, not a recommendation. It permits one request to construct millions of buckets and sub-aggregation states, exhausting heap on coordinating and data nodes and degrading unrelated searches. Putting the same huge value into query-level size repeats the problem per request.

The safe response is to bound query work rather than remove the cluster guardrail.

  • Enforce maximum time range and interfaceId count in the API.
  • Cap page size at a small value and use composite plus after_key for deep traversal.
  • Precompute repeatedly requested Dashboard values in a summary index or batch aggregation.
  • Observe timeouts, circuit breakers, and slow logs, and measure cost per query shape.
  • Reject an oversized request with guidance to narrow the interval rather than silently truncating it.

A cluster-wide limit increase should be small and justified by measured workloads, heap headroom, and concurrency tests. It must not be the first fix for an application query that is intrinsically unbounded.

cardinality(guid) is an approximate HyperLogLog++ aggregation. It works for Dashboard trends, approximate throughput, and Alert thresholds, but not for settlement counts or contractual SLA denominators where even one missing execution matters. Raising precision_threshold can improve accuracy at additional memory cost; it does not turn the aggregation into an exact count.

For exact numbers, record each terminal event once in an idempotent ledger or execution-summary store and count there. The difference between the OpenSearch estimate and ledger count can itself become an operational signal for duplicate or missing ingestion.

Like SQL HAVING, bucket_selector removes buckets after metrics are calculated. It can retain only executions where errors._count > 0, or only those with both start and terminal events. Because a pipeline aggregation runs after its input buckets have already been created, it does not reduce search cost. Put every eligible restriction in bool.filter first.

Using only the final event’s statusCode can misclassify late events or compensation. Define state rules explicitly.

StateExample evaluation
RUNNINGHas a start event and no terminal event inside the grace period
SUCCEEDEDHas a terminal event and no error event
FAILEDHas an error event or a failed terminal status
INCOMPLETEGrace period expired but a start or terminal event is missing

Use an exact guid filter and a stable sort key instead of an aggregation for details. Pass the sort tuple referenced by search_after into the next page.

{
"size": 200,
"query": { "term": { "guid": "g-demo-7f2c" } },
"sort": [
{ "hop": "asc" },
{ "time": "asc" },
{ "seq": "asc" },
{ "_id": "asc" }
],
"_source": [
"time", "appName", "eventType", "guid", "uuid",
"hop", "seq", "interfaceId", "statusCode"
]
}

_id is the tie-breaker when preceding values are equal. Combine a point in time with search_after if a long traversal needs a consistent snapshot. Exclude raw message by default and expose it through a separate endpoint with masking, authorization, and a maximum byte size.

Responsibilities of query and Dashboard APIs

Section titled “Responsibilities of query and Dashboard APIs”

A Trace list helps an operator find an execution and drill into it. A Dashboard serves repeatedly requested time-series summaries such as total, error rate, and latency trend. The two APIs may share field definitions and filter builders, but their response models and cost budgets remain separate.

Do not rebuild every guid bucket and top_hits result for every Dashboard refresh. Use bounded aggregation for a short real-time window and precomputed summaries for longer periods. Conversely, returning only summaries from Trace detail loses the event order required for diagnosis.

One OpenSearch execution can be represented by a guid bucket with min/max, top_hits, and an error sub-aggregation. Lists use bounded aggregation and cursors, while details use an ordered event search for one guid. Never make search.max_buckets effectively unlimited; constrain time, scope, and page size, and use composite aggregation to traverse a complete bucket set. Cardinality is approximate and shard failure means missing data, so expose both properties honestly in the API Contract.