Covers point-to-point queues versus publish/subscribe topics and subscriptions, the competing consumers pattern, the kinds of decoupling a broker gives (time, location, load) and when synchronous HTTP is still the right choice.
A queue is point-to-point: a producer sends a message and exactly one consumer processes it. A topic is publish/subscribe: each subscription gets its own copy, so billing, email and analytics can all react to one OrderPlaced event.
The trade-off: you lose the immediate answer. If the caller needs the result to continue, a direct HTTP call is simpler.
"A queue is point-to-point. A producer puts a message on the queue and exactly one consumer takes it, processes it and settles it. If I run five instances of the consumer on the same queue, the broker spreads messages across them; that is the competing consumers pattern, and it is how I scale a worker out or survive one instance crashing. A topic is publish/subscribe. The producer publishes once, and every subscription on the topic gets its own copy, so the billing service, the email service and the analytics service each process
OrderPlacedindependently, at their own pace, and each can have competing consumers of its own.In .NET with Azure Service Bus that maps to
ServiceBusSendersending to a queue or topic, and aServiceBusProcessorreading from a queue or fromtopic/subscriptions/name. Why bother? Because the broker decouples the services three ways: in time, since the consumer can be down for a deploy and the messages wait; in location, because the producer doesn't know or care who listens; and in load, because a spike of 10,000 orders queues up instead of knocking over the email service. The guarantee is normally at-least-once, so I always say up front that a consumer may see the same message twice and must be idempotent.The mistake I see is putting everything on a broker. If the checkout page needs to know whether the card was accepted before it can show the next screen, a message doesn't help; you've just built slow, hard-to-debug RPC. I use commands on queues when one service owns the work, events on topics when many might care, and plain HTTP when the caller genuinely needs the answer now."
| Queue | Topic + subscriptions | |
|---|---|---|
| Model | Point-to-point | Publish/subscribe |
| Who gets a message | One consumer | One copy per subscription |
| Typical message | Command: ChargeCard, SendInvoice |
Event: OrderPlaced, CustomerMoved |
| Adding a new reader | Changes the meaning (they compete) | Add a subscription, producer unchanged |
| Service Bus | Queue | Topic, subscriptions, SQL/correlation filters |
| RabbitMQ | Queue bound to the default exchange | Fanout or topic exchange bound to many queues |
| Kafka | (No queue; a topic with one consumer group behaves like one) | Topic, each consumer group reads all partitions |
Producer --> [ queue: m1 m2 m3 m4 m5 ] --> worker A (m1, m4)
--> worker B (m2, m5)
--> worker C (m3)
| Kind | Meaning | Example |
|---|---|---|
| Time | Consumer need not be running when the producer sends | Email service deploys for 5 minutes, nothing is lost |
| Location | Producer has no address for the consumer | New fraud service subscribes without touching Ordering |
| Load | Queue buffers bursts | Black Friday spike drains over 20 minutes |
What you don't get: decoupling from the message contract. Change the shape of OrderPlaced carelessly and every subscriber breaks.
| Use messaging | Use a direct call |
|---|---|
| Work can happen later (email, invoice PDF) | Caller needs the result to continue |
| Many services react to one fact | A query: "what is this customer's credit limit?" |
| Smoothing spikes, retrying for hours | Sub-100 ms user-facing interaction |
An order API that sent confirmation emails over SMTP inside the request had a p95 of 1.8 s and failed checkouts whenever the mail provider was slow. Moving the email to an OrderPlaced topic subscription cut checkout p95 to about 250 ms, and a 40-minute mail outage simply left about 6,000 messages queued, which drained in under 3 minutes once it recovered.
Checks the candidate understands the two basic messaging models and what decoupling a broker really buys.
Green flags
Red flags
A broker is a durable store with delivery rules. Service Bus and RabbitMQ are queue brokers: a message is removed once a consumer settles it. Kafka is a log: messages stay for the retention period and each consumer group tracks its own position (offset). Both can give you queue-like and pub/sub-like behaviour, but the mechanics differ.
Queue broker (Service Bus) Log (Kafka)
[m1][m2][m3] -> receive -> delete [m1][m2][m3][m4]... (kept 7 days)
^ group A offset
^ group B offset
In Service Bus, a topic is a front door; each subscription behaves like its own queue with its own lock, delivery count and dead-letter sub-queue. A filter (SQL or correlation) decides which messages each subscription keeps.
Ordering --publish--> topic: orders
|-- sub: billing (filter: all) -> Billing workers
|-- sub: email (filter: all) -> Email worker
|-- sub: highvalue (Total > 1000) -> Fraud worker
If the email worker is down, only the email subscription grows; billing is unaffected. That isolation is a big part of why topics beat calling three services in a row.
With peek-lock (the default), the broker hands the message to a consumer and locks it for a period (Service Bus default 30 s, max 5 min, renewable). The consumer must complete it. If it crashes, or takes too long without renewing, the lock expires and another consumer gets it.
Broker Worker A DB
|--m1 (lock)-->| |
| |--- INSERT invoice ------->| (commits)
| X crash before Complete |
| lock expires |
|--m1 again--> Worker B --- INSERT ------->| duplicate!
That is at-least-once delivery. The fix is on the consumer side: an idempotent operation or a dedup record (the inbox pattern). There is also receive-and-delete mode, which removes the message as it is handed out; a crash then loses it, which is at-most-once.
ServiceBusProcessor with MaxConcurrentCalls = 10 runs up to 10 handlers at once in one process; three pods give 30 concurrent handlers. On Kafka the parallelism is capped by the number of partitions: a consumer group with more members than partitions leaves some idle.
IssueRefund). One logical owner. Send to a queue. The sender expects it to happen.RefundIssued). Past tense, many listeners, the publisher doesn't care who reacts. Publish to a topic.Mixing them up (publishing a command to a topic) leads to two services both issuing the refund.
Diagnostic-Id/traceparent so Application Insights stitches spans together).Environment.FailFast) and watch the message come back with DeliveryCount = 2.A minimal publisher and competing consumer with Azure.Messaging.ServiceBus. Run the consumer twice to see messages shared between instances.
// Program.cs (publisher)
using System.Text.Json;
using Azure.Identity;
using Azure.Messaging.ServiceBus;
await using var client = new ServiceBusClient(
"my-namespace.servicebus.windows.net", new DefaultAzureCredential());
// Event: past tense, goes to a topic so any number of services can subscribe.
ServiceBusSender topic = client.CreateSender("orders");
var evt = new OrderPlaced(Guid.NewGuid(), "CUST-42", 129.95m);
await topic.SendMessageAsync(new ServiceBusMessage(JsonSerializer.SerializeToUtf8Bytes(evt))
{
MessageId = evt.OrderId.ToString(), // stable id: enables broker duplicate detection and consumer dedup
Subject = nameof(OrderPlaced),
ContentType = "application/json"
});
public sealed record OrderPlaced(Guid OrderId, string CustomerId, decimal Total);
// Program.cs (email worker: one subscription, competing consumers across pods)
using System.Text.Json;
using Azure.Identity;
using Azure.Messaging.ServiceBus;
await using var client = new ServiceBusClient(
"my-namespace.servicebus.windows.net", new DefaultAzureCredential());
await using ServiceBusProcessor processor = client.CreateProcessor(
topicName: "orders", subscriptionName: "email",
new ServiceBusProcessorOptions { MaxConcurrentCalls = 4, AutoCompleteMessages = false });
processor.ProcessMessageAsync += async args =>
{
var evt = args.Message.Body.ToObjectFromJson<OrderPlaced>()!;
// At-least-once: this may be a redelivery, so the send must be idempotent (keyed on OrderId).
Console.WriteLine($"[{Environment.ProcessId}] email for {evt.OrderId} (delivery {args.Message.DeliveryCount})");
await args.CompleteMessageAsync(args.Message, args.CancellationToken);
};
processor.ProcessErrorAsync += args =>
{
Console.Error.WriteLine($"{args.ErrorSource}: {args.Exception.Message}");
return Task.CompletedTask;
};
await processor.StartProcessingAsync();
Console.ReadLine();
await processor.StopProcessingAsync();
public sealed record OrderPlaced(Guid OrderId, string CustomerId, decimal Total);
Messaging is a trade: you buy resilience and independent scaling, and you pay with eventual consistency, duplicates and harder debugging. The senior move is being explicit about which interactions deserve that trade. Notifications, document generation, cross-service reactions to business events: yes. Validations and queries the user is waiting for: no. And the one sentence every interviewer wants to hear is "delivery is at-least-once, so the consumer is idempotent".
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Queue | One owner must do the work, load levelling | Duplicates, no order with competing consumers | Many independent reactions to one fact |
| Topic | Many services react to an event | Contract coupling, per-subscription DLQs to watch | Exactly one service should act |
| HTTP / gRPC | Caller needs the answer now | Temporal coupling, cascading failure | Slow or retry-heavy work |
Measure it: queue depth, oldest message age and end-to-end latency (enqueued time to completion) tell you whether consumers keep up.
An operation is idempotent if doing it once or many times leaves the system in the same state. It's the core tool because distributed systems produce duplicates all the time: clients retry after timeouts, brokers deliver at least once, users double-click. You get it in two ways. Some operations are naturally idempotent: 'set status to Shipped', a PUT of the full resource, an upsert by a natural key. The rest need deduplication: the caller sends a unique idempotency key (or the broker supplies a message id), and the service records it under a unique constraint in the same transaction as the business change, so a repeat is detected and answered with the stored result. The trade-off is storage and a little complexity, against duplicate charges, orders and emails.
The dual-write problem: an order is saved in SQL Server and an OrderPlaced event is sent to Service Bus. Those are two systems with no shared transaction. If the publish fails after the commit, the event is lost. If you publish first and the commit fails, consumers act on an order that doesn't exist.
The outbox fixes this by writing the event as a row in an OutboxMessages table in the same EF Core transaction as the order. A relay (a BackgroundService polling with UPDLOCK, READPAST) publishes unprocessed rows and marks them ProcessedAt.
A crash between publish and mark means the row is sent again, so delivery is at-least-once. Consumers must be idempotent (an inbox), helped by setting MessageId to the outbox id for Service Bus duplicate detection. The trade-off is guaranteed publication against extra writes, latency, cleanup and a relay to monitor.
Partial failure means part of a distributed system fails while the rest keeps running, and no single node can see the whole picture. The sharpest example is a timeout: when your call to the payments service times out, the request might have been lost, the service might have crashed before or after charging the card, the response might have been lost, or it might still be running. A timeout means the outcome is unknown, not that it failed. So calling code must be written for the unknown: make the operation idempotent (or send an idempotency key) so a retry can't do the work twice, or look up the outcome by a client-generated id before retrying, and run reconciliation for anything left in doubt. The trade-off is extra design work on every write that crosses the network.
Last updated 23 Nov 2026.