Separating Integration Alerting and Metrics
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.
Identifiers used in this article
Section titled “Identifiers used in this article”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.
| Concept | Question | Stored or delivered to |
|---|---|---|
| Error Event | Which step failed, and with what? | Trace / event index |
| Alert | Does an operator need to act now? | Alert history, notification |
| Incident | Are several Alerts one outage? | Incident management |
| Metric | How 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.
The observability and alerting flow
Section titled “The observability and alerting flow”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.
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.
Error classification and suppression
Section titled “Error classification and suppression”Operational policy is built on reprocessability and blast radius rather than on exception class names.
| Class | Example | Notification policy |
|---|---|---|
| Transient | connection timeout, temporary 5xx, rate limit | Alert only after backoff retry exceeds a threshold |
| Contract | schema mismatch, missing required field | No retry; alert the contract owner |
| Business | business rule violation, duplicate request | Route to a business channel, separate from technical alerts |
| Platform | consumer stopped, search cluster failure | Group and escalate by blast radius |
Grouping key and dedup key
Section titled “Grouping key and dedup key”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 + timeWindowThe 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.
Metric definitions
Section titled “Metric definitions”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.
| Metric | Definition formula | Window | Target index | Example aggregation |
|---|---|---|---|---|
| total count | cardinality(guid) over completed exchanges | 1m bucket, 15m view | trace index | cardinality on guid |
| error count | cardinality(guid where eventType = ERR) | 1m bucket, 15m view | trace index | filter + cardinality |
| error rate | error count / total count | 5m rolling | trace index | bucket_script over the two above |
| latency p50 / p95 | percentile of max(time) - min(time) per guid | 5m rolling | trace index | percentiles on a bucket_script duration |
| TPM | cardinality(guid) averaged per minute bucket | 1m bucket, 60m view | trace index | date_histogram + avg_bucket |
| in-flight count | guid with a start event and no end event | evaluated at query time | trace index | bucket_selector on missing end |
| incomplete count | guid missing either start or end after the grace period | 15m | trace index | bucket_selector after now-15m |
| replay backlog | rows remaining in quarantine or dead letter | current value | dispatch / quarantine store | count by state |
| last execution | last statusCode and time per interfaceId | current value | trace index | terms on interfaceId + top_hits size 1 |
| batch read/write/skip | Spring Batch step execution counters | per execution | batch result store | sum 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.
Aggregation boundaries and cost
Section titled “Aggregation boundaries and cost”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.
OpenSearch aggregation design
Section titled “OpenSearch aggregation design”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.
Alert rule definition
Section titled “Alert rule definition”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: 2hminSamples 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
guidstarts 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.
Alert API input and idempotency
Section titled “Alert API input and idempotency”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.
Put batch statistics into the same model
Section titled “Put batch statistics into the same model”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.
Dashboard and history API boundaries
Section titled “Dashboard and history API boundaries”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.
Operator replay flow
Section titled “Operator replay flow”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.
- Confirm whether the original request already produced a side effect.
- Confirm the target’s idempotency key or duplicate-detection method.
- Confirm whether the original payload can be reused as is.
- Give the replayed execution a new
uuidand an incrementedattempt. - Keep the original
guidso the relationship between the original and the replay stays traceable.
Summary
Section titled “Summary”- 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
guidvalues. - An alert rule must be a versioned object with threshold,
forduration, 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.