dotnet-cqrs/docs/observability/health-checks/stream-health.md

75 lines
2.1 KiB
Markdown

# Stream Health
Monitor event stream availability and health status.
## Overview
Stream health monitoring detects issues with event streams:
- Stream availability
- Write/read performance
- Error rates
- Stream growth rate
## Implementation
```csharp
public interface IStreamHealthService
{
Task<StreamHealthResult> CheckStreamHealthAsync(string streamName, CancellationToken ct = default);
Task<StreamHealthSummary> CheckAllStreamsAsync(CancellationToken ct = default);
}
public class StreamHealthService : IStreamHealthService
{
private readonly IEventStreamStore _eventStore;
private readonly ILogger<StreamHealthService> _logger;
public async Task<StreamHealthResult> CheckStreamHealthAsync(
string streamName,
CancellationToken ct)
{
var result = new StreamHealthResult { StreamName = streamName };
try
{
// Check stream exists and is accessible
var streamHead = await _eventStore.GetStreamHeadAsync(streamName, ct);
result.IsAccessible = true;
result.CurrentOffset = streamHead;
// Check error rate
var errorRate = await GetErrorRateAsync(streamName, ct);
result.ErrorRate = errorRate;
// Determine health status
result.Status = errorRate switch
{
> 10 => HealthStatus.Unhealthy,
> 5 => HealthStatus.Degraded,
_ => HealthStatus.Healthy
};
result.Message = $"Stream healthy (offset: {streamHead}, error rate: {errorRate}/min)";
}
catch (StreamNotFoundException)
{
result.Status = HealthStatus.Unhealthy;
result.Message = "Stream not found";
}
catch (Exception ex)
{
result.Status = HealthStatus.Unhealthy;
result.Message = $"Stream check failed: {ex.Message}";
_logger.LogError(ex, "Error checking stream health for {StreamName}", streamName);
}
return result;
}
}
```
## See Also
- [Health Checks Overview](README.md)
- [Consumer Health](consumer-health.md)