Introduction
Event-driven architectures allow applications to process work asynchronously. Instead of performing every operation during an HTTP request, an application can publish an event and let a separate component handle it.
This introduces a different set of operational challenges. An API can return a successful response while the work triggered by that request is still waiting to be processed. A background worker can remain online while repeatedly failing to process events. And even when every component appears healthy, the system can gradually fall behind as incoming work exceeds its processing capacity.
These problems are difficult to detect if monitoring focuses primarily on HTTP endpoints and infrastructure health.
To understand what is happening inside an event-driven system, we need to observe how events move through the application, how long processing takes, and whether the system is making progress.
Identifying the problem
Consider an application that stores events and processes them asynchronously.
When a user performs an operation, the application persists the corresponding event. A background processor subsequently handles that event and updates a read model.
The processing pipeline might look like this:
┌──────────────┐│ API │└──────┬───────┘ │ ▼┌──────────────┐│ Event Store │└──────┬───────┘ │ ▼┌──────────────┐│ Processor │└──────┬───────┘ │ ▼┌──────────────┐│ Read Model │└──────────────┘Suppose the API continues returning successful responses, but the processor starts taking longer to handle events.
Initially, this might not cause any visible errors. However, if events arrive faster than they can be processed, the amount of outstanding work increases. Eventually, users start seeing stale data because the read model cannot keep up with the event stream.
Monitoring the API’s response time would not reveal this problem. Neither would a health check that only verifies whether the processor is running.
We need to measure the behavior of the processing pipeline itself.
Measuring processing progress
The first step is to identify which metrics describe the system’s behavior.
For a background processor, I would start with the following:
| Metric | What it tells us |
|---|---|
| Events received | How much work enters the system |
| Events processed successfully | How much work the system completes |
| Processing duration | How long individual processing attempts take |
| Processing failures | How often processing fails |
| Retry count | How frequently processing needs another attempt |
| Backlog size | How much work remains outstanding |
| Oldest outstanding event age | How long the oldest unfinished work has been waiting |
These metrics complement one another.
For example, consider a processor that receives 100 events per second but processes only 80. Assuming the rates remain stable and no other work is being completed, the backlog grows by approximately 20 events per second.
A backlog measurement reveals the accumulated work, while the difference between incoming and completed throughput helps explain why it is accumulating.
The age of the oldest outstanding event provides another useful perspective. A large backlog is not necessarily problematic if the application can process it within its expected latency requirements. Conversely, even a small backlog can be problematic if one event has been waiting for several minutes.
It is therefore useful to monitor both backlog size and backlog age.
The exact measurements depend on the underlying technology. A message broker might expose queue depth and consumer lag, while an event-sourced application might track projection positions or the age of the last successfully processed event. These metrics are not interchangeable, but they can answer similar operational questions.
Instrumenting event processing in .NET
.NET provides the System.Diagnostics.Metrics API for recording application-specific metrics. These metrics can subsequently be collected by OpenTelemetry and exported to a monitoring backend.
A small instrumentation class could look like this:
using System.Diagnostics.Metrics;
public static class EventProcessingMetrics{ private static readonly Meter Meter = new("CatchIgnore.EventProcessing");
private static readonly Counter<long> Processed = Meter.CreateCounter<long>( "app.events.processed");
private static readonly Histogram<double> Duration = Meter.CreateHistogram<double>( "app.events.processing.duration", unit: "s");
public static void RecordProcessed( string handler, string outcome, double durationSeconds) { var tags = new TagList { { "handler", handler }, { "outcome", outcome } };
Processed.Add(1, tags); Duration.Record(durationSeconds, tags); }}The counter records the number of processing attempts, while the histogram records their duration. Both measurements are tagged with the handler and outcome, allowing us to distinguish between different processing components.
For example, the same application might have several handlers, each with different performance characteristics. By recording the handler name, we can identify whether a slowdown affects the entire application or a single part of the processing pipeline.
There are a few details worth considering when implementing this in a real application.
First, the instrumentation must be called at the appropriate point in the processing lifecycle. A failed attempt should be recorded as a failure even if a subsequent retry succeeds.
Second, the meaning of the counter should be explicit. Counting processing attempts is different from counting unique events completed successfully. If both measurements are needed, they should be recorded separately.
Finally, metric tags should have a limited number of possible values. Handler names and a small set of outcomes are generally suitable. Event IDs and correlation IDs are not, because they can produce a large number of distinct time series.
Those identifiers are better suited to structured logs and distributed traces.
Integrating OpenTelemetry
The custom meter can be registered with OpenTelemetry so that its measurements are collected alongside other application metrics.
For example:
using OpenTelemetry.Metrics;
builder.Services .AddOpenTelemetry() .WithMetrics(metrics => { metrics .AddMeter("CatchIgnore.EventProcessing") .AddAspNetCoreInstrumentation() .AddHttpClientInstrumentation(); });This configures metric instrumentation. Exporting the measurements requires an appropriate exporter or OpenTelemetry Collector configuration, depending on the monitoring infrastructure.
Automatic instrumentation provides useful information about HTTP requests and supported dependencies. However, it cannot determine whether a business operation has completed successfully or whether a projection is falling behind. Those measurements require application-specific instrumentation.
This distinction is important: infrastructure and framework metrics describe how components behave, while domain-specific metrics describe whether the application is accomplishing its work.
Distinguishing slow processing from delayed processing
Processing duration alone does not tell us how long an event takes to move through the entire system.
Consider two scenarios.
In the first scenario, an event starts processing immediately but takes five seconds to complete. In the second, the event waits for five minutes before a handler processes it in a few milliseconds.
Both scenarios could have acceptable handler execution times, but the second introduces significant processing latency.
To distinguish between them, we need to measure at least two different durations:
- Processing duration: the time between starting and completing a processing attempt.
- Processing delay: the time between an event becoming eligible for processing and processing actually starting.
Where an end-to-end processing objective exists, we can also measure the time between event creation and completion.
The distinction helps narrow down the cause of a problem. High processing duration suggests that handlers or their dependencies may be slow. Increasing processing delay suggests that the system is not starting work quickly enough, potentially because of insufficient capacity, scheduling delays, or a growing backlog.
Percentiles such as p95 and p99 are useful when examining processing duration. An average can hide a small number of unusually slow operations, while percentiles reveal more about the distribution.
The metrics should still be interpreted in context. A high p99 might indicate an important problem, or it might reflect an expected long-running operation. The relevant thresholds depend on the application’s requirements.
Using logs and traces to investigate failures
Metrics help identify that something is wrong, but they rarely provide enough information to explain why.
Suppose the failure rate of one handler increases. We can use structured logs to identify the exceptions being thrown and distributed traces to determine whether the handler is spending most of its time in application code, a database, or an external dependency.
A structured log entry might contain fields such as:
{ "eventType": "SubscriptionUpdated", "handler": "UpdateSubscriptionProjection", "eventId": "evt-example-123", "correlationId": "corr-example-456", "attempt": 2, "outcome": "Failed"}These values are illustrative. The important point is that the fields should be consistent across the processing pipeline.
An event ID allows us to locate the processing history of an individual event. A correlation ID can help connect related operations across components. The handler name makes it easier to identify where a failure occurred.
Logs should not replace metrics. Recording every successful operation and querying the resulting logs to calculate throughput can be unnecessarily expensive at high volumes. Metrics are better suited to aggregate measurements, while logs provide details about individual operations and failures.
Distributed tracing adds another dimension by showing how an operation moves through multiple components.
In an asynchronous system, however, the relationship between operations is not always a simple parent-child relationship. An HTTP request might finish long before its corresponding event is processed. Trace context should therefore be propagated through messages where possible, with span links used when appropriate for asynchronous relationships.
OpenTelemetry provides instrumentation and propagation mechanisms that can help implement this without tying the application to a particular observability backend.
Turning metrics into actionable alerts
Collecting metrics is only useful if we can recognize when they indicate a problem.
A dashboard showing a backlog of 10,000 events does not automatically tell us whether intervention is necessary. The acceptable backlog depends on the arrival rate, processing capacity, and the time within which events are expected to be handled.
Instead of alerting on arbitrary metric values, we should define operational expectations.
For example, if a projection is expected to process events within a minute, an alert could be triggered when the oldest outstanding event exceeds that limit for a sustained period.
Other useful alert conditions include:
- Processing failures exceed an expected threshold.
- The backlog continues growing instead of returning to normal.
- No processing progress is observed while work is expected.
- Events repeatedly fail and enter a dead-letter mechanism.
The thresholds and evaluation periods should be based on the application’s requirements rather than copied from another system.
It is also important to distinguish between a temporary spike and a persistent problem. A short increase in backlog might be expected during a burst of traffic, whereas a backlog that continues growing for several minutes could indicate that the processor cannot keep up with demand.
An alert should provide enough context to start an investigation. For example, it should identify the affected handler or queue, the condition that triggered the alert, and a link to the relevant dashboard or runbook.
Without that context, alerts can generate noise without helping engineers resolve the underlying problem.
Applying this to event-sourced applications
Event sourcing introduces additional questions because the event stream is the source of truth, while read models may be updated asynchronously.
For example, a projection can fall behind even when new events are being persisted successfully. From the perspective of the command-handling API, everything might appear healthy, but queries against the read model can return stale data.
In this case, I would monitor the projection’s processing position, the amount of outstanding work, and the age of the last successfully processed event.
Projection failures should also be visible. If a projection repeatedly fails on the same event, simply restarting the processor might not resolve the issue. The system needs enough diagnostic information to identify the failure and determine whether the event can be processed safely after the underlying problem has been corrected.
Replay duration is another useful measurement. If a projection needs to be rebuilt, knowing how quickly it can process historical events helps estimate recovery time and plan operational changes.
These measurements are specific to event-sourced applications, but the underlying principle remains the same: monitoring should describe whether the system is making progress toward its intended outcome.
Conclusion
Observability for event-driven systems requires more than checking whether services are running.
We need to understand how much work enters the system, how quickly it is completed, how long events wait, and where failures occur. Metrics provide an overview of processing behavior, while logs and traces help investigate individual problems.
In .NET, OpenTelemetry and System.Diagnostics.Metrics provide a foundation for collecting this information. The application still needs to expose the measurements that matter for its specific processing model.
I would start with a small set of metrics covering throughput, processing duration, failures, and backlog age. From there, I would build dashboards around operational questions and add alerts for conditions that require intervention.
The result should be a system where a growing backlog or stalled processor is detected before it becomes a larger operational problem, and where engineers have enough information to understand what happened without having to reconstruct the entire processing pipeline from scratch.