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.
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
- Queues give at-least-once delivery. Make handlers idempotent by recording processed message ids.
- A dead-letter queue holds messages that keep failing so they do not block the rest; alert on it.
- Queue (one consumer per message) versus topic (every subscriber gets a copy): order confirmation email is a queue job, "order placed" for many services is a topic.
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.