High-Throughput Event Ingestion in ASP.NET Core Using Bounded Channels
How to decouple HTTP intake from database persistence, apply explicit backpressure with Channel<T>, batch writes in a BackgroundService, and keep hot-path watchlist checks sub-second.
When an HTTP endpoint writes synchronously to a relational database, image store, and downstream alert pipeline inside the request lifecycle, throughput collapses the moment one dependency slows down. Even a brief 400ms database lock spike backs up Kestrel request threads, exhausts connection pools, and turns temporary congestion into cascading 503 failures for edge clients.
In real-time telemetry and ANPR-style ingestion workloads, the pattern that repeatedly holds up under pressure is decoupling intake from persistence using an in-memory BoundedChannel<T>, paired with batched background consumers and a separate sub-second hot path.
Why Unbounded Queues Fail in Production
A common mistake when moving work off the request thread is registering a Channel.CreateUnbounded<T>() (or pushing fire-and-forget tasks onto Task.Run). If downstream storage stalls for 90 seconds while edge nodes push 3,000 events/sec, an unbounded queue silently buffers hundreds of thousands of payloads until the container hits its Kubernetes memory limit and gets OOMKilled — losing every buffered event.
BoundedChannelOptions makes capacity explicit and forces you to choose a backpressure policy up front:
using System.Threading.Channels;
public sealed record VehicleDetectionEvent(
string EventId,
string CameraNodeId,
string PlateNumber,
DateTimeOffset CapturedAtUtc,
byte[] ThumbnailPayload);
public static class IngestionChannelSetup
{
public static IServiceCollection AddIngestionPipeline(this IServiceCollection services)
{
services.AddSingleton(_ => Channel.CreateBounded<VehicleDetectionEvent>(
new BoundedChannelOptions(capacity: 10_000)
{
FullMode = BoundedChannelFullMode.Wait,
SingleReader = false,
SingleWriter = false,
AllowSynchronousContinuations = false,
}));
services.AddHostedService<DetectionBatchProcessor>();
return services;
}
}
Choosing FullMode Intentionally
BoundedChannelFullMode.Wait: SuspendsWriteAsyncasynchronously (without blocking an OS thread) when the channel hits capacity. Combined with a shortCancellationTokentimeout (250ms), the endpoint can fail fast with503 Service Unavailableand aRetry-Afterheader so edge nodes buffer locally on disk instead of crashing your pod.BoundedChannelFullMode.DropOldest: Useful only for replaceable telemetry snapshots (e.g., periodic GPS heartbeats), never for auditable enforcement or financial events.AllowSynchronousContinuations = false: Prevents the consumer continuation from hijacking the Kestrel request thread when completing writes.
Separating the Hot Path from Persistence
In enforcement or alerting pipelines, watchlist matching cannot wait behind a bulk database insert. Before enqueuing the heavy payload for persistence, evaluate the hot path against an in-memory or Redis-backed cache inside a tight timeout:
app.MapPost("/api/v1/detections", async (
DetectionRequest request,
IWatchlistMatcher matcher,
Channel<VehicleDetectionEvent> channel,
CancellationToken ct) =>
{
// 1. Sub-second hot path: evaluate against cached watchlist
var match = await matcher.CheckAsync(request.PlateNumber, ct);
if (match.IsFlagged)
{
// Trigger low-latency alert dispatch without waiting for cold storage
await matcher.PublishAlertAsync(request, match, ct);
}
var evt = new VehicleDetectionEvent(
request.EventId,
request.CameraNodeId,
request.PlateNumber,
request.CapturedAtUtc,
request.ThumbnailBytes);
// 2. Bounded enqueue with explicit backpressure timeout
using var enqueueCts = CancellationTokenSource.CreateLinkedTokenSource(ct);
enqueueCts.CancelAfter(TimeSpan.FromMilliseconds(250));
try
{
await channel.Writer.WriteAsync(evt, enqueueCts.Token);
return Results.Accepted();
}
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
{
return Results.StatusCode(StatusCodes.Status503ServiceUnavailable);
}
});
Notice what happens under surge load: Kestrel never blocks threads waiting on SQL Server or object storage, valid requests return 202 Accepted in single-digit milliseconds, and if capacity saturates, clients get an honest 503 backpressure signal while pod memory stays flat.
Batched Background Consumers with Graceful Drain
Writing 200 events in one batch cuts round-trip overhead dramatically compared to 200 individual inserts. Just as important is graceful shutdown draining: when Kubernetes sends SIGTERM during a rolling deployment, your worker must finish draining already-accepted events before the pod exits.
public sealed class DetectionBatchProcessor(
Channel<VehicleDetectionEvent> channel,
IServiceScopeFactory scopeFactory,
ILogger<DetectionBatchProcessor> logger) : BackgroundService
{
private const int MaxBatchSize = 200;
private static readonly TimeSpan MaxFlushWait = TimeSpan.FromMilliseconds(500);
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
var batch = new List<VehicleDetectionEvent>(MaxBatchSize);
while (await channel.Reader.WaitToReadAsync(stoppingToken).ConfigureAwait(false))
{
var deadline = DateTime.UtcNow.Add(MaxFlushWait);
while (batch.Count < MaxBatchSize && DateTime.UtcNow < deadline)
{
if (channel.Reader.TryRead(out var item))
{
batch.Add(item);
}
else
{
await Task.Delay(15, stoppingToken).ConfigureAwait(false);
}
}
if (batch.Count > 0)
{
await FlushBatchAsync(batch, CancellationToken.None).ConfigureAwait(false);
batch.Clear();
}
}
}
public override async Task StopAsync(CancellationToken cancellationToken)
{
// Stop accepting new HTTP writes, then drain remaining buffered items
channel.Writer.TryComplete();
var remaining = new List<VehicleDetectionEvent>();
while (channel.Reader.TryRead(out var item))
{
remaining.Add(item);
if (remaining.Count >= MaxBatchSize)
{
await FlushBatchAsync(remaining, cancellationToken).ConfigureAwait(false);
remaining.Clear();
}
}
if (remaining.Count > 0)
{
await FlushBatchAsync(remaining, cancellationToken).ConfigureAwait(false);
}
await base.StopAsync(cancellationToken).ConfigureAwait(false);
}
private async Task FlushBatchAsync(List<VehicleDetectionEvent> batch, CancellationToken ct)
{
try
{
using var scope = scopeFactory.CreateScope();
var repository = scope.ServiceProvider.GetRequiredService<IDetectionRepository>();
await repository.BulkUpsertAsync(batch, ct).ConfigureAwait(false);
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to persist batch of {Count} detection events", batch.Count);
// Push failed batch to durable dead-letter storage or retry queue
}
}
}
Operational Checklist Before Shipping
- Idempotency at the consumer: Because edge devices retry on
503or connection drops,BulkUpsertAsyncshould deduplicate on(CameraNodeId, EventId)at the database boundary. - Match
terminationGracePeriodSecondsin Kubernetes: Set pod termination grace period (e.g.45s) higher than your worst-case drain flush time, and keepHostOptions.ShutdownTimeoutaligned. - Export queue depth metrics: Expose
channel.Reader.Countvia OpenTelemetryObservableGaugeso you can alert when depth stays above 70% capacity.
Channel<T> won’t replace a durable distributed broker like Kafka or RabbitMQ when you need cross-service replay, but inside a single ingestion service it eliminates entire classes of thread-pool starvation and memory leaks with zero external moving parts.