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.
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.
SessionId; a ServiceBusSessionProcessor locks a session to one receiver and processes it in order, while different sessions run in parallel.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.
"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:
OrderPlacedbeforeOrderShippedfor 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 inSessionIdon a session-enabled queue; theServiceBusSessionProcessortakes 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 usesMessageGroupIdthe 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
CustomerUpdatedevents out of order after a [scale-out], and addresses reverted. We [added a per-customer version number to each event and anUPDATE ... 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."
| 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 |
| 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 |
| 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 |
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.
Checks the candidate knows ordering is per key, how each platform provides it, and when to design it away.
Green flags
Red flags
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
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.
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.
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.
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).
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.
ServiceBusSessionProcessor; confirm zero out-of-order.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);
MaxConcurrentCallsPerSession above 1. Why it is wrong: messages in the same session run concurrently and lose order. Instead: keep 1 and scale with MaxConcurrentSessions.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.
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.
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.
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.
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.
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.
Last updated 23 Nov 2026.