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

📚 Interview question

How do you keep messages in order in a distributed system? Explain Azure Service Bus sessions, Kafka partition keys and SQS FIFO message groups, what breaks ordering (competing consumers, retries, dead-lettering, repartitioning), and how you design so you don't need global ordering at all.

Covers why ordering is expensive, per-key ordering with Service Bus sessions, Kafka partitions and SQS FIFO message groups, what breaks order (parallel consumers, retries, DLQ, rebalancing, repartitioning), and design alternatives: commutative updates, version numbers and state-carrying events.

Mid-Level Theory Intermediate azure-service-bus distributed-systems kafka message-ordering messaging sessions

🎯 Key points

  • Global order means one consumer at a time: it kills throughput and availability
  • Order per key (customer, order, account) is what businesses actually need; ask which entity and what breaks if two events swap
  • Service Bus: SessionId on a session-enabled entity + ServiceBusSessionProcessor, MaxConcurrentCallsPerSession = 1
  • Kafka: same key -> same partition; each partition is read by one member of a consumer group, many members read different partitions in parallel; adding partitions remaps keys
  • SQS FIFO: MessageGroupId, one in-flight batch per group
  • Order breaks with competing consumers on non-session queues, abandon/retry, dead-lettering, producer retries without idempotence
  • Design around it: version numbers and 'ignore older', state-carrying events, commutative operations
  • Head-of-line blocking: a poison message stalls its whole session or partition, cutting throughput for that key; dead-letter it or park the key deliberately

⏱ 30-second answer

Global ordering means one consumer processing one message at a time, which kills throughput, so real systems guarantee order per key: per order, customer or account.

  • Service Bus: set SessionId; a ServiceBusSessionProcessor locks a session to one receiver and processes it in order, while different sessions run in parallel.
  • Kafka: the message key picks the partition, and order holds within it. Adding partitions remaps keys.
  • SQS FIFO: the MessageGroupId works like a session.

Order breaks with competing consumers, retries, dead-lettering and rebalances. Better still, design so order doesn't matter: version numbers with "ignore older", events that carry full state, or commutative updates. The trade-off is that per-key order lets one stuck message block every later message for that key.

🗣 Full answer (senior)

How I would answer this in an interview

"My first question is: ordered relative to what? Global order across all messages means a single consumer with no parallelism, so nobody really wants that. What businesses need is order per entity: OrderPlaced before OrderShipped for the same order, or debits and credits on one account. Every platform gives you that through a key. In Service Bus I put the order id in SessionId on a session-enabled queue; the ServiceBusSessionProcessor takes a lock on one session at a time per slot, processes its messages in sequence, and other sessions proceed in parallel. In Kafka the producer's key is hashed to a partition, a partition is read by one consumer in the group, and order holds within it. SQS FIFO uses MessageGroupId the same way.

Then I talk about what breaks it. Competing consumers on a non-session queue process messages in parallel, so message two can finish before message one. An abandon or a retry puts message one back behind message two. Dead-lettering removes message one entirely, so the consumer happily applies message two on top of missing state. In Kafka, adding partitions changes the key-to-partition mapping, and a producer without idempotence can reorder on retry.

So I prefer to design ordering out. For example, at [company] the [customer projection] received CustomerUpdated events out of order after a [scale-out], and addresses reverted. We [added a per-customer version number to each event and an UPDATE ... WHERE Version < @version], so older events became no-ops, and we didn't need sessions at all. The mistake I see is turning on sessions everywhere 'to be safe', then discovering one poison message has frozen a busy customer's whole stream."


Ordering scope by platform

Platform Ordering key Unit of parallelism Notes
Azure Service Bus SessionId Session (one lock holder at a time) Entity must be created with sessions enabled
Kafka Message key -> partition Partition (one consumer per group) Partition count caps consumers
SQS FIFO MessageGroupId Message group 300 TPS per partition without high-throughput mode
RabbitMQ Queue Single active consumer Single-active-consumer flag or consistent-hash exchange

What breaks order

Cause Example
Competing consumers without sessions Shipped handled by pod B before Placed finishes on pod A
Retry / abandon m1 fails, m2 succeeds, m1 succeeds on retry
Dead-lettering m1 in DLQ, m2 applied to incomplete state
Repartitioning (Kafka) Key moves to a new partition while old messages still sit in the old one
Producer retries Two sends in flight; first fails, retried after second (fixed by Kafka idempotent producer)
Multiple producers Two services publish about the same entity with no shared sequence

Designing ordering out

Technique How Works when
Version / sequence check Each event carries entity version; apply only if newer Events about one entity from one owner
State-carrying events Event includes full current state, not a delta Consumers just need latest state
Commutative operations Increments that can apply in any order; sets keyed by id Counters, tags
Re-fetch on event Event is a signal; consumer reads current state via API Low volume, owner API available

Production example

A payments ledger used one non-session queue with 16 competing consumers; about 0.2% of refund events arrived before their payment events and failed validation, generating 300 support tickets a month. Moving to sessions keyed by payment id fixed order for each payment while keeping 16-way parallelism across payments, and the tickets dropped to near zero.

🔍 What the interviewer is checking

Checks the candidate knows ordering is per key, how each platform provides it, and when to design it away.

Green flags

  • Rejects global ordering and names a business key
  • Explains sessions, partitions and message groups accurately
  • Lists what breaks order, including retries and repartitioning
  • Offers version checks or state-carrying events as alternatives

Red flags

  • Believes a queue is FIFO regardless of consumers
  • Doesn't consider head-of-line blocking
  • Orders events by wall-clock timestamps across services

📚 Learn in depth

1. Why ordering costs throughput

Order is a property of a single sequence. To preserve it, message n+1 can't be processed until n has finished. So the maximum parallelism equals the number of independent sequences. Choose keys with high cardinality and even distribution.

Global order:    m1 -> m2 -> m3 -> m4 -> m5        (1 worker)
Per-key order:   key A: a1 -> a2 -> a3              worker 1
                 key B: b1 -> b2                    worker 2
                 key C: c1                          worker 3

2. Service Bus sessions

A session-enabled entity requires every message to carry SessionId. A receiver calls accept-session; the broker grants an exclusive session lock. Messages in that session are delivered in enqueue order to that receiver only. ServiceBusSessionProcessor options:

  • MaxConcurrentSessions: how many sessions a process works on at once.
  • MaxConcurrentCallsPerSession: keep at 1 for strict order.
  • SessionIdleTimeout: release a session when no messages arrive, so others can be picked up.

Sessions also hold session state (SetSessionStateAsync), useful for a small per-session workflow.

3. Kafka partitions

The default partitioner hashes the key (murmur2) modulo partition count. A partition is consumed by one member of a group; offsets are committed in order. With EnableIdempotence = true (default in recent Confluent clients), the producer keeps order even with retries and up to 5 in-flight requests. Changing the partition count reassigns keys; plan partitions for future peak and avoid changing them on ordered topics.

4. The head-of-line blocking problem

session "order-42":  [m1 POISON][m2][m3][m4]
                      ^ fails 10 times, blocks m2..m4

Options after MaxDeliveryCount: m1 is dead-lettered and m2 proceeds (order broken but flowing), or you deliberately park the session (stop processing that key, alert, fix, resume). For financial streams, parking is safer; for notification streams, skipping is fine. Make it an explicit decision per stream.

5. Version checks: ordering without ordering

UPDATE CustomerView
SET    Address = @address, Version = @version
WHERE  CustomerId = @id AND Version < @version;
-- 0 rows affected => this event is stale or a duplicate: ignore it

This handles out-of-order and duplicate events with one statement. It needs a single owner assigning monotonically increasing versions (for example the aggregate's row version or an event sequence).

6. Causal order across entities

Sometimes order matters across keys (create customer, then their first order). Options: a consumer that tolerates missing parents (retry later, or create a placeholder); including enough data in the later event; or a saga. Don't widen the session key to the whole customer base.

Try it yourself

  1. Send 1,000 messages for 10 keys to a non-session queue with 8 consumers; log out-of-order arrivals per key.
  2. Repeat with a session-enabled queue and ServiceBusSessionProcessor; confirm zero out-of-order.
  3. Make one message per session fail permanently and observe head-of-line blocking until it dead-letters.
  4. Create a Kafka topic with 3 partitions, produce keyed messages, then add a partition and see which keys move.
  5. Implement the version-check update and replay events in random order; confirm the final state is correct.

💻 Code

Ordered per order id with Service Bus sessions, plus a version guard so a stale or duplicate event is harmless.

// Producer: the session id is the ordering key.
using Azure.Messaging.ServiceBus;

namespace Orders;

public sealed record OrderStatusChanged(Guid OrderId, string Status, long Version);

public sealed class OrderEventsPublisher(ServiceBusSender sender)
{
    public Task PublishAsync(OrderStatusChanged evt, CancellationToken ct) =>
        sender.SendMessageAsync(new ServiceBusMessage(BinaryData.FromObjectAsJson(evt))
        {
            SessionId = evt.OrderId.ToString(),            // all events for one order, in order
            MessageId = $"{evt.OrderId}:{evt.Version}",     // stable id for dedup
            Subject = nameof(OrderStatusChanged)
        }, ct);
}
// Consumer: one session at a time per slot, strictly sequential within a session.
using Azure.Messaging.ServiceBus;
using Microsoft.EntityFrameworkCore;

namespace Tracking;

public sealed class OrderStatusConsumer(ServiceBusClient client, IServiceScopeFactory scopes) : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        await using ServiceBusSessionProcessor processor = client.CreateSessionProcessor(
            "order-status", new ServiceBusSessionProcessorOptions
            {
                MaxConcurrentSessions = 16,           // parallel across orders
                MaxConcurrentCallsPerSession = 1,     // strict order within an order
                AutoCompleteMessages = false,
                SessionIdleTimeout = TimeSpan.FromSeconds(5)
            });

        processor.ProcessMessageAsync += async args =>
        {
            var evt = args.Message.Body.ToObjectFromJson<OrderStatusChanged>()!;
            await using var scope = scopes.CreateAsyncScope();
            var db = scope.ServiceProvider.GetRequiredService<TrackingDbContext>();

            // Defence in depth: even if order slips (DLQ resubmit, replay), older versions are no-ops.
            int rows = await db.OrderViews
                .Where(o => o.OrderId == evt.OrderId && o.Version < evt.Version)
                .ExecuteUpdateAsync(s => s
                    .SetProperty(o => o.Status, evt.Status)
                    .SetProperty(o => o.Version, evt.Version), args.CancellationToken);

            await args.CompleteMessageAsync(args.Message, args.CancellationToken);
        };
        processor.ProcessErrorAsync += _ => Task.CompletedTask;

        await processor.StartProcessingAsync(stoppingToken);
        try { await Task.Delay(Timeout.Infinite, stoppingToken); }
        catch (OperationCanceledException) { }
        await processor.StopProcessingAsync(CancellationToken.None);
    }
}

public sealed record OrderStatusChanged(Guid OrderId, string Status, long Version);

⚠ Common mistakes

  • Mistake: Asking for global ordering. Why it is wrong: it forces a single consumer and makes one slow message stall everything. Instead: order per business key.
  • Mistake: Assuming a FIFO queue keeps order with competing consumers. Why it is wrong: parallel handlers finish out of order. Instead: use sessions, partitions or message groups.
  • Mistake: Choosing a low-cardinality key such as country. Why it is wrong: one hot key becomes a bottleneck and parallelism is tiny. Instead: pick a high-cardinality key such as order or account id.
  • Mistake: Increasing Kafka partitions on an ordered topic in production. Why it is wrong: keys remap and messages for one key are split across partitions mid-stream. Instead: size partitions up front or migrate to a new topic.
  • Mistake: Setting MaxConcurrentCallsPerSession above 1. Why it is wrong: messages in the same session run concurrently and lose order. Instead: keep 1 and scale with MaxConcurrentSessions.
  • Mistake: Ignoring head-of-line blocking. Why it is wrong: a poison message freezes a key and nobody notices. Instead: alert on session age and decide explicitly whether to skip or park.
  • Mistake: Relying on timestamps to order events from different producers. Why it is wrong: clocks skew. Instead: use a version assigned by the owning service.

🏛 Senior insight: trade-offs

Ordering is a requirement to challenge, not to grant. I ask three questions: which entity does the order apply to, what goes wrong if two events swap, and how often does that actually happen? Often the answer is "nothing, if the consumer checks versions", which is cheaper and more robust than any broker feature, and it also handles duplicates and replays. Where strict order is real (a ledger, workflow steps), I accept the architectural cost: parallelism capped by the number of active keys, head-of-line blocking that can freeze a hot key (one stuck session on a busy merchant can hold thousands of messages), and a session-enabled entity that every producer must honour, which is a contract decision you can't toggle later without recreating the queue.

Option When it fits Cost When not to
Sessions / partitions / message groups Strict per-key sequences (ledger, workflow steps) Head-of-line blocking, parallelism capped by keys Consumers only need latest state
Version check in the consumer Single owner assigns versions One column and a conditional update Deltas that must all apply in sequence
State-carrying events Read models, caches Larger messages, possible PII spread Huge aggregates
Re-fetch on event Low volume, owner API reliable Extra load and coupling to the owner High volume or owner often down

Measure out-of-order arrivals (version gaps logged by the consumer) and the age of the oldest message per session; both tell you whether ordering is actually a problem before you pay for it. For cross-entity dependencies (create customer before first order), don't widen the ordering key: let the consumer retry until the parent exists, carry the needed data in the later event, or, where several services must reach a consistent outcome, coordinate with a saga.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions events about one entity arriving out of order Why: Checks they can diagnose an ordering and idempotency incident end to end
    How to answer

    I'd first confirm the mechanics: Azure Service Bus delivers at least once and only orders messages within a session, so after a release that raised consumer concurrency or scaled out, events for the same order can be processed out of order and redelivered. Traces with event ids, aggregate versions and delivery counts prove it.

    The fixes: every event carries the aggregate version and the consumer applies it only if newer (or I use sessions keyed by order id); an inbox with a unique key dedups by message id in the same transaction; increments like loyalty credits use a natural idempotency key (order id plus reason). Unknown event versions dead-letter. Then I rebuild the corrupted state from the source of truth.

    The trade-off: sessions give ordering but limit parallelism per key; version checks keep parallelism but require versioned events.

  2. When: Candidate suggests ordering by timestamp Why: Checks they understand clock skew and logical clocks
    How to answer

    Each machine has its own clock, and clocks drift and skew: a few milliseconds is normal, seconds when sync breaks. Worse, wall clocks can jump, backwards or forwards, when NTP corrects them or a VM is restored. So timestamps from different machines can't reliably tell you which event happened first, and last-writer-wins by timestamp silently discards newer data. For ordering, use something that only goes up: a sequence number from a single writer, a database rowversion, a Kafka offset per partition, or logical clocks (Lamport, vector, hybrid) when nodes write independently. For durations, use a monotonic clock (Stopwatch, TimeProvider.GetTimestamp), never DateTime differences. In .NET, inject TimeProvider so time can be faked in tests. The trade-off: logical clocks give correct order but no human-readable time, so you usually keep both.

  3. When: Candidate compares sessions with Kafka partitions Why: Checks broader knowledge of the platforms' models
    How to 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.

🛠 Real-world problems: how you handle them

Refunds processed before their payments
Situation
A payments ledger service consumes `PaymentCaptured` and `RefundIssued` from a Service Bus queue with [16] competing consumers across [4] pods, about [500,000] events a day for an Australian retailer.
Signals
About 0.2% of refunds fail validation with 'payment not found'; they retry and some dead-letter; support tickets about refunds stuck 'pending'; Application Insights shows refund handled milliseconds before the matching payment on another pod.
Investigation
Joined handler traces by payment id and compared enqueue times with processing times; confirmed the producer enqueued in the right order but parallel consumers and retries reordered them; checked DLQ: all entries were refunds whose payment had arrived later.
Resolution
Immediate: resubmitted dead-lettered refunds after confirming the payments existed. Real fix: recreated the queue with sessions enabled, `SessionId = PaymentId`, and moved to `ServiceBusSessionProcessor` with `MaxConcurrentSessions = 16`; added a per-payment version check as defence in depth.
Prevention
Contract test asserting every ledger message has a `SessionId`; alert on session age > 5 minutes for head-of-line blocking; ADR explaining per-key ordering and the park-the-session policy for poison messages.

How to tell it (STAR)

**S:** Our ledger service [at company] was rejecting some refunds because they were processed before their payments. **T:** I owned fixing ordering without losing throughput. **A:** I traced refunds and payments by payment id and showed that competing consumers and retries reordered them, even though they were enqueued correctly. I moved the queue to sessions keyed by payment id, kept 16 sessions in parallel, and added a version check plus an alert for blocked sessions. **R:** Out-of-order failures dropped from [about 1,000 a day] to zero, support tickets for stuck refunds [fell by around 300 a month], and throughput stayed the same.

↩ Usually asked after

More in Messaging

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me