Message queues: decouple, buffer and retry

Why "place order" should not wait for email, invoices and analytics, and how a queue with retries and a dead-letter queue keeps work safe.

Time O(1) per messageSpace O(m) queuedCode C#
Watch it animatedStep through it, with the running line highlighted. Free with an account.

The idea

A queue sits between the service that creates work and the services that do it. The producer returns as soon as the message is stored. Consumers process at their own pace, retry on failure, and scale independently. Because a message can be delivered more than once, consumers must be idempotent.

Code

// Producer: the API saves the order and publishes an event, then returns at once.
await db.Orders.AddAsync(order); await db.SaveChangesAsync();
await bus.PublishAsync(new OrderPlaced(order.Id));
return Results.Accepted();

// Consumer: runs separately and can scale on its own.
async Task Handle(OrderPlaced e)
{
    if (await _done.ContainsAsync(e.OrderId)) return;
    await _email.SendConfirmation(e.OrderId);
    await _done.AddAsync(e.OrderId);
}
// After 5 failed attempts the broker moves the message to the dead-letter queue.

Tips

In the .NET library

Azure Service Bus offers queues, topics, sessions for ordering, and dead-letter queues built in; MassTransit is a popular .NET library on top of it or RabbitMQ.