An event pipeline is observable when an operator can determine not only that a job is alive, but also what is late, where it is late, whether records are being lost, and which version of code, schema, and infrastructure produced the effect. Broker metrics alone cannot answer those questions. A complete design joins infrastructure, framework, application, data-quality, and business signals at stable boundaries.

The objective is to shorten time to detect, time to explain, and time to recover without turning every process metric into a page. Start with a small number of service-level objectives (SLOs), then retain enough supporting telemetry to diagnose violations.

Metric taxonomy architecture for observable streaming pipelines

Define the observable contract

For a business event stream, define the contract before selecting dashboards:

  • an event has an immutable event ID, event time, ingest time, schema version, and source;
  • one or more accepted source topics or subscriptions exist;
  • outputs have known partitions, idempotency keys, and ownership;
  • late, malformed, duplicate, and unprocessable records have explicit routes;
  • the team defines freshness and completeness targets for each data product.

For example, an order-enrichment service might promise:

  • 99.9 percent of accepted events emit a valid output within 60 seconds;
  • no more than 0.01 percent fail permanently in a 30-minute window;
  • consumer lag stays below five minutes during normal broker operation;
  • a replay can reconstruct a named output partition from retained input plus versioned code and configuration.

Avoid an SLO that says “the Spark or Flink job is running.” Liveness can remain green while input is delayed, a checkpoint is stale, a sink is throttled, or every event goes to a dead-letter topic.

Use the four golden signals carefully

The familiar four golden signals map to pipelines, but each needs a pipeline-specific meaning:

Signal Streaming interpretation Example SLI
Traffic Work accepted by the system input records/bytes per second by topic and partition
Errors Work rejected, retried, or made invalid permanent failures per accepted event
Saturation Capacity or concurrency pressure hot-partition fraction, backpressure, worker utilization
Latency Freshness from event source to committed sink p99 sink_commit_time - event_time

Add two signals that are unusually important for data products:

  • Completeness: expected records or logical keys versus observed records;
  • Correctness: schema, invariant, reconciliation, and anomaly checks.

Do not divide total lag by current throughput to estimate recovery time when traffic is changing or keys are skewed. A lag-time estimate is useful for queues, but only a replay test proves actual recovery capacity.

Build a metric taxonomy

Metric names should describe the measured boundary, not the implementation that happened to expose it:

pipeline_input_records_total{pipeline,source,stage,environment}
pipeline_output_records_total{pipeline,sink,stage,environment}
pipeline_invalid_records_total{pipeline,rule,schema,stage}
pipeline_dlq_records_total{pipeline,reason,stage}
pipeline_event_age_seconds{pipeline,source,sink,quantile}
pipeline_checkpoint_age_seconds{pipeline}
pipeline_sink_commit_duration_seconds{pipeline,sink}
pipeline_reconcile_difference{pipeline,dataset,metric}

Keep label cardinality bounded. topic, job, sink, schema_major, and environment are usually useful. Raw trace_id, event_id, Kafka offset, user ID, order ID, partition GUID, and stack-trace text are not metric labels. Put high-cardinality identifiers in logs or exemplars.

Attach durable ownership labels such as pipeline_id and team, but derive release and infrastructure labels from controlled deployment metadata. A CI pipeline should emit the image digest, not an unbounded branch name, into job metadata.

Kafka metrics

At the broker and cluster layer, collect:

  • active controller count and controller changes;
  • under-replicated, offline, and leaderless partitions;
  • request queue time, request processing time, and network processor utilization;
  • bytes and messages in/out;
  • disk used, disk I/O saturation, and log segment removal;
  • min.insync.replicas and authentication/authorization failures;
  • consumer-group current offset, log-end offset, and consume rate.

Consumer offset is not enough for a data-product SLO because one fast consumer group can mask a slow downstream sink. Store both Kafka lag and end-to-end event age.

For a self-managed or Strimzi Kafka deployment, JMX Exporter configuration can expose the required subjects:

lowercaseOutputName: true
lowercaseOutputLabelNames: true
rules:
  - pattern: kafka.server<type=ReplicaManager, name=UnderReplicatedPartitions><>Value
    name: kafka_under_replicated_partitions
  - pattern: kafka.server<type=ReplicaManager, name=OfflinePartitionsCount><>Value
    name: kafka_offline_partitions
  - pattern: kafka.controller<type=KafkaController, name=ActiveControllerCount><>Value
    name: kafka_active_controller_count
  - pattern: kafka.server<type=BrokerTopicMetrics, name=BytesInPerSec><>Count
    name: kafka_bytes_in_total

Amazon MSK emits broker, topic, and consumer-group signals through JMX and CloudWatch depending on the monitoring level and deployment mode. GCP Pub/Sub is not Kafka, but the equivalent design compares num_undelivered_messages, oldest unacked message age, pull request latency, and publish errors rather than assuming Kafka terminology.

Framework metrics

Apache Spark Structured Streaming

Use the structured-streaming progress metrics for batch duration, source rate, processed rate, input rows, output rows, state store size, and streaming offsets. Mirror key values as Prometheus metrics or scrape them from a sidecar if the Spark distribution supports metric sinks.

Important conditions include:

  • numInputRows / batchDurationMs falling below arrival rate;
  • batch duration exceeding the trigger interval;
  • state rows or state memory growing beyond the expected key horizon;
  • skipped or repeatedly retried batches;
  • executor loss or spill that coincides with batch-duration growth.

Spark’s “batch” is an internal checkpointing and processing unit; end-to-end freshness must still include event time and sink commit behavior.

Collect job, operator, task, and checkpoint metrics:

  • job uptime and number of full restarts;
  • records in/out and exceptions by operator;
  • busy time, backpressure status, and buffer-pool usage;
  • checkpoint alignment and end-to-end duration;
  • checkpoint age and last successful checkpoint;
  • state bytes, state size by operator, and RocksDB compaction pressure;
  • Kafka committed versus current partition offsets.

Checkpoint duration should be evaluated relative to interval and recovery latency. A checkpoint that succeeds every ten minutes may still violate a two-minute recovery objective.

Apache Beam

Metric names are runner-specific. Measure:

  • transform element counters and distribution metrics;
  • per-transform failures and dropped or dead-lettered elements;
  • system and data watermark lag;
  • backlog bytes and source oldest message age;
  • Dataflow worker CPU, memory, disk, and autoscaling decisions;
  • state and timer sizes where the SDK or runner exposes them.

Beam’s portable model does not guarantee that equivalent metric names are exported by Dataflow, Flink Runner, and Spark Runner. Normalize only documented metrics in the common telemetry layer and retain runner-native metrics for incident response.

On Google Cloud, Dataflow emits job metrics into Cloud Monitoring. On AWS, Managed Service for Apache Flink exposes application status and operator-level metrics through CloudWatch. When using Beam on self-managed infrastructure, collect runner-level telemetry from the underlying Flink or Spark deployment.

PromQL examples

Alert on sustained symptoms and multi-window error-budget burn rather than one-point spikes. A generic permanent-error ratio is:

sum(rate(pipeline_invalid_records_total[5m]))
  /
clamp_min(sum(rate(pipeline_input_records_total[5m])), 1)

Detect freshness violations:

histogram_quantile(
  0.99,
  sum by (le, pipeline) (
    rate(pipeline_event_age_seconds_bucket[5m])
  )
) > 60

Detect a Kafka consumer that is falling behind despite recent processing:

(
  max by (pipeline) (kafka_consumer_lag_records) > 50000
)
and
(
  rate(kafka_consumer_committed_offset_total[10m]) <
  rate(kafka_partition_high_watermark_total[10m]) * 0.95
)

If the exporter exposes offsets as gauges, do not wrap a counter reset incorrectly. Name exported values by their actual type. The second query is illustrative; validate counter versus gauge semantics for the Kafka exporter in use.

CloudWatch and Cloud Monitoring queries

CloudWatch Logs Insights is useful for extracting structured error causes and DLQ counts:

fields @timestamp, pipeline, jobVersion, failureClass, message
| filter eventType = "dead_letter"
| stats count(*) as rejected by failureClass, bin(15m)
| sort @timestamp desc

A CloudWatch metric-math alarm can combine Kafka lag and Flink checkpoint age, but keep the actions separate. Escalate lag only when checkpoints are healthy; a stale checkpoint plus lag suggests a stateful recovery problem, not a harmless capacity scale-up.

For GCP Cloud Monitoring, an MQL-style aggregation can summarize Dataflow backlog age per job:

fetch dataflow_job
| metric 'dataflow.googleapis.com/job/system_lag'
| group_by 5m, [value_system_lag_mean: mean(value.system_lag)]
| every 5m

Metric identifiers and availability change across runner versions and Dataflow job types. Discover and verify the exact metric in the target project’s Metrics Explorer before checking in an alert definition.

Structured logs and tracing

Emit one-line structured JSON at application boundaries:

{
  "time": "2023-09-22T14:31:08.512Z",
  "level": "warn",
  "service": "order-enricher",
  "pipeline_id": "orders-v3",
  "job_version": "sha256:8a1f...",
  "event_id": "01HAY...",
  "event_time": "2023-09-22T14:30:52.001Z",
  "source": "orders",
  "partition": 17,
  "offset": 9918021,
  "trace_id": "6f7...",
  "span": "sink.write",
  "attempt": 3,
  "outcome": "dead_letter",
  "reason": "SCHEMA_VALIDATION"
}

Never log payloads, credentials, tokens, or complete personal data by default. Hash or sample identifiers where operational debugging requires correlation.

OpenTelemetry tracing is practical for request-like pipeline portions, but a Kafka record can spend hours in storage and pass through a stateful window. Propagate trace context in event headers when the security and message-size budgets permit, and treat lineage or source metadata as the durable correlation record. A trace link should help diagnose one record; it is not a substitute for aggregate pipeline SLOs.

Lineage and context

Every emitted partition should be attributable to:

  • source topics/subscriptions and offset ranges;
  • pipeline and container image versions;
  • configuration or schema version;
  • dependency models or feature versions;
  • checkpoint/savepoint or streaming query checkpoint;
  • sink table, partition, commit, and manifest.

Export this metadata to the lineage system or data catalog in an out-of-band write. If the output commit succeeds but lineage publication fails, decide whether the job retries lineage, quarantines the output, or marks it incomplete. Do not silently claim a complete lineage graph.

Data quality and dead-letter handling

A quality check must distinguish temporary outage from invalid data. Dead-letter every record with:

{
  "original_topic": "orders-v3",
  "partition": 17,
  "offset": 9918021,
  "event_id": "01HAY...",
  "schema_id": "orders.event:42",
  "failure_class": "CONTRACT",
  "error_code": "AMOUNT_NEGATIVE",
  "first_seen": "2023-09-22T14:30:53Z",
  "attempts": 1,
  "pipeline_version": "sha256:8a1f...",
  "replay_eligible": false
}

Keep the original payload encrypted and access-controlled if it must be replayed. A poison message can create unbounded retries and suppress the whole partition. Retry transient sink or network faults with bounded exponential backoff; route deterministic contract failures immediately.

DLQ volume itself is not the only quality metric. Alert on:

  • rate and ratio by reason code;
  • oldest DLQ message age;
  • replay success and recurrence rate;
  • schema compatibility failures by producer;
  • reconciliation differences by time bucket and key domain.

Build dashboards by question

Use a small set of role-oriented dashboards:

  1. Product health: freshness, completeness, errors, DLQ ratio, and last successful reconciliation.
  2. Processing: input/output rates, lag, backpressure, batch/checkpoint health, and sink commit latency.
  3. Capacity: CPU, memory, disk, network, partition skew, worker churn, and state size.
  4. Kafka: controller, ISR/offline partitions, broker storage, request latency, and group offsets.
  5. Release: old/new version overlap, schema mix, checkpoint restore, and result parity.
  6. Cost: bytes processed, compute hours, state size, storage tiers, and unallocated resources.

Link alerts to the exact view and runbook. A screenshot or a dashboard with hundreds of graphs is not an incident procedure.

Incident walkthrough: output freshness rises

Suppose p99 event age increases from 20 seconds to four minutes.

  1. Protect correctness: inspect sink commit errors and DLQ ratio. Do not scale blindly if records are being rejected.
  2. Locate the boundary: compare Kafka log-end and committed offsets, worker backlog, operator backpressure, output rate, and sink latency.
  3. Separate lag from age: rising lag with flat age may indicate burst catch-up that is keeping up with event time; old event age with flat lag can indicate a hot partition or replay.
  4. Inspect state and checkpoints: Flink checkpoint duration and state growth, Spark state-store maintenance, or Beam watermark and state size may reveal a long key horizon.
  5. Check the sink: throttling, connection pooling, lock contention, and regional endpoint failure can backpressure the framework.
  6. Mitigate narrowly: pause low-priority producers, increase only safe parallelism, partition/compact the sink, or switch to a documented drain and replay route.
  7. Verify recovery: confirm both lag and event-age SLOs recover and no gap exists at the output-reconciliation boundary.
  8. Close the loop: retain a timeline, root cause, impacted event range, replay proof, and a telemetry gap ticket.

Alert pages should identify an owner and include the first three diagnostic links. If the page only says “Flink CPU high,” operators still need to rediscover which data product is affected.

Retention and cost

Metrics, logs, traces, and lineage have different retention needs. Keep high-resolution metrics for a short period and downsample long-term trends. Retain structured DLQ and incident logs for the replay/audit window. Sample successful traces while retaining all failed or slow traces when the volume is controllable.

Protect observability pipelines from the production pipeline they observe. A logging volume spike should not take down the data plane. Apply local buffering, bounded retry, independent quotas, and graceful sampling. Conversely, sampling all errors can hide a single poison record that explains the incident, so retain aggregates plus a small set of representative examples.

Production checklist

  • Business freshness and correctness SLOs exist for every critical output.
  • Metrics use a bounded taxonomy with labels documented and tested.
  • Kafka, runner, state, sink, schema, and cloud-service signals are present.
  • Dashboards expose event-time and commit-time latency, not only process uptime.
  • Deterministic failures route to a DLQ with replay metadata.
  • Logs correlate event, source offset, job version, and trace without leaking sensitive data.
  • Lineage identifies source ranges and code/configuration for output partitions.
  • Alerts include multi-window thresholds, ownership, and a tested runbook.
  • Observability data has volume limits and does not share a failure domain with processing.

Observability is complete when an operator can explain an SLO breach across Kafka, processing, state, and sink with evidence. It is not complete when the only dashboard says that several pods are alive.