📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What is the difference between a queue and a topic (publish/subscribe)? Explain competing consumers, why putting a message broker between two services decouples them, and when you would still make a direct HTTP call instead.

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.

Junior Theory Beginner azure-service-bus competing-consumers distributed-systems messaging pub-sub queues

🎯 Key points

  • Queue: each message is processed by exactly one consumer (point-to-point)
  • Topic: each subscription gets its own copy of every matching message (publish/subscribe)
  • Competing consumers: several instances read one queue to share load and survive one instance dying
  • Decoupling in time (consumer can be down), location (no address needed) and load (queue absorbs spikes)
  • Peek-lock / manual-ack consumers get at-least-once delivery; at-most-once only by choosing receive-and-delete or early ack; so handlers must tolerate duplicates
  • Commands go to a queue (one owner); events go to a topic (many interested parties)
  • Schema changes still couple producer and subscribers: version messages, additive changes only
  • Use HTTP or gRPC when the caller needs the answer now to continue (a query, a validation)

⏱ 30-second answer

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.

  • Competing consumers: run several instances on one queue (or one subscription) and the broker hands each message to one of them, so you scale out and survive a crashed instance.
  • A broker decouples services in time (the consumer can be down), location (the producer doesn't know who listens) and load (the queue absorbs spikes).
  • Delivery is normally at-least-once, so consumers must tolerate duplicates.

The trade-off: you lose the immediate answer. If the caller needs the result to continue, a direct HTTP call is simpler.

🗣 Full answer (senior)

How I would answer this in an interview

"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 OrderPlaced independently, at their own pace, and each can have competing consumers of its own.

In .NET with Azure Service Bus that maps to ServiceBusSender sending to a queue or topic, and a ServiceBusProcessor reading from a queue or from topic/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 versus topic

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

Competing consumers

Producer --> [ queue: m1 m2 m3 m4 m5 ] --> worker A (m1, m4)
                                       --> worker B (m2, m5)
                                       --> worker C (m3)
  • Throughput scales with instances, until the downstream (database, API) becomes the limit.
  • Order is no longer guaranteed: m2 may finish before m1. If order matters, use sessions or partitions (a separate topic).
  • If worker B crashes mid-message, its lock expires and the message is redelivered to another worker. That is where duplicates come from.

What decoupling you actually get

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.

When to use HTTP instead

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

Production example

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.

🔍 What the interviewer is checking

Checks the candidate understands the two basic messaging models and what decoupling a broker really buys.

Green flags

  • Clearly separates one-consumer queues from per-subscription copies on a topic
  • Mentions competing consumers and that ordering is lost
  • States at-least-once delivery and idempotent handlers without being asked
  • Knows when not to use messaging

Red flags

  • Thinks messaging guarantees exactly-once processing
  • Uses a queue where several services each need every event
  • Cannot name any downside of asynchronous messaging

📚 Learn in depth

1. What a broker actually stores

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

2. How a topic fans out

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.

3. Peek-lock and why duplicates happen

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.

4. Competing consumers in .NET

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.

5. Commands versus events

  • Command: "do this" (IssueRefund). One logical owner. Send to a queue. The sender expects it to happen.
  • Event: "this happened" (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.

6. The costs you take on

  • Eventual consistency: the email is sent seconds later, maybe minutes.
  • Harder debugging: you need correlation ids and distributed tracing (the Service Bus SDK propagates Diagnostic-Id/traceparent so Application Insights stitches spans together).
  • Operating a broker: dead-letter queues, alerts on queue depth, message size limits (256 KB on Standard, up to 100 MB on Premium).

Try it yourself

  1. Create a Service Bus namespace (or run the Service Bus emulator in Docker) with a queue and a topic with two subscriptions.
  2. Send 100 messages to the queue and run two console consumers; log which instance handled which message and note the ordering.
  3. Publish 100 messages to the topic and confirm each subscription received all 100.
  4. Kill a consumer mid-handler (Environment.FailFast) and watch the message come back with DeliveryCount = 2.
  5. Stop one subscription's consumer for a minute and watch only that subscription's active message count grow in the portal.

💻 Code

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);

⚠ Common mistakes

  • Mistake: Publishing an event to a queue and adding a second service to read it. Why it is wrong: the two services now compete, so each sees only about half the events. Instead: publish events to a topic and give each service its own subscription.
  • Mistake: Assuming each message is processed exactly once. Why it is wrong: lock expiry, crashes and network blips cause redelivery. Instead: make handlers idempotent or record processed message ids.
  • Mistake: Expecting competing consumers to preserve order. Why it is wrong: parallel handlers finish in any order. Instead: use Service Bus sessions or Kafka partition keys only where order truly matters.
  • Mistake: Using a queue for request/response the user is waiting on. Why it is wrong: it adds latency and failure modes without any decoupling benefit. Instead: use HTTP or gRPC for synchronous queries.
  • Mistake: Treating the broker as decoupling the contract. Why it is wrong: every subscriber depends on the message schema. Instead: version messages and only make additive changes.
  • Mistake: Not monitoring queue depth or the dead-letter queue. Why it is wrong: a stopped consumer fails silently while messages pile up. Instead: alert on active and dead-lettered message counts and on the age of the oldest message.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate says consumers must handle duplicate messages Why: Checks they know how to actually make a handler idempotent rather than just naming it
    How to answer

    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.

  2. When: Candidate shows the order being saved and the event being published Why: Checks they see the dual-write problem between the database and the broker
    How to answer

    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.

  3. When: Candidate contrasts messaging with a direct HTTP call Why: Checks they understand partial failure and timeouts on the synchronous path
    How to answer

    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.

↩ Usually asked after

More in Messaging

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me