Skip to content

Separating Integration Alerting and Metrics

Interactive Diagram

새 탭 ↗

Sending an email for every ERR log makes alerts easy to ignore. Showing only numbers on a dashboard discovers an incident after it has passed. A useful observability model separates recording events, aggregating a window into a signal, and notifying a person.

This article builds interface dashboards and history statistics from a trace index, then creates alert history and notifications when a rule is satisfied. The same model connects synchronous APIs and Spring Batch job results.

This article uses the same log field names as the distributed tracing article: guid correlates one business exchange end to end, uuid identifies one log event or delivery attempt, seq orders events inside one guid, and hop marks a logical boundary. Where other documents say correlationId that is the same value as guid, and where they say messageId that is the same value as uuid.

Error Event, Alert, Incident, and Metric are different concerns

Section titled “Error Event, Alert, Incident, and Metric are different concerns”

An Error Event is a fact recorded at one processing step. Several hops under the same guid can fail, and one external outage can fail many Interfaces at once. An Alert is the result of turning those events into a signal that an operator must look at.

ConceptQuestionStored or delivered to
Error EventWhich step failed, and with what?Trace / event index
AlertDoes an operator need to act now?Alert history, notification
IncidentAre several Alerts one outage?Incident management
MetricHow does system state change over time?Dashboard / time series

With this separation, a retryable timeout can be grouped up to a threshold, a contract violation can be classified immediately, and hundreds of events from one outage can collapse into a single Alert.

PlantUML Diagram

The Querier turns searches and aggregations into API responses; the evaluator owns threshold decisions and deduplication. A notification adapter retries delivery failures without blocking dashboard queries.

The evaluator itself follows a fixed order: aggregate the window, resolve the last trace of each bucket, write alert history, and only then call the notification adapter.

PlantUML Diagram

Alert creation and message delivery must not share one transaction. History can be stored while notification fails temporarily, and the reverse is also possible. Record retry and state for each side independently.

Operational policy is built on reprocessability and blast radius rather than on exception class names.

ClassExampleNotification policy
Transientconnection timeout, temporary 5xx, rate limitAlert only after backoff retry exceeds a threshold
Contractschema mismatch, missing required fieldNo retry; alert the contract owner
Businessbusiness rule violation, duplicate requestRoute to a business channel, separate from technical alerts
Platformconsumer stopped, search cluster failureGroup and escalate by blast radius

Two different keys are needed, and they answer different questions.

The grouping key decides which events belong to the same signal, and drives suppression:

groupKey = interfaceId + errorClass + target + timeWindow

The dedup key decides whether a new alert history row may be inserted, and drives storage idempotency:

dedupKey = (ruleId, groupKey, windowStart)

The grouping key must never contain a guid. Using guid as a grouping key produces one notification per request, which is exactly the per-request alerting this model avoids. A guid belongs in the alert body as a lastTrace detail reference so an operator can jump into the trace view, not in the key that decides how many alerts exist.

The opposite failure also exists: a grouping key that spans too wide a time window or too many Interfaces merges unrelated outages. Grouping key and suppression window are operational parameters and should be tuned against observed alert volume.

Alerts ask whether action is needed now; metrics ask whether system state is improving. Each metric needs a definition formula, a time window, a target index, and an example aggregation.

The number of events in one request is not the number of business transactions. One guid can contain IFST, TXST, TXEN, and IFEN events, so guid cardinality is the transaction approximation and raw event count is not.

MetricDefinition formulaWindowTarget indexExample aggregation
total countcardinality(guid) over completed exchanges1m bucket, 15m viewtrace indexcardinality on guid
error countcardinality(guid where eventType = ERR)1m bucket, 15m viewtrace indexfilter + cardinality
error rateerror count / total count5m rollingtrace indexbucket_script over the two above
latency p50 / p95percentile of max(time) - min(time) per guid5m rollingtrace indexpercentiles on a bucket_script duration
TPMcardinality(guid) averaged per minute bucket1m bucket, 60m viewtrace indexdate_histogram + avg_bucket
in-flight countguid with a start event and no end eventevaluated at query timetrace indexbucket_selector on missing end
incomplete countguid missing either start or end after the grace period15mtrace indexbucket_selector after now-15m
replay backlogrows remaining in quarantine or dead lettercurrent valuedispatch / quarantine storecount by state
last executionlast statusCode and time per interfaceIdcurrent valuetrace indexterms on interfaceId + top_hits size 1
batch read/write/skipSpring Batch step execution countersper executionbatch result storesum per jobExecutionId

Latency percentiles are defined on the exchange, not on the event: for each guid compute duration = max(time) - min(time), then take the p50 and p95 of that duration set inside the window. Percentiles from a percentiles aggregation are approximate; use them for trend and threshold, not for contractual reporting.

The error-rate denominator must exclude in-flight guid values. An exchange that has started but not finished inside the window is neither a success nor a failure yet, and counting it as a denominator entry makes the error rate dip artificially during traffic bursts. Count only guid values with a terminal event in the window, and publish in-flight and incomplete counts as their own metrics so the missing volume stays visible.

Cardinality may not be exact, so use a ledger or dedicated counter for SLA and settlement numbers. Limit query ranges and bucket sizes, and never return shard failures as if they were successful data.

Building a guid bucket and computing start, end, error count, and last trace per bucket produces an execution-level list. top_hits is useful for the last state, but cost grows with bucket count and cardinality.

  • Cap the search range.
  • Push page and size into the aggregation stage.
  • Keep detail payloads out of aggregation results.
  • Clean old traces with retention and rollover policy.
  • Serve dashboards from precomputed summaries and read source events only in the detail view.
  • Request only the fields each query actually needs.

A dashboard query filters by interfaceId and time range first. It creates a guid terms bucket below each interface, then calculates the minimum start, maximum end, last event with top_hits, and error count. Interface buckets summarize those values with stats bucket aggregations.

{
"query": { "bool": { "filter": [
{ "terms": { "interfaceId": ["inventory-sync-v1", "catalog-sync-v2"] } },
{ "range": { "time": { "gte": "now-15m", "lt": "now" } } }
] } },
"aggs": {
"by_interface": { "terms": { "field": "interfaceId" }, "aggs": {
"by_guid": { "terms": { "field": "guid" }, "aggs": {
"error_count": { "filter": { "term": { "eventType": "ERR" } } },
"start": { "min": { "field": "time" } },
"end": { "max": { "field": "time" } },
"last_trace": { "top_hits": { "sort": [{ "seq": "desc" }], "size": 1 } }
} },
"minute_histogram": { "date_histogram": { "field": "time", "fixed_interval": "1m" }, "aggs": {
"count_guid": { "cardinality": { "field": "guid" } }
} }
} }
}
}

A date_histogram supplies dashboard trends and TPM; cardinality provides a transaction approximation that is less sensitive to duplicate events. Sorting top_hits by seq rather than by time keeps the last trace stable when several events share a timestamp.

A rule must be a stored, versioned object, otherwise alert history cannot explain why a notification fired. A rule declares its threshold, its for duration, severity, grouping key, and suppression window.

alertRule:
id: rule-error-rate-high
version: 3
status: ACTIVE
metric: error_rate
scope:
interfaceIds: [inventory-sync-v1, catalog-sync-v2]
window: 5m
evaluationInterval: 1m
condition:
operator: GT
threshold: 0.10
minSamples: 20
for: 5m
severity: MAJOR
grouping:
key: [interfaceId, errorClass, target]
suppressionWindow: 30m
notification:
channelRef: ops-primary
repeatInterval: 60m
maintenanceWindows:
- cron: "0 2 * * SUN"
duration: 2h

minSamples prevents a single failure in a low-traffic window from crossing a percentage threshold. for requires the condition to hold across consecutive evaluations, so a one-minute spike does not page anyone. suppressionWindow limits how often the same grouping key can produce a new alert, and repeatInterval controls re-notification while an alert stays open.

Typical windowed conditions in this style include:

  • Error rate stays above 10% for five minutes.
  • Latency p95 exceeds its limit for three consecutive minutes.
  • A guid starts but has no completion for a defined period.
  • Batch write-to-read ratio falls outside the expected range.
  • Parser failures or log-drop count increases sharply.

Never record credentials or recipient addresses in the rule source or in logs; channelRef should resolve to a delivery target through platform configuration.

The evaluator passes aggregation bucket results to an Alert API. The request contains rule information and a bucket list keyed by the grouping key.

{
"alert": {
"ruleId": "rule-error-rate-high",
"ruleVersion": 3,
"groupKey": "inventory-sync-v1|TRANSIENT|order-service",
"window": "5m",
"windowStart": "2024-03-18T04:15:00Z"
},
"buckets": [
{
"key": "inventory-sync-v1|TRANSIENT|order-service",
"docCount": 8,
"errorCount": 2,
"observedValue": 0.25,
"threshold": 0.10,
"lastTrace": {
"guid": "g-demo-7f2c",
"uuid": "u-demo-0004",
"seq": 4,
"statusCode": "E500"
}
}
]
}

Store ruleId, rule version, interfaceId, groupKey, observed value, threshold, detectedAt, lastTrace, and delivery status in history. To avoid creating a record on every polling cycle for the same rule and group, use (ruleId, groupKey, windowStart) as the idempotency key. For stateful rules, also store OPEN, ACKNOWLEDGED, RESOLVED, and REPLAY_REQUESTED transitions.

The lastTrace block is the only place a guid appears. It exists so an operator can open one representative trace, and it must not influence deduplication.

Spring Batch records status, start/end time, read count, write count, and skip count in JobExecution and StepExecution. A common listener can emit structured START, RUNNING, COMPLETED, and FAILED events with guid, uuid, hop, seq, and interfaceId, making batch searchable in the same trace view.

A large chunk readCount with a small writeCount may indicate missing business data. Show skipCount and retry count together, and distinguish step failure from whole-job failure. A restart creates a new execution ID, but should retain the original business guid and parent relationship.

A dashboard API returns aggregated summary, per-interface statistics, and hourly trends. A Trace API returns paginated source events for one guid and may pretty-print JSON or XML error messages. An alert-history API returns evaluation evidence and notification state.

Designing an OpenSearch Trace Query API with Aggregations continues with the concrete terms, top_hits, bucket_sort, and bucket_selector combinations for list and detail queries and safe pagination across many buckets. Building an Interface Error Pipeline from Bucket Monitor to Notification turns this article’s grouping and deduplication rules into a lookback window, alert-payload parsing, history persistence, and decoupled notification delivery.

Copying the same OpenSearch query into all three APIs causes filter, timezone, and status semantics to drift. Reuse common query builders and aggregation names, but keep purpose-specific response DTOs. Store timestamps consistently and apply the user’s timezone only at presentation; enforce page size and maximum date range on the server.

Closing an Alert and reprocessing the business work are different actions. Alert history carries states such as OPEN, ACKNOWLEDGED, RESOLVED, and REPLAY_REQUESTED, and replay is an explicit separate operation.

Check the following before replay.

  1. Confirm whether the original request already produced a side effect.
  2. Confirm the target’s idempotency key or duplicate-detection method.
  3. Confirm whether the original payload can be reused as is.
  4. Give the replayed execution a new uuid and an incremented attempt.
  5. Keep the original guid so the relationship between the original and the replay stays traceable.
  • An Error Event is a recorded fact; an Alert is an operational signal.
  • Grouping and suppression are what make alert volume operable.
  • The grouping key decides how many alerts exist; the dedup key decides how many rows are stored. They are not the same key, and neither contains a guid.
  • Every metric needs a formula, a window, a target index, and an aggregation; the error-rate denominator must exclude in-flight guid values.
  • An alert rule must be a versioned object with threshold, for duration, severity, grouping key, and suppression window.
  • Trace aggregation stays separate from detail payloads, and bucket count and retention cost are managed together.
  • Replay is modeled as a new execution, not as an alert state change.

With the same trace envelope, Spring Batch and API operations can be managed as one Integration observability model rather than two unrelated dashboards, and growing log volume is turned into signals an operator can actually judge. Designing OpenSearch Cluster Monitoring and Incident Response separately covers search-infrastructure signals and incident runbooks for cluster health, node pressure, and unassigned shards.