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

📚 Interview question

How do Azure Service Bus, RabbitMQ, Apache Kafka and Amazon SQS differ? Compare their messaging models, ordering, retention and replay, delivery guarantees and operating cost, and tell me how you would choose one for a new .NET system.

Compares queue brokers (Azure Service Bus, RabbitMQ, Amazon SQS) with Kafka's partitioned log on model, ordering, retention and replay, delivery guarantees, throughput and operations, and gives a decision approach for .NET teams.

Intermediate Theory Intermediate amazon-sqs azure-service-bus distributed-systems kafka messaging rabbitmq

🎯 Key points

  • Service Bus, RabbitMQ and SQS are queue brokers: messages are deleted once settled
  • Kafka is a partitioned, retained log: consumers track offsets and can replay
  • Ordering: Service Bus sessions, SQS FIFO message groups, Kafka per partition, RabbitMQ per queue with one consumer
  • All four are at-least-once in practice for consumers that settle after processing; consumers must deduplicate
  • Service Bus: managed, sessions, duplicate detection (window up to 7 days), DLQ, transactions, Australia East
  • Self-hosted Kafka is costly to operate; managed options (Confluent Cloud, Event Hubs' Kafka endpoint) cut ops but Event Hubs lacks some Kafka features (e.g. limited retention tiers, no full broker configuration)
  • Security: Entra ID / IAM auth, TLS in transit, encryption at rest, private endpoints for all managed options
  • Choose by need: commands and workflows vs event streaming and replay, cloud, throughput, team skills and cost

⏱ 30-second answer

Service Bus, RabbitMQ and SQS are queue brokers: a message is delivered, settled and gone. Kafka is a partitioned, retained log: messages stay for the retention period and each consumer group tracks an offset, so you can replay.

  • Ordering: Service Bus sessions, SQS FIFO message groups, Kafka per partition; RabbitMQ only per queue with a single consumer.
  • Guarantees: all are at-least-once in practice, so consumers deduplicate.
  • Operations: Service Bus and SQS are fully managed; RabbitMQ and self-hosted Kafka need a team (or Confluent Cloud / Event Hubs' Kafka endpoint).

For a .NET system on Azure doing commands and business events, I default to Service Bus. I pick Kafka when I need high-volume streaming and replay. The trade-off is features and simplicity versus throughput and history.

🗣 Full answer (senior)

How I would answer this in an interview

"I split them into two families. Service Bus, RabbitMQ and SQS are queue brokers: the broker hands a message to a consumer, the consumer settles it, and it is deleted. They are built for work distribution and business messaging, with features like dead-letter queues, delayed delivery and per-message locks. Kafka is a distributed, partitioned log: producers append to partitions, messages are retained for days or forever, and each consumer group just remembers an offset. That makes Kafka great for high-volume event streams, replaying history into a new read model, or feeding analytics, but it pushes more work to the consumer: there is no per-message dead-letter queue, and parallelism is capped by partition count.

Within the brokers: Service Bus is the managed Azure option, with sessions for ordered processing, duplicate detection on Standard and Premium, transactions, scheduled messages and a native DLQ; Premium gives dedicated capacity and private endpoints in Australia East. SQS is the AWS equivalent but simpler: standard queues are at-least-once with best-effort order; FIFO queues order by message group and deduplicate over five minutes. RabbitMQ is open source and very flexible in routing through exchanges, but you run it, or pay for a hosted service. Whatever I pick, I assume at-least-once delivery and make consumers idempotent.

For example, at [company] we [chose Service Bus for order and payment commands and Event Hubs with the Kafka protocol for clickstream telemetry], because [the business messages needed sessions and dead-lettering while the telemetry needed about 50,000 events per second and seven days of replay]. The mistake I see is picking Kafka because it is fashionable, then rebuilding retries, dead-lettering and delayed delivery by hand."


Side-by-side (as of late 2026)

Azure Service Bus RabbitMQ Apache Kafka Amazon SQS
Model Queues, topics/subscriptions Exchanges routing to queues Partitioned append-only log Queues (standard, FIFO)
After consumption Deleted on complete Deleted on ack Retained (time/size or compacted) Deleted on DeleteMessage
Replay No (only DLQ resubmit) No (streams feature aside) Yes, reset offsets No
Ordering Per session Per queue, single consumer Per partition FIFO per message group
Broker dedup Duplicate detection, window up to 7 days No Idempotent producer (per session) FIFO: 5-minute dedup interval
DLQ Built in per queue/subscription Dead-letter exchange None built in (you build a DLQ topic) Redrive policy to a DLQ
Throughput Premium scales by messaging units Tens of thousands msg/s per node Very high, scales by partitions Standard: nearly unlimited; FIFO: 300 TPS per partition, high-throughput mode far higher
Operations Fully managed Self-host or hosted Self-host, Confluent Cloud, or Event Hubs Kafka endpoint Fully managed
.NET client Azure.Messaging.ServiceBus RabbitMQ.Client 7 (async API) Confluent.Kafka (librdkafka) AWSSDK.SQS

How I choose

Need Lean towards
Commands, business events, sagas on Azure Service Bus (Standard; Premium for isolation, VNet, large messages)
Same on AWS SQS + SNS (or EventBridge)
Complex routing, on-premises or multi-cloud, low cost RabbitMQ
High-volume streams, replay, many independent readers, event sourcing-style history Kafka (or Event Hubs with the Kafka protocol on Azure)
Need both Often both: a broker for workflows, a log for streams

Also weigh: team skills, data residency (Australia East/Southeast for Privacy Act obligations), and whether you want a library such as MassTransit (v9 is commercially licensed; v8 stays Apache 2.0) or NServiceBus over the raw SDKs.

Production example

A team that used Kafka for order commands spent weeks building retry topics, delay handling and a DLQ consumer, and still lost a day when one poison message blocked a partition. Moving those commands to Service Bus with MaxDeliveryCount = 10 and native dead-lettering removed about 1,200 lines of plumbing; Kafka stayed for the 30,000-events-per-second telemetry stream where replay mattered.

🔍 What the interviewer is checking

Checks the candidate understands the broker-versus-log distinction and can match a platform to requirements rather than to fashion.

Green flags

  • Explains Kafka as a retained, partitioned log with offsets and replay
  • Knows how each platform scopes ordering (sessions, message groups, partitions)
  • Says all are at-least-once and consumers must deduplicate
  • Mentions operations, cost and licensing

Red flags

  • Claims one platform gives exactly-once end to end
  • Picks Kafka for everything or cannot say why
  • Unaware that messages are deleted after consumption on brokers

📚 Learn in depth

1. Two families: broker versus log

Queue broker                        Partitioned log (Kafka)
producer -> [queue] -> consumer     producer -> partition 0: [0][1][2][3][4]...
            delete on settle                    partition 1: [0][1][2]...
                                    group A reads at offsets (4, 2)
                                    group B reads at offsets (1, 0)  (independent)

In a broker the server tracks per-message state (locked, delivery count, dead-lettered). In a log the server tracks almost nothing per message; the consumer group tracks one offset per partition. That is why Kafka is cheap per message and fast, and why per-message features (delay, DLQ, individual retry) are absent.

2. Ordering mechanics

  • Service Bus sessions: messages with the same SessionId are locked to one receiver at a time, processed in order. Different sessions run in parallel.
  • SQS FIFO: MessageGroupId plays the same role; within a group messages are delivered in order, one in flight at a time.
  • Kafka: the partition is chosen by hashing the key; order holds within a partition. Change the partition count and keys map to new partitions, which breaks order for in-flight keys.
  • RabbitMQ: a queue is FIFO, but with several consumers and prefetch, processing order is lost; requeues also reorder.

3. Delivery guarantees

All four default to at-least-once for a consumer that settles after processing. "Exactly-once" claims are narrow: Kafka transactions give exactly-once within Kafka (read-process-write to Kafka topics); Service Bus duplicate detection drops resends with the same MessageId inside the window. Neither covers your database write plus an email.

4. Retention and replay

Kafka keeps data by time (retention.ms, often 7 days), size, or log compaction (latest value per key, forever). A new service can start at offset 0 and build its state. Brokers can't do this: once settled, a message is gone, so a new subscriber only sees future messages.

5. Cost and operations

  • Service Bus Standard: pay per operation; Premium: per messaging unit per hour, predictable latency, private endpoints, messages up to 100 MB.
  • SQS: pay per request (batching up to 10 messages cuts cost tenfold).
  • Kafka: brokers, storage, (KRaft controllers replace ZooKeeper in Kafka 4.x), partition planning, upgrades. Managed options trade money for that work.
  • RabbitMQ: quorum queues for durability across nodes; classic mirrored queues are removed in RabbitMQ 4.

6. Abstractions

MassTransit and NServiceBus hide transport differences and add retries, outbox, sagas. Check licences: NServiceBus is commercial; MassTransit v9 (released 2026) requires a commercial licence, while v8 remains Apache 2.0 with maintenance through 2026. Wolverine and Rebus are open-source alternatives. An abstraction doesn't remove semantic differences: you can't get Kafka replay from Service Bus by swapping transports.

Try it yourself

  1. Run RabbitMQ, Kafka (single KRaft node) and the Service Bus emulator in Docker Compose.
  2. Publish 10,000 messages to each from a .NET console app and measure throughput with Stopwatch.
  3. On Kafka, start a second consumer group from offset 0 and watch it replay everything; try the same on Service Bus and note it can't.
  4. Send messages with three keys to a 3-partition Kafka topic and log partition and order per key.
  5. Send the same MessageId twice to a Service Bus queue with duplicate detection on, and confirm only one arrives.

💻 Code

The same "publish an event" in two clients, showing where ordering keys and dedup ids go.

// Azure Service Bus: SessionId gives per-customer order, MessageId enables duplicate detection.
using Azure.Identity;
using Azure.Messaging.ServiceBus;

await using var sb = new ServiceBusClient("my-ns.servicebus.windows.net", new DefaultAzureCredential());
ServiceBusSender sender = sb.CreateSender("orders");

var order = new OrderPlaced(Guid.NewGuid(), "CUST-42", 129.95m);
await sender.SendMessageAsync(new ServiceBusMessage(BinaryData.FromObjectAsJson(order))
{
    MessageId = order.OrderId.ToString(),
    SessionId = order.CustomerId,          // only needed if the entity requires sessions
    Subject = nameof(OrderPlaced)
});

public sealed record OrderPlaced(Guid OrderId, string CustomerId, decimal Total);
// Kafka with Confluent.Kafka: the key picks the partition, so order holds per customer.
using System.Text.Json;
using Confluent.Kafka;

var config = new ProducerConfig
{
    BootstrapServers = "localhost:9092",
    EnableIdempotence = true,   // no duplicates from producer retries (within Kafka only)
    Acks = Acks.All
};
using var producer = new ProducerBuilder<string, string>(config).Build();

var order = new OrderPlaced(Guid.NewGuid(), "CUST-42", 129.95m);
DeliveryResult<string, string> result = await producer.ProduceAsync("orders",
    new Message<string, string> { Key = order.CustomerId, Value = JsonSerializer.Serialize(order) });

Console.WriteLine($"partition {result.Partition.Value}, offset {result.Offset.Value}");

public sealed record OrderPlaced(Guid OrderId, string CustomerId, decimal Total);

⚠ Common mistakes

  • Mistake: Choosing Kafka for task queues because it is popular. Why it is wrong: you lose per-message retry, delay and dead-lettering and must build them yourself. Instead: use a broker for commands and workflows, Kafka for streams and replay.
  • Mistake: Assuming RabbitMQ or SQS standard preserve order. Why it is wrong: multiple consumers, prefetch and requeues reorder; SQS standard is best-effort ordering. Instead: use FIFO queues, sessions or partition keys where order matters.
  • Mistake: Believing broker deduplication makes processing exactly-once. Why it is wrong: it only drops resends inside a window; redelivery after a crash still happens. Instead: make consumers idempotent.
  • Mistake: Over-partitioning or under-partitioning Kafka topics. Why it is wrong: too few caps parallelism; changing it later remaps keys and breaks order. Instead: size partitions for peak consumer parallelism up front.
  • Mistake: Ignoring data residency. Why it is wrong: personal information may leave Australia, raising Privacy Act (APP 8) obligations. Instead: deploy the namespace or cluster in Australia East/Southeast.
  • Mistake: Adopting MassTransit v9 without checking the licence. Why it is wrong: v9 needs a paid licence for commercial use. Instead: budget for it, stay on v8 with a plan, or choose an open-source alternative.

🏛 Senior insight: trade-offs

The real question is not which product is best but what kind of messaging you are doing. Business workflows (commands, sagas with compensation, retries with backoff, dead-lettering, scheduled messages) suit a broker, because those patterns need per-message state. Streams (telemetry, change data capture, event histories many teams read at their own pace, projections rebuilt by replay) suit a log. Many mature systems run both, and that is fine as long as each has a clear purpose. Resilience patterns such as circuit breakers around the downstream call and bulkheads (separate consumers per dependency) apply to both.

Option When it fits Cost When not to
Service Bus Azure, business messaging, sessions, DLQ Per-op (Standard) or per-messaging-unit (Premium) pricing, 256 KB on Standard Replay or 100k+ msg/s streams
RabbitMQ Routing flexibility, on-prem, low cost You operate it (quorum queues, upgrades) No ops capacity
Kafka (self-hosted) Streams, replay, many readers, high volume Ops heavy, partition planning, no native DLQ Simple task queues
Event Hubs (Kafka endpoint) Kafka clients on Azure without running brokers Throughput-unit pricing, retention limits by tier, not every Kafka feature Need full Kafka control or features like arbitrary compaction settings
SQS (+SNS) AWS, simple managed queues FIFO limits, 256 KB messages Need replay or rich routing

Measure before deciding: peak messages per second, message size, needed retention, ordering scope and latency target (p99 enqueue-to-handle). Load-test the shortlisted option with your real message size; those numbers usually make the choice obvious.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate says all platforms are at-least-once Why: Checks they can implement an idempotent consumer, not just name it
    How to answer

    With at-least-once delivery, duplicates are normal: outbox resends, peek-lock redelivery after a crash or lock expiry, and publisher retries. An idempotent consumer makes processing a message twice have the same effect as once.

    The inbox is an InboxMessages table with a primary key on (MessageId, Consumer). For each message, in one EF Core transaction:

    1. Insert the inbox row first.
    2. Apply the business change.
    3. Commit, then complete the Service Bus message.

    If the insert fails with SQL error 2627/2601, the message was already processed, so complete it. A concurrent duplicate blocks on the key lock until the first commits, then fails the insert. If the first rolls back, the duplicate goes ahead.

    Purge old rows past the redelivery window. The trade-off is an extra write and table per consumer against correct exactly-once processing.

  2. When: Candidate mentions Kafka retention and replaying old messages Why: Checks they know old and new event versions must coexist
    How to answer

    Make changes additive where possible, so one schema serves both. When a breaking change is unavoidable, give the event a version (in the type name or a schemaVersion field), have consumers accept both (or upcast old to new on read) before producers switch, and keep old-version support until no old messages remain in queues, dead-letter queues or replayable logs. A schema registry with BACKWARD or FULL compatibility can enforce this at publish time.

  3. When: Candidate recommends Service Bus for business workflows Why: Checks they can coordinate multi-step workflows over messaging
    How to answer

    A saga replaces a distributed transaction with a sequence of local transactions, one per service, coordinated by messages. Each step has a compensating action that semantically undoes it: release the stock, refund the payment. Compensation isn't a rollback, because other parties may already have seen or acted on the intermediate state.

    • Choreography: services react to each other's events. It's simple for two or three steps, but the flow is implicit.
    • Orchestration: a state machine (such as a MassTransit saga) sends commands, persists its state per correlation id, and handles failures. The flow is explicit and observable.

    Design points: put the irreversible step last, make every step idempotent, add scheduled timeouts, and handle late replies (payment succeeds after a timeout cancelled the order, so refund it). The trade-off is availability and autonomy against eventual consistency and more complex failure handling.

↩ Usually asked after

More in Messaging

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me