Oswaldo Gonzalez

Batch messages before you add servers: Dapr in C#

When message volume grows, the easy answer is more servers. Some of that capacity may be going to moving messages one at a time. Batching gets more from what you already pay for, as long as you handle partial failures properly.

Illustration: single messages making separate trips compared with one batch
Batching carries many messages on one trip.

The business case

Batching lets the same systems handle more volume, which can put off spending on more infrastructure. The risk is quiet data loss: a batch that mostly succeeds can hide a few lost orders. Done properly, every message is accounted for. The rest of this post shows how, in Dapr and C#.

Jump to: the implementation / questions for your team

Every message that goes through Dapr makes a trip from your app to the sidecar, and from there to the broker. At 50 messages a second you'll never notice. At 5,000, your service spends its time on those trips and your CPU graph has nothing to do with the work you actually care about.

Dapr has bulk APIs for both directions. The Dapr part is easy. The part that deserves your attention is the failure handling, because a batch doesn't fail the way a single message does.

Publishing in bulk

The .NET client gives you BulkPublishEventAsync. You hand it a list and get back the entries that failed.

var result = await dapr.BulkPublishEventAsync(
    "pubsub", "orders", orders, cancellationToken: ct);

foreach (var failed in result.FailedEntries)
{
    logger.LogWarning(
        "Publish failed: {Error}", failed.ErrorMessage);
    await retryQueue.AddAsync(failed.Entry.EventData, ct);
}

Read that response every time. The call can return normally with failures inside it, so await finishing doesn't mean your orders were published. A try/catch around this call catches some problems and misses the one that matters most.

Retrying only FailedEntries matters too. If you resend the whole list, every message that already got through goes out twice.

Subscribing in bulk

On the receiving side, Dapr collects messages and delivers them to your handler together. Two numbers control it: how many messages make a batch, and how long to wait for them.

[Topic("pubsub", "orders")]
[BulkSubscribe("orders", 500, 1000)]
[HttpPost("orders")]
public async Task<ActionResult<BulkSubscribeAppResponse>>
    HandleOrders(
        [FromBody] BulkSubscribeMessage<Order> batch,
        CancellationToken ct)
{
    var responses = new List<BulkSubscribeAppResponseEntry>();

    foreach (var entry in batch.Entries)
    {
        var status = await ProcessAsync(entry.Event, ct);
        responses.Add(new BulkSubscribeAppResponseEntry(
            entry.EntryId, status));
    }

    return Ok(new BulkSubscribeAppResponse(responses));
}

private async Task<BulkSubscribeAppResponseStatus> ProcessAsync(
    Order order, CancellationToken ct)
{
    try
    {
        await orders.SaveAsync(order, ct);
        return BulkSubscribeAppResponseStatus.SUCCESS;
    }
    catch (InvalidOrderException)
    {
        return BulkSubscribeAppResponseStatus.DROP;
    }
    catch (Exception ex)
        when (ex is TimeoutException or HttpRequestException)
    {
        return BulkSubscribeAppResponseStatus.RETRY;
    }
}

In the attribute, 500 is maxMessagesCount and 1000 is maxAwaitDurationMs. Dapr delivers when it reaches 500 messages or after one second, whichever comes first.

So 1,000 ms is also the delay you've just added to a quiet system. If your traffic drops overnight, messages can sit for that long waiting for a batch that never fills. Pick the wait based on the latency you can live with, then raise the count until throughput stops improving.

That loop runs one message at a time to keep the example readable. You'll get more out of a batch by saving the whole thing in one database call, or by running entries concurrently with a limit. Without one of those, you've batched the transport and left the slow part alone.

3 of 500 failed. Now what?

This is why the response has one status per entry. Return one status for the whole batch and you get two bad options: retry 497 good messages, or lose 3 messages. Per-entry status gets you out of that.

A grid of 500 messages with 497 successes, 2 marked retry and 1 marked drop
Each entry gets its own status, so only the failures are retried.

The sorting is where teams get it wrong. Mark a bad message RETRY and it comes back forever, burning capacity. Mark a timeout DROP and you've quietly lost an order. Default unknown exceptions to RETRY only if retries are capped, and set a dead-letter topic so a message that runs out of attempts lands somewhere a person can look at it. Dropped messages should at least be logged, because DROP means gone.

Things to check before you ship

Load test with failures turned on. Make 1% of messages fail and confirm that exactly those come back, exactly the right number of times. A batching setup that has only seen success hasn't been tested.

Questions to ask your team

If those answers are fuzzy, your system may be losing work without telling you. I help teams find that out before their customers do. Send me a message on LinkedIn with what yours does, and we can work out where to look first.