Skip to content

Ordering & Partitioning: Keys, Head-of-Line Blocking ​

"If you use 1 stream -> N consumers, you are load balancing to N consumers, however in that case, messages about the same logical item may be consumed out of order, because a given consumer may process message 3 faster than another consumer is processing message 4." — Redis documentation, Redis Streams, "Differences with Kafka (TM) partitions"

Summary: Order in messaging exists only inside one lane (a queue, a partition, a stream); you choose a key that sends related messages to the same lane and accept that one slow message blocks the lane behind it. Focus: Total vs per-key vs causal order, partition keys and hot keys, head-of-line blocking, Kafka's partitioner and producer retries, RabbitMQ single active consumer and hashing exchanges, Redis stream sharding, Laravel queues, and the retries that silently reorder. Learning goal: Pick a partition key, predict exactly where each broker can reorder your messages, and keep per-key order through concurrency, retries and partition changes, with version checks as the last line of defence.

This page is the complete reference for message ordering. It covers what "ordered" can mean, why global order does not scale, how to choose a partition key (aggregate id, key cardinality, hot keys, compound keys), how Kafka maps keys to partitions (murmur2, the sticky partitioner, custom partitioners, and the remapping when the partition count changes), how producer retries reorder (max.in.flight.requests.per.connection, idempotence), how consumers keep order under concurrency (per-key worker queues in Go), how retries, requeues and DLQ replays reorder, and what RabbitMQ (x-single-active-consumer, x-modulus-hash, the consistent-hash exchange, the sharding plugin), Redis Streams and Laravel queues actually guarantee. It does not re-teach four neighbours. How many consumers to run, Kafka group rebalancing and Horizon autoscaling are in Competing Consumers & Scaling. Ack, nack and offset commit mechanics are in Message Acknowledgment. Backoff schedules and delayed delivery are in Retry, Backoff & Delayed Delivery. The dedup table is in Idempotent Consumers & the Inbox.

Page map ​

If you are looking forGo to
The whole topic in three small tablesEverything in one minute
Why order is expensive and global order does not scaleWhy ordering is hard
Where the vocabulary comes from (EIP, Kafka, RabbitMQ, Redis)Where it comes from
Total, per-key and causal order; publish vs processing orderWhat "ordered" can mean
Partition keys, hot keys, head-of-line blocking, repartitioning, producer and consumer order, retries, versionsThe concepts, one by one
Go code: keyed worker pool, ordered retry, version checkGo
Laravel code: WithoutOverlapping, chains, SQS FIFO groups, shard queuesLaravel
RabbitMQ, Kafka and Redis Streams side by sideBroker differences
murmur2, sticky partitioner, client hash compatibility, requeue position, Laravel's listsMechanics
Every knob and every error you will meetKnobs, Errors and signals
Out-of-order projections, stuck keys, hot tenants, growing partitionsSolving the classic problems
Which design for which situationChoosing a strategy
From one process to multi-regionIn architecture
Reproduce reordering and the fixLab
Wrong beliefs, cheat sheet, every term definedMisconceptions, Cheat sheet, Glossary

Everything in one minute ​

Kinds of order. Each row is unpacked in What "ordered" can mean.

KindIn plain wordsTiny exampleWho provides it
Total (global) orderEvery message in one sequenceOne queue, one consumerOne RabbitMQ queue + one consumer; one Kafka partition; one Redis stream + one reader
Per-key orderMessages with the same key stay in sequence; different keys interleaveorder-7: created → paid → shippedKafka partition by key; RabbitMQ hashing exchange + single active consumer per queue; Redis stream per shard; SQS FIFO message group
Causal orderIf B was caused by A, everyone sees A before BA reply never before its questionNo broker; you carry causality (same key, or version / vector metadata)
No orderAny orderThumbnails for unrelated uploadsAny competing-consumer queue

What breaks order, and where.

EventRabbitMQKafkaRedis StreamsLaravel queue
Two consumers on one laneYes: completion order is arbitraryImpossible inside a group (one consumer per partition)Yes: consumer group load-balances one streamYes: N workers pop one list
Producer retryOnly across channels / connectionsYes if idempotence is off and in-flight > 1No (XADD is one command)No
Consumer retry / requeueRequeue goes back to original position "if possible"; other consumers may have moved onOnly if you skip or re-produce the recordPending entry redelivered later via XCLAIM / XAUTOCLAIMrelease() puts the job at the back
DLQ replayYesYesYesqueue:retry re-pushes at the back
Changing lane countx-modulus-hash: most keys move; consistent-hash: few keys moveAdding partitions remaps hash % NChanging shard count remaps keysChanging shard queue count remaps keys
PrioritiesHigher priority overtakesn/an/a--queue=high,default overtakes

Fix menu.

ProblemFirst fixBackstop
Related messages processed in parallelPartition by aggregate id; one consumer per laneVersion check in the consumer
Need parallelism inside one consumerPer-key worker lanes (hash → channel → one goroutine)Commit only below the lowest offset in flight
Failing message for one keyRetry in place, then park the keyOperator replay of the parked key in order
Producer retries reorderKafka idempotent producer (default on in Java and franz-go, off in librdkafka)Sequence numbers in the payload
Hot keyCompound key, or a dedicated laneAccept the lane is a bottleneck; scale that consumer vertically
Partition count must growOver-provision up frontNew topic + drain old, or version checks during the switch

Why ordering is hard, and why global order does not scale ​

A queue is a line, and a line is ordered for free while one person serves it. The moment a second server opens, people leave the line in a different order from how they joined, because service times differ. Every broker faces the same arithmetic: order requires one sequencing point at the write side and, to preserve it at the read side, one reader at a time. Throughput is then capped by one log on one node and by one consumer's speed.

Choose orderChoose parallelism
One lane, one readerMany lanes, many readers
Simple reasoning: state machines just workThroughput scales with lanes
A slow message stalls everything (head-of-line blocking)A slow message stalls only its lane
Failover means "pause, then resume where the dead one stopped"Failover means "rebalance lanes"
Throughput ceiling = one consumerCeiling = lanes × consumer speed
No reordering by the brokerOrder exists per lane only; between lanes none

The way out is to notice what you actually needed. Customer 7's created, email_changed and deleted must stay in order; customer 8's events do not care about customer 7's. So you pick a key, hash it to a lane, and run one reader per lane. Order holds per key; parallelism equals the number of lanes.

The everyday picture used through this page. A supermarket with one till is totally ordered and slow. Open eight tills and strangers finish in any order, which is fine. A family shopping together is the exception: if the parent must pay before the child collects the bag, the whole family goes to one till, chosen by the family name (the key). A till stuck on a price check holds up every family behind it (head-of-line blocking). If the shop opens a ninth till at lunch, the "family name → till" rule changes and a family mid-shop may be split across two tills (repartitioning).

Three common misunderstandings, up front ​

  1. "Kafka is ordered." Per partition only. A topic with 12 partitions has no global order, and an unkeyed producer gives no per-entity order either.
  2. "One queue with several workers keeps order." The broker dequeues in order; the workers finish in any order. Order at the broker is not order of effects.
  3. "Retries are an error-handling detail." Almost every retry mechanism (requeue, delay queue, DLQ replay, Laravel release()) moves a message behind its successors. Retries are the most common source of reordering in production.

Where it comes from ​

The first queues were ordered because they were single-consumer FIFOs. Hohpe and Woolf's Enterprise Integration Patterns (2003) already treat reordering as normal and give it a pattern: the Resequencer is "a stateful filter" used "to collect and re-order messages so that they can be published to the output channel in a specified order" (EIP site). Its sibling, Message Sequence, numbers the parts of a large message. Both are owned by Advanced Routing; this page uses their idea of a sequence number as the application-level fix.

Modern brokers scope their promise to one lane, each in its own words. Kafka's introduction:

"Events with the same event key (e.g., a customer or vehicle ID) are written to the same partition, and Kafka guarantees that any consumer of a given topic-partition will always read that partition’s events in exactly the same order as they were written."

RabbitMQ's queues guide says "A queue is an ordered collection of messages providing FIFO semantics", and then lists the exceptions: priorities, and multiple active consumers, where "the broker still dequeues in FIFO, but any redelivery can change order." Redis says the same of consumer groups (the quote at the top). The three vendors agree: order exists inside one log or one queue, and nowhere else.

What "ordered" can mean ​

Total (global) order Important ​

In plain words: every message in the system sits in one sequence, and everyone sees that sequence.

Common misunderstanding: "We need global order." Almost nobody does. When you list the invariants, they are per order, per account, per device. Global order is a request for one lane, and you pay for it with one consumer.

Definition: a total order over all messages of a channel such that every consumer observes the same sequence. In practice: a RabbitMQ queue with one consumer (or a stream), a Kafka topic with one partition, one Redis stream read by one consumer.

text
     Producer          Lane (1 queue / 1 partition / 1 stream)       Consumer
1    send m1  ──────▶  [m1]
2    send m2  ──────▶  [m1 m2]
3    send m3  ──────▶  [m1 m2 m3]   ─────────────────────────────▶  process m1
4                      [m2 m3]      ─────────────────────────────▶  process m2   (m3 waits, even if unrelated)

Real scenarios: a ledger for one bank account; a single-writer audit log; a small back-office queue where throughput is irrelevant; a Kafka topic with one partition used as a sequencer for a low-volume control plane.

BrokerHow to get total orderPrice
RabbitMQOne queue, x-single-active-consumer: true, prefetch 1 if handlers can fail; or a streamOne consumer's throughput
KafkaOne partitionOne partition's write and read throughput; one consumer
Redis StreamsOne stream, one reader (no group, or a group with one consumer)One consumer; one Redis shard
LaravelOne queue, one queue:work processOne PHP worker

Fix / how to use it: only for a low-volume, truly sequential stream. Otherwise move to per-key order.

Per-key order Must-know ​

In plain words: messages about the same thing (the same order, account, user) stay in sequence; messages about different things may interleave.

Common misunderstanding: "Per-key order means each key gets its own queue." No: thousands of keys share a few lanes. A lane carries many keys in sequence, which is why one slow key can block others (see head-of-line blocking).

Definition: for any two messages m1, m2 with the same key k, if m1 was published before m2 by the same producer, every consumer processes m1 before m2. No guarantee between different keys.

text
     Lane 0 (keys hashing to 0)            Lane 1 (keys hashing to 1)
1    order-7 created                        order-9 created
2    order-12 created                       order-9 paid
3    order-7 paid                           order-4 created
4    order-7 shipped
     -- order-7 is in sequence; order-7 vs order-9 has no defined order

Real scenarios: order lifecycle events (created → paid → shipped); user profile changes synced to a CRM; device telemetry per device; per-account balance changes; CDC events per primary key (see Change Data Capture).

BrokerPer-key primitive
KafkaRecord key → partition (built in)
RabbitMQx-modulus-hash or x-consistent-hash exchange → N queues, each with single active consumer
Redis StreamsYou shard: hash(key) % N → stream name; one consumer per stream
LaravelSQS FIFO onGroup(); or one queue per shard with one worker each
Amazon SQS FIFOMessage group ID
NATS JetStream, PulsarSubject-based or key-shared subscriptions; see Other Brokers

Fix / how to use it: choose the partition key, then keep one reader per lane and never let two handlers run the same key at once.

Causal order Good to know ​

In plain words: if message B exists because of message A, nobody should see B before A, even if A and B are about different entities.

Common misunderstanding: "Per-key order gives causal order." Only when cause and effect share a key. OrderPlaced(order-7) causes StockReserved(sku-3); with keys order-7 and sku-3 they can land in different partitions and a consumer of both topics may see the reservation first.

Definition: the order induced by "happened-before" (Lamport): A → B if B was produced after its producer observed A. Brokers do not track this relation; the application must carry it.

text
     Orders service            Topic orders (key order-7)     Topic stock (key sku-3)     Reporting consumer
1    publish OrderPlaced ───▶  P2: OrderPlaced
2                                                              Inventory reads it, publishes StockReserved ──▶ P0
3                                                                                          reads stock P0 first: StockReserved for unknown order
4                                                                                          reads orders P2: OrderPlaced (too late)

Real scenarios: a reply before its request in a chat; a "payment captured" before "order created" in a reporting pipeline; an "account closed" notification arriving before the last statement.

Fix: carry the causal key (put order_id on StockReserved and partition by it), or carry the dependency (causation_id, the upstream version) and let the consumer wait or retry until the cause has been applied. Envelope fields are in Message Design & Schema Evolution.

Publish order, delivery order, processing order Must-know ​

In plain words: "in order" can mean three different moments: the order producers sent, the order the broker hands out, and the order handlers finished. Only the last one changes your database.

Common misunderstanding: "The broker delivered in order, so I processed in order." With prefetch above 1 and a handler that spawns goroutines, or two consumers, the broker's delivery order says nothing about completion order.

Definition: publish order is fixed per producer connection/channel (RabbitMQ: "When publishing on a single channel, messages are enqueued in publishing order"); delivery order is the lane order; processing order is the order side effects become visible. Only processing order matters, and only a single in-flight message per key guarantees it.

text
     Producer P1 (channel A)   Producer P2 (channel B)     Queue                 Consumer (prefetch 10, 2 goroutines)
1    publish o7:created                                     [c]
2                              publish o7:paid               [c p]                (two producers: no defined order)
3                                                           deliver c, p ──▶      g1: created (slow DB)
4                                                                                 g2: paid (fast)  -> paid applied first

Fix: one producer (or one channel) per key for publish order; one lane per key for delivery order; one in-flight message per key for processing order.

The concepts, one by one ​

Partition key: choosing it Must-know ​

Producer Akey=order-7 createdkey=order-9 createdkey=order-7 paidkey=order-7 shipped(no key: sticky batches)Producer Bkey=order-3 createdkey=order-9 paidsame key, other producer:same partition, no orderPartitionermurmur2(key)& 0x7fffffff% numPartitions (4)P0order-7: created, paid, shippedP1order-9: created, paidP2order-3: createdP3(other keys)Consumer 1owns P0, P1Consumer 2owns P2, P3Order: inside one partition only. Add a 5th partition and % 5 sends order-7 somewhere else.

In plain words: the partition key is the field the broker (or your code) hashes to choose a lane. Everything with the same key goes to the same lane, so it is processed in order.

Common misunderstanding: "Pick something unique, like the event id, so load spreads evenly." A unique key spreads load perfectly and destroys order, because related events now land in different lanes.

Definition: a function lane = hash(key) mod N (Kafka: murmur2, RabbitMQ x-modulus-hash: hash of the routing key, your Redis sharding: e.g. fnv32a). The key must be the identity of the thing whose events must be sequential.

How to choose it, in order of questions:

QuestionGood answerWhy
Whose events must be in order?The aggregate id: order_id, account_id, device_idDDD aggregates are the consistency boundary; see Domain Events vs Integration Events
How many distinct values? (key cardinality)Many more than lanes (100× or more)Few keys → some lanes empty, others overloaded
Is any single key huge? (hot key)No key above a few % of trafficOne key is always one lane; you cannot spread it
Does a parent need order across children?Use the parent id (tenant, customer) only if you need cross-child orderCoarser key = more order, less parallelism
Will the key ever change for an entity?NeverChanging keys splits an entity's history across lanes
Can every producer compute it the same way?Same bytes, same hash functionSee client hash compatibility

Compound keys. tenant_id:order_id keeps order per order inside a tenant and spreads a big tenant across lanes; you give up order between two orders of the same tenant. tenant_id alone keeps a tenant fully ordered but makes the biggest tenant a hot key. Choose the finest key whose order you truly need.

Real scenarios: e-commerce: order_id; banking: account_id (transfers touch two accounts: partition by the account being debited and let the credit be a separate event); IoT: device_id; multi-tenant SaaS: tenant_id:entity_id; CDC: the table's primary key.

Fix in code: Kafka key in produce.go; RabbitMQ routing key in publish.go; Redis ShardKey in shard.go; Laravel shard queue in OrderedDispatch.php.

Hot keys and key skew Important ​

In plain words: hashing balances keys, not load. If one key produces 40% of the traffic, one lane gets 40% of the traffic, no matter how many lanes exist.

Common misunderstanding: "Add partitions to fix a hot partition." The hot key still hashes to exactly one partition; you only add empty ones.

Definition: key skew is a non-uniform distribution of messages per key; a hot key is a key whose rate exceeds what one consumer can process. The RabbitMQ sharding plugin README states the rule for every hash scheme: "If all messages had the same routing key, they would all end up on the same shard."

text
     keys/min    tenant-big: 40 000   tenant-a: 300   tenant-b: 250   ... (2 000 tenants)
1    hash % 12  -> tenant-big on P5
2    P5 lag grows; P0..P4, P6..P11 idle-ish
3    add 12 more partitions -> tenant-big still on one partition (now P17)
RemedyHowOrder you keepCost
Finer compound keytenant:order instead of tenantPer orderNo order across one tenant's orders
Dedicated laneCustom partitioner pins the hot key to its own partitionFull order for the hot keyA partitioner to maintain; remap when the table changes
Key saltingkey#0..key#7 round-robinNone for that keyConsumer must re-merge (Resequencer) or not care
Separate topic / queueBig tenant gets its own channelFullMore topology
Faster single consumerBatch writes, bigger instance for that laneFullVertical limit

Fix in code: HotKeyPartitioner and CompoundKey in produce.go.

Head-of-line blocking Must-know ​

1. Retry in place: order kept, whole lane stalls2. Park the key: order kept for A, lane keeps movingC #2A #3B #5C #1...A #2fails x5Consumerbusy retrying A #2tail ... B and C are healthy but wait behind A #2: head-of-line blocking ... headC #2B #5C #1ConsumerB, C flow onParked key A: A #2, A #3later A events append here; replay in orderRabbitMQ: reject/nack with requeue on a single active consumer, prefetch 1. Kafka: do not commit past A #2.Redis Streams: do not XACK, re-read pending (ID 0) first. Laravel: release() sends the job to the BACK (order lost).

In plain words: in an ordered lane the consumer cannot skip the message at the front. If that message is slow or keeps failing, every message behind it waits, including messages for other, healthy keys.

Common misunderstanding: "It only delays the failing customer." It delays every key that hashes to the same lane. With 12 partitions and one poison record, one twelfth of all customers stall.

Definition: head-of-line (HOL) blocking is the delay imposed on queued items by the item at the head of an ordered queue. It is the direct price of in-order processing; you can shrink its blast radius but not remove it while keeping order.

text
     Lane 3 (single active consumer, prefetch 1)
1    head: order-7 #2 -> payment API 503 -> reject(requeue) -> back to the head
2    order-7 #2 again -> 503 ...                         (order-12, order-31 waiting)
3    20 deliveries later (quorum queue default delivery-limit) -> dead-lettered
4    order-7 #3 now processed -> applies "shipped" on an order that was never "paid"

Step 4 shows the second trap: escaping HOL by dropping or dead-lettering the head lets the next message of the same key overtake it. Order is lost exactly where it mattered.

StrategyOrder for the failing keyOther keys in the laneUse when
Retry in place foreverKeptBlockedThe failure is global (DB down) and will pass
Retry in place N times, then dead-letterBroken (next message overtakes)FreedMessages are independent after all
Retry in place N times, then park the keyKeptFreedPer-key state machines, ledgers
More lanesKeptFewer keys per laneAlways helps the blast radius
Per-key lanes inside the consumerKeptOnly same-lane keys waitYou need parallelism in one process

Fix in code: retry.OrderedRetrier (park the key) in Go; the rules per broker are in Broker differences.

Repartitioning: when the lane count changes Must-know ​

In plain words: hash(key) % N gives a different answer when N changes. Add a partition and many keys move to a new lane while their older messages are still waiting in the old one.

Common misunderstanding: "Kafka will move the old data." It does not. The operations guide: "adding partitions doesn’t change the partitioning of existing data so this may disturb consumers if they rely on that partition", and the partitioning "will potentially be shuffled by adding partitions but Kafka will not attempt to automatically redistribute data in any way."

Definition: a key→lane remap. With modulo hashing (% N) most keys change lane when N changes; with consistent hashing (ring, jump hash) only about 1/N of keys move. See Consistent Hashing.

text
     t0: 4 partitions. order-7 -> P0.  P0 holds order-7 #1..#5, consumer C1 lagging
1    t1: admin raises partitions to 5
2    t2: producer: order-7 #6 -> murmur2 % 5 = P3
3    t3: C2 (owns P3, no lag) applies #6 "cancelled"
4    t4: C1 finally applies #4, #5 "paid", "shipped" on a cancelled order
ProductWhat remapsBuilt-in help
KafkaAll keyed producers once they see new metadataNone; plan partitions up front
RabbitMQ x-modulus-hash"the routing for almost all keys will be reshuffled" when queues are added or removedStable as long as bindings stay the same, even across restarts
RabbitMQ x-consistent-hashFew keys on bind/unbind; may also move after a node restartMinimal movement, no locality guarantee
Redis Streams (your sharding)Whatever your % N doesNone
Laravel shard queuesWhatever your crc32 % N doesNone

Fix: over-provision lanes (Kafka partitions are cheap compared with a migration); if you must grow, either drain (stop producers for the topic, let consumers reach the end, then add partitions) or create a new topic with more partitions and switch producers at a cut-over, keeping version checks on during the switch. Never rely on "it is only a few keys".

Producer-side order: in-flight requests and idempotence Must-know ​

In plain words: a producer that sends batch 2 before batch 1 is acknowledged can end up with batch 2 written first if batch 1 fails and is retried.

Common misunderstanding: "Order is a consumer problem." The Kafka producer docs describe a purely producer-side reordering: "if two batches are sent to a single partition, and the first fails and is retried but the second succeeds, then the records in the second batch may appear first."

Definition: for the Java producer, max.in.flight.requests.per.connection (default 5) bounds unacknowledged requests per connection. The docs: "if this configuration is set to be greater than 1 and enable.idempotence is set to false, there is a risk of message reordering after a failed send due to retries (i.e., if retries are enabled); if retries are disabled or if enable.idempotence is set to true, ordering will be preserved." Idempotence makes the broker track a producer id and per-partition sequence numbers, so a retried batch is placed correctly or rejected; it requires max.in.flight.requests.per.connection ≤ 5, retries > 0 and acks=all, and "is enabled by default if no conflicting configurations are set."

text
     Producer (idempotence OFF, max.in.flight=5, retries on)      Partition P0 leader
1    send batch A (order-7 #1)  ─────────────────────────────▶   timeout / NOT_LEADER
2    send batch B (order-7 #2)  ─────────────────────────────▶   appended at offset 100
3    retry batch A              ─────────────────────────────▶   appended at offset 101
     -- consumers read #2 then #1
     with idempotence ON: broker sees B's sequence > expected, rejects it; producer resends A then B
ClientDefault partitionerIdempotence defaultIn-flight default
Java producermurmur2 for keys; sticky (KIP-480/794) without a keytrue (if no conflicting config)5
franz-goUniformBytesPartitioner family; StickyKeyPartitioner(nil) = Java's key hashingOn (DisableIdempotentWrite() to turn off)5 with idempotence; 1 without, unless MaxProduceRequestsInflightPerBroker
librdkafka (php-rdkafka, Laravel Kafka, confluent-kafka-go)consistent_random (CRC32)false1000000
RabbitMQ publishern/an/a: one channel is orderedPublisher confirms do not reorder a channel
Redis XADDn/an/aEach XADD is atomic and gets a monotonically increasing ID

Error you may see: OutOfOrderSequenceException: the Java javadoc says the broker "received an unexpected sequence number from the producer", and for an idempotent (non-transactional) producer continuing "risks reordering of sent records". For transactional producers it is fatal. Idempotence and transactions as delivery guarantees are owned by Delivery Guarantees.

Fix in code: keep idempotence on, acks=all; in librdkafka set enable.idempotence=true explicitly. See produce.go and UserEventPublisher.php.

Consumer-side order with concurrency Must-know ​

Fetch loopone partition /queue / stream,read in orderDispatcherlane =fnv32a(key) % Nstable across restartslane 0: chan (cap 16)order-7, order-12, ...lane 1: chan (cap 16)order-9, order-4, ...lane 2: chan (cap 16)order-3, ...goroutine 0one event at a timegoroutine 1one event at a timegoroutine 2one event at a timeCommit / ack trackercommit only below the lowest offset in flightfull lane blocks dispatcher = backpressure

In plain words: one consumer per lane is often too slow. You can process many keys in parallel inside one consumer, as long as each key goes to exactly one worker and that worker handles its messages one at a time.

Common misunderstanding: "I'll just go handle(msg) for each message." Now two messages of order-7 run at once and finish in any order, and you also commit offsets for messages that have not finished.

Definition: a per-key worker pool (keyed executor): a single fetch loop reads the lane in order; a dispatcher computes lane = hash(key) % N with a hash that is stable across processes; each of N bounded channels is drained by one goroutine. Different keys run concurrently; one key never does. The ack/commit point is the lowest offset still in flight in any lane.

text
     Fetch loop (partition P0, offsets 100..105)   Dispatcher         Lanes (1 goroutine each)
1    100 order-7  ─────────────────────────────▶   fnv(order-7)%3=0   lane0: 100 running
2    101 order-9  ─────────────────────────────▶   fnv(order-9)%3=2   lane2: 101 running
3    102 order-7  ─────────────────────────────▶   lane 0             lane0: 102 queued behind 100
4    101 done, 100 still running                                       commit point stays at 100 (not 102)
5    100 done, 102 done                                                commit 103
ConcernRule
HashStable across restarts and languages (hash/fnv, crc32); never Go map order or a per-process seed
Channel sizeBounded; a full lane blocks the dispatcher: backpressure, see Backpressure & Flow Control
Commit / ackOnly below the lowest unfinished offset (Kafka); RabbitMQ: ack each delivery when its lane finished it, never multiple=true past an unfinished one
PrefetchRabbitMQ prefetch > 1 is fine only with keyed lanes inside; with free goroutines it reorders
RebalanceDrain lanes before giving up a partition (franz-go BlockRebalanceOnPoll + AllowRebalance)
ShutdownStop fetching, close lanes, wait, commit

Ack and commit semantics in detail are in Message Acknowledgment; sizing the pool and graceful shutdown in Competing Consumers & Scaling.

Fix in code: serialiser.KeyedPool in Go; partition-parallel consumer kafka.Run in Kafka.

Retries that reorder Must-know ​

In plain words: most retry mechanisms take the failed message out of line and put it back later, behind messages that came after it.

Common misunderstanding: "A delay queue is just a pause." A delay queue (RabbitMQ TTL + DLX, Kafka retry topic, Laravel release(30)) is a different lane. While message #2 waits there, #3 is processed.

Definition: a reordering retry is any retry that lets a later message of the same key be processed before the retried one. Non-reordering retries either retry in place (blocking the lane) or park the whole key.

text
     Kafka main topic, partition P1                 retry topic (30 s delay)
1    order-7 #2 fails -> produced to retry topic    order-7 #2 (waits 30 s)
2    commit #2, continue
3    order-7 #3 "shipped" applied
4                                                   order-7 #2 "paid" applied after "shipped"
MechanismReorders?Notes
RabbitMQ basic.reject/basic.nack with requeueUsually not with one consumer and prefetch 1; possible with several consumers"placed to its original position in its queue, if possible"; otherwise "closer to queue head"
RabbitMQ quorum queue returnsReturns go to a returns queue "in the exact order they were returned"Redelivered before the rest; delivery limit default 20
RabbitMQ TTL + DLX delay queueYesA different queue
Kafka retry topic / DLQ topicYesA different partition and topic
Kafka "skip and commit"Yes (message lost from order)Never commit past an unprocessed record you still care about
Redis Streams: leave pending, XAUTOCLAIM laterYes, if the consumer kept reading >Re-read pending (ID 0) first to keep order
Laravel release($delay) / failed job + queue:retryYesReleased jobs go to the delayed sorted set, then rpush to the back
In-place retry with backoffNoHead-of-line blocking
Park the keyNoAll later messages for the key wait behind it

Fix in code: in-place retry + park the key (retry.OrderedRetrier), and the version check as backstop (version.Apply). Backoff policy design is in Retry, Backoff & Delayed Delivery; where parked messages finally go is in Dead-Letter Queue.

Sequence numbers and event versions Must-know ​

In plain words: stamp each event with the entity's version (1, 2, 3...). The consumer applies an event only if it is newer than what it already has. Any reordering the infrastructure lets through becomes harmless.

Common misunderstanding: "Timestamps do the same." Wall clocks on two producers disagree, and two events in one millisecond tie. Use a per-aggregate counter from the source of truth (the row's version column, the event store's stream position, a CDC LSN).

Definition: a monotonically increasing per-key sequence number assigned by the single writer of that key. The consumer stores the last applied version and uses compare-and-set (WHERE version < :incoming) to apply. For state snapshots ("event-carried state transfer") dropping stale events is enough. For deltas (+10 €) you also need gap detection: if version 5 arrives after 3, wait or park until 4 arrives.

sql
-- read model guarded by version: stale or duplicate events update zero rows
CREATE TABLE customer_view (
  id      bigint PRIMARY KEY,
  email   text   NOT NULL,
  version bigint NOT NULL
);

INSERT INTO customer_view (id, email, version)
VALUES ($1, $2, $3)
ON CONFLICT (id) DO UPDATE
   SET email = EXCLUDED.email, version = EXCLUDED.version
 WHERE customer_view.version < EXCLUDED.version;   -- 0 rows = stale, skip
text
     Consumer (versions arrive 1, 3, 2)
1    v1 email=a@x   -> view(version 0 -> 1)  applied
2    v3 email=c@x   -> view(1 -> 3)          applied (snapshot event: gap is fine)
3    v2 email=b@x   -> WHERE 3 < 2 false     skipped; view keeps c@x (correct final state)
Event styleVersion check enough?Extra
Full-state snapshot ("customer is now X")YesNone
Delta ("balance +10")NoGap detection, park until missing version
Command-like ("ship order")NoState machine guard: allowed only from paid

This is the same compare-and-set idea as a version column in Optimistic vs Pessimistic Locking; the dedup side (same version twice) is the idempotent consumer. Where the version comes from at the producer is the outbox's job: Transactional Outbox.

Fix in code: version.Apply in Go and ApplyIfNewer in Laravel.

Go ​

Before ​

Four workers drain one channel, the in-process version of competing consumers. Nothing ties a user to a worker, so user u-42's deleted event can be applied before its email_changed event.

go
// Package main shows parallel consumers reordering one user's events.
package main

import (
	"fmt"
	"sync"
	"time"
)

type Event struct {
	UserID string
	Seq    int
	Kind   string
}

func main() {
	events := make(chan Event)
	var wg sync.WaitGroup

	// Four workers share one channel, exactly like competing consumers on
	// one queue. Nothing ties a user to a worker.
	for w := 0; w < 4; w++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			for e := range events {
				// Work time varies, so a later event can finish first.
				time.Sleep(time.Duration(5-e.Seq%5) * time.Millisecond)
				fmt.Printf("applied user=%s seq=%d kind=%s\n", e.UserID, e.Seq, e.Kind)
			}
		}()
	}

	// Published in order: created(0), email_changed(1), deleted(2), ...
	kinds := []string{"created", "email_changed", "deleted"}
	for i, k := range kinds {
		events <- Event{UserID: "u-42", Seq: i, Kind: k}
	}
	close(events)
	wg.Wait()
	// "deleted" can be applied before "email_changed": the user is deleted,
	// then an update resurrects or errors on a missing row.
}

After ​

The keyed serialiser: hash the key to a lane, give each lane one goroutine. Different users run in parallel, one user never does. A full lane blocks Submit, which is head-of-line blocking showing up as backpressure.

go
// Package serialiser runs handlers in parallel across keys and strictly in
// order within one key.
package serialiser

import (
	"context"
	"hash/fnv"
	"sync"
)

type Event struct {
	Key     string
	Payload []byte
}

// KeyedPool owns N lanes. The same key always maps to the same lane, and a
// lane is drained by exactly one goroutine, so per-key order is preserved
// while different keys run concurrently.
type KeyedPool struct {
	lanes []chan Event
	wg    sync.WaitGroup
}

func NewKeyedPool(ctx context.Context, lanes, buffer int, handle func(context.Context, Event)) *KeyedPool {
	p := &KeyedPool{lanes: make([]chan Event, lanes)}
	for i := range p.lanes {
		p.lanes[i] = make(chan Event, buffer)
		p.wg.Add(1)
		go func(in <-chan Event) {
			defer p.wg.Done()
			for e := range in {
				handle(ctx, e)
			}
		}(p.lanes[i])
	}
	return p
}

func (p *KeyedPool) lane(key string) int {
	h := fnv.New32a()
	_, _ = h.Write([]byte(key))
	return int(h.Sum32() % uint32(len(p.lanes)))
}

// Submit blocks when the lane is full. A slow key therefore delays every key
// that shares its lane: head-of-line blocking, made visible as backpressure.
func (p *KeyedPool) Submit(ctx context.Context, e Event) error {
	select {
	case p.lanes[p.lane(e.Key)] <- e:
		return nil
	case <-ctx.Done():
		return ctx.Err()
	}
}

// Close stops intake and waits for the lanes to drain.
func (p *KeyedPool) Close() {
	for _, l := range p.lanes {
		close(l)
	}
	p.wg.Wait()
}

A test that pushes 100 events for each of 5 keys through 3 lanes and asserts per-key order (go test ./... passes):

go
package serialiser

import (
	"context"
	"fmt"
	"sync"
	"testing"
)

func TestPerKeyOrder(t *testing.T) {
	ctx := context.Background()
	var mu sync.Mutex
	got := map[string][]string{}
	p := NewKeyedPool(ctx, 3, 4, func(_ context.Context, e Event) {
		mu.Lock()
		got[e.Key] = append(got[e.Key], string(e.Payload))
		mu.Unlock()
	})
	for i := 0; i < 100; i++ {
		for _, k := range []string{"u-1", "u-2", "u-3", "u-4", "u-5"} {
			_ = p.Submit(ctx, Event{Key: k, Payload: []byte(fmt.Sprint(i))})
		}
	}
	p.Close()
	for k, seq := range got {
		for i, v := range seq {
			if v != fmt.Sprint(i) {
				t.Fatalf("key %s out of order at %d: %v", k, i, seq[:i+1])
			}
		}
	}
}

Retry without reordering: retry in place with backoff; if the retries run out, park the key, so every later event for it queues behind the failed one while other keys keep moving. Resume replays in order and stops at the first failure.

go
// Package retry keeps per-key order when a handler fails: it retries in place
// (blocking only that key's lane) and, if the retries run out, parks the key so
// that every later event for it waits behind the failed one.
package retry

import (
	"context"
	"errors"
	"sync"
	"time"
)

type Event struct {
	Key     string
	Seq     int64
	Payload []byte
}

// Handler applies one event. It must be idempotent: a parked event is
// replayed later and may already be partly applied.
type Handler func(context.Context, Event) error

// OrderedRetrier is called from ONE goroutine per lane (see the serialiser
// package), so events of a key reach Process in their original order.
type OrderedRetrier struct {
	Handle   Handler
	Attempts int           // in-place attempts before parking, e.g. 5
	Backoff  time.Duration // base backoff, doubled per attempt

	mu     sync.Mutex
	parked map[string][]Event // key -> failed event + everything after it
}

var ErrParked = errors.New("key parked: event queued behind an earlier failure")

// Process blocks the key (and, because lanes are shared, the lane) while it
// retries. That is the price of order: head-of-line blocking is deliberate.
func (r *OrderedRetrier) Process(ctx context.Context, e Event) error {
	r.mu.Lock()
	if r.parked == nil {
		r.parked = map[string][]Event{}
	}
	if q, ok := r.parked[e.Key]; ok {
		// An earlier event of this key failed: never overtake it.
		r.parked[e.Key] = append(q, e)
		r.mu.Unlock()
		return ErrParked
	}
	r.mu.Unlock()

	delay := r.Backoff
	var err error
	for attempt := 1; attempt <= r.Attempts; attempt++ {
		if err = r.Handle(ctx, e); err == nil {
			return nil
		}
		if attempt == r.Attempts {
			break
		}
		select {
		case <-time.After(delay):
			delay *= 2
		case <-ctx.Done():
			return ctx.Err()
		}
	}

	// Give up on the key, not on the lane: park it so other keys keep moving.
	r.mu.Lock()
	r.parked[e.Key] = []Event{e}
	r.mu.Unlock()
	return err
}

// Parked returns the keys waiting for an operator or a fix.
func (r *OrderedRetrier) Parked() map[string]int {
	r.mu.Lock()
	defer r.mu.Unlock()
	out := make(map[string]int, len(r.parked))
	for k, q := range r.parked {
		out[k] = len(q)
	}
	return out
}

// Resume replays a parked key in its original order. It stops at the first
// failure and keeps the rest parked, so order is never broken.
func (r *OrderedRetrier) Resume(ctx context.Context, key string) error {
	r.mu.Lock()
	q := r.parked[key]
	r.mu.Unlock()
	for i, e := range q {
		if err := r.Handle(ctx, e); err != nil {
			r.mu.Lock()
			r.parked[key] = q[i:]
			r.mu.Unlock()
			return err
		}
	}
	r.mu.Lock()
	delete(r.parked, key)
	r.mu.Unlock()
	return nil
}
go
package retry

import (
	"context"
	"errors"
	"reflect"
	"testing"
)

func TestParkedKeyKeepsOrder(t *testing.T) {
	ctx := context.Background()
	var applied []int64
	broken := true
	r := &OrderedRetrier{Attempts: 2, Handle: func(_ context.Context, e Event) error {
		if e.Key == "a" && e.Seq == 2 && broken {
			return errors.New("downstream 503")
		}
		applied = append(applied, e.Seq)
		return nil
	}}

	for _, e := range []Event{{Key: "a", Seq: 1}, {Key: "a", Seq: 2}, {Key: "b", Seq: 10}, {Key: "a", Seq: 3}} {
		_ = r.Process(ctx, e)
	}
	// a/3 must not overtake a/2; b is unaffected.
	if want := []int64{1, 10}; !reflect.DeepEqual(applied, want) {
		t.Fatalf("before resume: got %v want %v", applied, want)
	}
	if got := r.Parked()["a"]; got != 2 {
		t.Fatalf("parked a: got %d want 2", got)
	}

	broken = false
	if err := r.Resume(ctx, "a"); err != nil {
		t.Fatal(err)
	}
	if want := []int64{1, 10, 2, 3}; !reflect.DeepEqual(applied, want) {
		t.Fatalf("after resume: got %v want %v", applied, want)
	}
}

The backstop: a version-guarded upsert with database/sql.

go
// Package version applies an event only if it is newer than what the read
// model already holds: the application-level fix for any reordering that
// slipped through (retries, DLQ replays, partition changes, two producers).
package version

import (
	"context"
	"database/sql"
)

type CustomerChanged struct {
	CustomerID int64
	Version    int64 // per-aggregate sequence set by the producer, 1, 2, 3, ...
	Email      string
}

// Apply returns applied=false for a stale or duplicate event. The guard is in
// the WHERE clause, so two consumers racing on one row cannot both win.
func Apply(ctx context.Context, db *sql.DB, e CustomerChanged) (applied bool, err error) {
	res, err := db.ExecContext(ctx, `
		INSERT INTO customer_view (id, email, version)
		VALUES ($1, $2, $3)
		ON CONFLICT (id) DO UPDATE
		   SET email = EXCLUDED.email, version = EXCLUDED.version
		 WHERE customer_view.version < EXCLUDED.version`,
		e.CustomerID, e.Email, e.Version)
	if err != nil {
		return false, err
	}
	n, err := res.RowsAffected()
	return n == 1, err
}

// Gap reports whether an event skipped a version. Version checks drop stale
// events; they do not wait for missing ones. If a gap matters (a ledger, a
// state machine), buffer or park the key until the missing version arrives.
func Gap(current, incoming int64) bool { return incoming > current+1 }

Wiring, without a broker:

go
// Package main wires the keyed pieces without needing a running broker.
package main

import (
	"context"
	"fmt"
	"sync"

	"academy/ordering-partitioning/after/kafka"
	"academy/ordering-partitioning/after/redis"
	"academy/ordering-partitioning/after/serialiser"
)

func main() {
	ctx := context.Background()
	var mu sync.Mutex
	seen := map[string][]string{}

	pool := serialiser.NewKeyedPool(ctx, 4, 16, func(_ context.Context, e serialiser.Event) {
		mu.Lock()
		defer mu.Unlock()
		seen[e.Key] = append(seen[e.Key], string(e.Payload))
	})
	for _, k := range []string{"created", "email_changed", "deleted"} {
		_ = pool.Submit(ctx, serialiser.Event{Key: "u-42", Payload: []byte(k)})
	}
	pool.Close()

	fmt.Println(seen["u-42"], redis.ShardKey("u-42"), string(kafka.CompoundKey("t-9", "o-1")))
}

The Go angle ​

A Go channel is exactly one ordered lane: values are received in send order, and one goroutine ranging over it processes them one at a time. "N channels, hash to pick one" is therefore the natural idiom, and it is the same shape as a Kafka partition or a hash-exchange queue. Use hash/fnv or hash/crc32 from the standard library; avoid map iteration order and maphash with a random seed, because the key→lane mapping must be identical across processes and restarts. For brokers: franz-go exposes kgo.StickyKeyPartitioner(nil) (Java-compatible murmur2), kgo.BasicConsistentPartitioner for custom partitioners, kgo.DisableAutoCommit, BlockRebalanceOnPoll and CommitRecords; amqp091-go passes x- arguments as an amqp.Table; go-redis gives XAdd, XReadGroup, XAck, and leaves stream sharding to you.

Laravel ​

Before ​

Eight workers on one queue, three jobs for one user dispatched back to back. The queue delivers each job to one worker; it does not run them in dispatch order, so deleted can run before created.

php
<?php

namespace App\Jobs;

use App\Models\User;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;

// Dispatched once per change, in order: created, email changed, deleted.
// With eight workers on the "default" queue, three different workers can pop
// those three jobs within milliseconds of each other and run them in parallel.
class SyncUserToCrm implements ShouldQueue
{
    use Queueable;

    public function __construct(
        public int $userId,
        public string $kind, // created | email_changed | deleted
    ) {}

    public function handle(): void
    {
        $user = User::withTrashed()->find($this->userId);

        match ($this->kind) {
            'created' => $this->crm()->upsert($user),
            'email_changed' => $this->crm()->updateEmail($user), // may run after "deleted"
            'deleted' => $this->crm()->delete($user),            // may run before "created"
        };
    }

    private function crm(): object
    {
        return app('crm');
    }
}

// Caller:
// SyncUserToCrm::dispatch($user->id, 'created');
// SyncUserToCrm::dispatch($user->id, 'email_changed');
// SyncUserToCrm::dispatch($user->id, 'deleted');

After ​

WithoutOverlapping keyed by user id stops two of that user's jobs running at the same time. Read its limit carefully: it is mutual exclusion, not ordering. The docs describe it as a way to "prevent job overlaps based on an arbitrary key", and a job that finds the lock taken is released and retried later, possibly behind a younger job. The docs also warn: "Releasing an overlapping job back onto the queue will still increment the job's total number of attempts", hence #[Tries(20)].

php
<?php

namespace App\Jobs;

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\Attributes\Tries;
use Illuminate\Queue\Middleware\WithoutOverlapping;

// A released job still counts as an attempt, so leave room for it.
#[Tries(20)]
class SyncUserToCrm implements ShouldQueue
{
    use Queueable;

    public function __construct(
        public int $userId,
        public string $kind,
    ) {}

    /**
     * One job per user at a time. This is mutual exclusion, not ordering:
     * a job that finds the lock taken is released and runs again later,
     * possibly after a job that was dispatched after it.
     *
     * @return array<int, object>
     */
    public function middleware(): array
    {
        return [
            (new WithoutOverlapping((string) $this->userId))
                ->releaseAfter(5)
                ->expireAfter(180),
        ];
    }

    public function handle(): void
    {
        // Handlers must also tolerate a stale event, for example by comparing
        // a version column, because the lock alone does not fix the order.
    }
}

// For real per-key ordering, route one user to one queue and run one worker
// for that queue (see RedisShard.php), then keep WithoutOverlapping as a guard:
//
// SyncUserToCrm::dispatch($user->id, 'created')->onQueue(RedisShard::queue($user->id));

Real sequencing comes from three tools: a chain when the sequence is known up front, an SQS FIFO message group, or one queue per shard with one worker each.

php
<?php

namespace App\Orders;

use App\Jobs\CaptureOrderPayment;
use App\Jobs\ReserveOrderStock;
use App\Jobs\ShipOrder;
use App\Models\Order;
use Illuminate\Support\Facades\Bus;

final class OrderedDispatch
{
    /**
     * Sequencing known in advance: a chain runs the next job only after the
     * previous one succeeded, and stops if one fails.
     */
    public function fulfil(Order $order): void
    {
        Bus::chain([
            new ReserveOrderStock($order->id),
            new CaptureOrderPayment($order->id),
            new ShipOrder($order->id),
        ])->onQueue('orders')->dispatch();
    }

    /**
     * Per-key order on Amazon SQS FIFO: jobs with the same message group run
     * one after another, different groups in parallel.
     */
    public function onSqsFifo(Order $order): void
    {
        CaptureOrderPayment::dispatch($order->id)
            ->onConnection('sqs-fifo')
            ->onGroup("order-{$order->id}");
    }

    /**
     * Per-key order on the redis/database drivers: one queue per shard and
     * exactly ONE `queue:work --queue=orders-N` process per shard queue.
     */
    public function onShard(Order $order): void
    {
        $shard = crc32((string) $order->id) % 8;

        CaptureOrderPayment::dispatch($order->id)->onQueue("orders-{$shard}");
    }
}

And the backstop, the same version-guarded upsert as the Go code:

php
<?php

namespace App\Listeners;

use Illuminate\Support\Facades\DB;

/**
 * Consumer-side version check: the application-level fix for reordering.
 * The producer stamps every event with the aggregate's version (1, 2, 3...).
 * A stale or duplicated event updates zero rows and is dropped.
 */
final class ApplyIfNewer
{
    /**
     * @param  array{customer_id: int, version: int, email: string}  $event
     */
    public function handle(array $event): bool
    {
        $affected = DB::affectingStatement(
            'INSERT INTO customer_view (id, email, version) VALUES (?, ?, ?)
             ON CONFLICT (id) DO UPDATE
                SET email = EXCLUDED.email, version = EXCLUDED.version
              WHERE customer_view.version < EXCLUDED.version',
            [$event['customer_id'], $event['email'], $event['version']],
        );

        // 0 = this event is older than (or equal to) what we already applied.
        return $affected === 1;
    }
}

The Laravel angle ​

Laravel 13's queue configuration covers the database, Amazon SQS, Redis and Beanstalkd drivers, plus sync and null. A single worker processing a single queue is FIFO for the redis driver: the framework's Lua scripts push with rpush and pop with lpop. Order ends there. Run several workers and they pop the same list concurrently; release() adds the job to the :delayed sorted set with zadd, and the migration back uses rpush, so a released job lands behind younger jobs; --queue=high,default lets one queue overtake another. Tools that help:

ToolWhat it givesWhat it does not
Bus::chain([...])Strict sequence of known steps: "run in sequence after the primary job has executed successfully"; stops on failureOrder across independently dispatched jobs
WithoutOverlapping($key)One running job per key (atomic lock; cache drivers memcached, redis, dynamodb, database, file, array)Dispatch order: released jobs come back later
SQS FIFO + onGroup() / messageGroup()"Jobs with the same group ID are processed sequentially"Other drivers
One queue per shard + one queue:work --queue=orders-N per shardPer-key FIFO on redis/databaseSurvives release(): no, a released job still goes to the back
ShouldBeUniqueAt most one queued instance per keyOrder
Version column + conditional updateCorrect final state whatever the orderDelta events without gap handling

If you run Horizon, configure ordered shard queues with exactly one process each. Driver internals are in Laravel Queue Internals. RabbitMQ and Kafka are not built-in drivers: Kafka via mateusjunges/laravel-kafka (below), RabbitMQ via vladimir-yuldashev/laravel-queue-rabbitmq (its ordering is RabbitMQ's: see below).

Broker differences ​

QuestionRabbitMQKafkaRedis Streams
Unit of orderQueue (or stream)PartitionStream key
Key → lanex-modulus-hash (built in), x-consistent-hash (plugin), sharding pluginRecord key, murmur2 % partitionsYour code: hash(key) % N → stream name
One reader per lanex-single-active-consumer: true (or one consumer)Automatic inside a consumer groupYou assign shards to consumers
Failover keeps order?Yes: SAC promotes a standbyYes: partition moves to another group member at the committed offsetYes, if the new owner re-reads the pending list first
Retry without reorderingReject/nack requeue with one consumer, prefetch 1Retry in place; do not commit pastDo not XACK; re-read ID 0
Lane count changeModulus: most keys move; consistent hash: fewAdding partitions remaps keysYour remap
Priorities break orderYesn/an/a

RabbitMQ ​

A queue is FIFO: "When publishing on a single channel, messages are enqueued in publishing order in every queue they are routed to," and messages from several channels are interleaved. Delivery follows enqueue order unless priorities or redelivery intervene. The guide's two options to keep order are a stream, or a queue with a single active consumer; it adds: return messages in the order received, set a delivery limit on quorum queues "This ensures messages are requeued at the front of the queue", don't use basic.get, and prefer closing the channel over basic.cancel when stopping a consumer.

For per-entity order and parallelism, the guide now recommends the built-in x-modulus-hash exchange: "As long as the bindings to the exchange remain the same, messages with the same routing key will always be routed to exactly the same destination queue, even across node restarts." Bind N queues, enable SAC on each, and run N application instances. The consistent-hash exchange (rabbitmq_consistent_hash_exchange plugin, binding key = weight, hash-header or hash-property to hash something other than the routing key) moves fewer keys when queues are added, but its README warns that it "cannot guarantee stable queue routing locality for messages with a given routing key", because the ring is rebuilt in memory on restart. The sharding plugin (rabbitmq_sharding) creates shard queues per node behind a pseudo-queue; it "trades off total ordering on the logical queue for gains in parallelism" and is for non-replicated classic queues only.

go
// Package rabbitmq partitions one logical stream of events into N ordered
// lanes: a hashing exchange picks the queue, single active consumer keeps
// each queue strictly sequential.
package rabbitmq

import (
	"context"
	"fmt"

	amqp "github.com/rabbitmq/amqp091-go"
)

const lanes = 4

// DeclareModulusHash is the topology the RabbitMQ queues guide recommends for
// per-entity order: x-modulus-hash routes hash(routing key) mod N and keeps a
// key on the same queue as long as the bindings do not change, even across
// node restarts. It ignores binding keys.
func DeclareModulusHash(ch *amqp.Channel) error {
	if err := ch.ExchangeDeclare("orders.events", "x-modulus-hash", true, false, false, false, nil); err != nil {
		return err
	}
	for i := 0; i < lanes; i++ {
		q := fmt.Sprintf("orders.events.lane.%d", i)
		args := amqp.Table{
			"x-queue-type": "quorum",
			// One consumer receives at a time; others wait as hot standbys.
			// SAC cannot be enabled by policy, only at declaration.
			"x-single-active-consumer": true,
		}
		if _, err := ch.QueueDeclare(q, true, false, false, false, args); err != nil {
			return err
		}
		if err := ch.QueueBind(q, "", "orders.events", false, nil); err != nil {
			return err
		}
	}
	return nil
}

// DeclareConsistentHash is the plugin-based alternative
// (rabbitmq-plugins enable rabbitmq_consistent_hash_exchange). The binding key
// is a weight. Adding a queue moves few keys, but the ring is rebuilt in
// memory on restart, so a key MAY move to another queue: pair it with
// version checks in the consumer.
func DeclareConsistentHash(ch *amqp.Channel) error {
	args := amqp.Table{"hash-header": "order-id"} // hash a header, not the routing key
	if err := ch.ExchangeDeclare("orders.events.ch", "x-consistent-hash", true, false, false, false, args); err != nil {
		return err
	}
	for i := 0; i < lanes; i++ {
		q := fmt.Sprintf("orders.events.ch.lane.%d", i)
		if _, err := ch.QueueDeclare(q, true, false, false, false, amqp.Table{"x-single-active-consumer": true}); err != nil {
			return err
		}
		if err := ch.QueueBind(q, "1", "orders.events.ch", false, nil); err != nil {
			return err
		}
	}
	return nil
}

// Publish uses the order id as the routing key, so every event of one order
// lands in one lane. Publish one order's events on ONE channel: messages from
// different channels are interleaved by the broker.
func Publish(ctx context.Context, ch *amqp.Channel, orderID string, seq int64, body []byte) error {
	return ch.PublishWithContext(ctx, "orders.events", orderID, false, false, amqp.Publishing{
		DeliveryMode: amqp.Persistent,
		ContentType:  "application/json",
		Headers:      amqp.Table{"order-id": orderID, "seq": seq},
		Body:         body,
	})
}
go
package rabbitmq

import (
	"context"

	amqp "github.com/rabbitmq/amqp091-go"
)

// ConsumeLane processes one lane strictly in order. Prefetch 1 means the
// broker never hands this consumer message N+1 before N is settled, so a
// requeue cannot let a later message overtake an earlier one.
func ConsumeLane(ctx context.Context, ch *amqp.Channel, queue string, handle func(amqp.Delivery) error) error {
	if err := ch.Qos(1, 0, false); err != nil {
		return err
	}
	msgs, err := ch.ConsumeWithContext(ctx, queue, "", false, false, false, false, nil)
	if err != nil {
		return err
	}
	for d := range msgs {
		if err := handle(d); err != nil {
			// requeue=true returns the message to its original position if
			// possible; with one consumer and prefetch 1 that is the head, so
			// it is retried before anything behind it (head-of-line blocking).
			// On quorum queues basic.reject counts towards the delivery
			// limit (default 20 since 4.0); since 4.3 basic.nack does not.
			_ = d.Reject(true)
			continue
		}
		_ = d.Ack(false)
	}
	return ctx.Err()
}

What breaks: a second active consumer on a lane; x-max-priority; publishing one entity's messages from two channels; a TTL+DLX delay queue for retries; redeclaring a queue with different arguments (fails with 406 PRECONDITION_FAILED, which protects you from silently changing SAC). SAC cannot be enabled by policy, only by the x-single-active-consumer argument at declaration. Since RabbitMQ 4.3 basic.nack requeues no longer count towards the quorum queue delivery limit; use basic.reject if you rely on the limit to stop a poison message. Laravel through vladimir-yuldashev/laravel-queue-rabbitmq inherits all of this. Deep dive: RabbitMQ in Depth.

Kafka ​

Order is per partition and the key picks the partition: the Java client computes Utils.toPositive(Utils.murmur2(serializedKey)) % numPartitions (BuiltInPartitioner.partitionForKey). Without a key, the default since KIP-480 is a sticky partitioner, refined by KIP-794 to switch partitions after batch.size bytes: good batching, no per-entity order. Inside a consumer group each partition has exactly one consumer, so the broker never splits a key across consumers; reordering comes from the producer (idempotence off + in-flight > 1), from partition-count changes, from consumer code (parallel processing, skip-and-commit, retry topics) and from mixing producers whose clients hash differently.

go
// Package kafka publishes keyed records with franz-go and consumes them with
// per-partition order kept end to end.
package kafka

import (
	"context"

	"github.com/twmb/franz-go/pkg/kgo"
)

func NewProducer(brokers ...string) (*kgo.Client, error) {
	return kgo.NewClient(
		kgo.SeedBrokers(brokers...),
		// nil hasher = exactly the Java client's mapping:
		// murmur2(key) & 0x7fffffff % numPartitions. A Java, Go and librdkafka
		// (partitioner=murmur2_random) producer then agree on the partition.
		kgo.RecordPartitioner(kgo.StickyKeyPartitioner(nil)),
		// Idempotent writes are on by default; with them up to 5 in-flight
		// requests per broker keep order. Do NOT call DisableIdempotentWrite
		// together with MaxProduceRequestsInflightPerBroker(>1): a failed and
		// retried batch can then land after a later one.
		kgo.RequiredAcks(kgo.AllISRAcks()),
	)
}

// PublishOrderEvent keys by the aggregate id: every event of one order lands
// on the same partition and keeps its order there.
func PublishOrderEvent(ctx context.Context, cl *kgo.Client, orderID string, payload []byte) error {
	rec := &kgo.Record{Topic: "orders.events", Key: []byte(orderID), Value: payload}
	return cl.ProduceSync(ctx, rec).FirstErr()
}

// CompoundKey keeps order per (tenant, order) and spreads a big tenant over
// many partitions. Order across two orders of one tenant is given up on
// purpose.
func CompoundKey(tenantID, orderID string) []byte {
	return []byte(tenantID + ":" + orderID)
}

// HotKeyPartitioner is a custom partitioner: a few known hot keys get a
// dedicated partition each, every other key is hashed exactly like Kafka's
// default. Changing this table is a key->partition remap: treat it like a
// partition-count change (drain or version-check first).
func HotKeyPartitioner(hot map[string]int) kgo.Partitioner {
	def := kgo.StickyKeyPartitioner(nil)
	return kgo.BasicConsistentPartitioner(func(topic string) func(r *kgo.Record, n int) int {
		fallback := def.ForTopic(topic)
		return func(r *kgo.Record, n int) int {
			if p, ok := hot[string(r.Key)]; ok && p < n {
				return p
			}
			return fallback.Partition(r, n)
		}
	})
}
go
package kafka

import (
	"context"
	"sync"
	"time"

	"github.com/twmb/franz-go/pkg/kgo"
)

func NewConsumer(brokers ...string) (*kgo.Client, error) {
	return kgo.NewClient(
		kgo.SeedBrokers(brokers...),
		kgo.ConsumerGroup("order-projector"),
		kgo.ConsumeTopics("orders.events"),
		// Commit only what was processed, never past an unfinished record.
		kgo.DisableAutoCommit(),
		// Do not let a rebalance move a partition while we are mid-batch.
		kgo.BlockRebalanceOnPoll(),
	)
}

// Run processes partitions concurrently and each partition sequentially:
// parallelism = number of assigned partitions, order = per partition (so per
// key). handle must be idempotent; after a crash the uncommitted tail of a
// partition is redelivered.
func Run(ctx context.Context, cl *kgo.Client, handle func(context.Context, *kgo.Record) error) error {
	for ctx.Err() == nil {
		fetches := cl.PollFetches(ctx)
		if fetches.IsClientClosed() {
			return nil
		}
		var wg sync.WaitGroup
		var mu sync.Mutex
		var done []*kgo.Record
		fetches.EachPartition(func(p kgo.FetchTopicPartition) {
			wg.Add(1)
			go func(recs []*kgo.Record) {
				defer wg.Done()
				for _, r := range recs {
					// The client's fetch position has already moved past r,
					// so "skip and come back later" would lose it. Retry in
					// place: the partition waits (head-of-line blocking),
					// order holds. Parking per key is in the retry package.
					for backoff := 100 * time.Millisecond; handle(ctx, r) != nil; backoff = min(2*backoff, 30*time.Second) {
						select {
						case <-time.After(backoff):
						case <-ctx.Done():
							return
						}
					}
					mu.Lock()
					done = append(done, r)
					mu.Unlock()
				}
			}(p.Records)
		})
		wg.Wait()
		if len(done) > 0 {
			// CommitRecords commits the highest offset per partition.
			if err := cl.CommitRecords(ctx, done...); err != nil {
				return err
			}
		}
		cl.AllowRebalance()
	}
	return ctx.Err()
}

From Laravel with mateusjunges/laravel-kafka, the Message takes a key: and withConfigOptions passes librdkafka properties. Because librdkafka's default partitioner is consistent_random (CRC32) and its idempotence default is false, set both explicitly when PHP and Go/Java producers share a topic:

php
<?php

namespace App\Messaging;

use Junges\Kafka\Facades\Kafka;
use Junges\Kafka\Message\Message;

final class UserEventPublisher
{
    /**
     * The Kafka key decides the partition, so every event of one user lands on
     * one partition and is read back in the order it was written.
     */
    public function publish(int $userId, string $kind, array $payload): void
    {
        $message = new Message(
            headers: ['event-kind' => $kind],
            body: ['user_id' => $userId, 'kind' => $kind] + $payload,
            key: (string) $userId,
        );

        Kafka::publish('broker')
            ->onTopic('user-events')
            // librdkafka defaults differ from the Java client: partitioner is
            // consistent_random (CRC32) and idempotence is off. murmur2_random
            // matches Java/franz-go, so a PHP and a Go producer send the same
            // key to the same partition; idempotence keeps retries in order.
            ->withConfigOptions([
                'partitioner' => 'murmur2_random',
                'enable.idempotence' => 'true',
                'acks' => 'all',
            ])
            ->withMessage($message)
            ->send();
    }
}

Deep dive: Kafka in Depth.

Redis Streams ​

One stream is one ordered log: entry IDs are <ms>-<seq> and monotonically increasing even if the clock goes backwards. One consumer reading it gets order; the docs: "If you use 1 stream -> 1 consumer, you are processing messages in order." A consumer group is a server-side load balancer on that one key, so per-key order across consumers is gone (the quote at the top), and the docs say the partitions in a group "are only logical". To scale while keeping order: "If you use N streams with N consumers, so that only a given consumer hits a subset of the N streams, you can scale the above model of 1 stream -> 1 consumer." The partition key is therefore yours: hash the entity id to a stream name, give each shard exactly one consumer, and keep a group only for the pending entries list (PEL) and XACK. On restart, read your own pending entries (ID 0) before new ones (>); a failed entry stays pending and must be retried before anything newer, not left for XAUTOCLAIM while you read on.

go
// Package redis shards one logical stream into N physical streams by key and
// reads each shard with exactly one consumer, which is how Redis Streams give
// per-key order with parallelism.
package redis

import (
	"context"
	"fmt"
	"hash/fnv"

	goredis "github.com/redis/go-redis/v9"
)

const shards = 8

// ShardKey maps a user to one of N stream keys. Changing the shard count
// remaps users, just like adding Kafka partitions.
func ShardKey(userID string) string {
	h := fnv.New32a()
	_, _ = h.Write([]byte(userID))
	return fmt.Sprintf("user-events:%d", h.Sum32()%shards)
}

// Add appends to the user's shard. XADD IDs are monotonically increasing
// within a stream, so the shard holds a total order of its appends.
func Add(ctx context.Context, rdb *goredis.Client, userID, kind string) error {
	return rdb.XAdd(ctx, &goredis.XAddArgs{
		Stream: ShardKey(userID),
		Values: map[string]any{"user": userID, "kind": kind},
	}).Err()
}

// ConsumeShard is run once per shard (one process owns shard i). A consumer
// group is still used for the PEL and XACK, but with ONE consumer in the
// group, so the group's load balancing never splits a user's events.
func ConsumeShard(ctx context.Context, rdb *goredis.Client, shard int, handle func(goredis.XMessage) error) error {
	stream := fmt.Sprintf("user-events:%d", shard)
	group, consumer := "projector", fmt.Sprintf("projector-%d", shard)
	if err := rdb.XGroupCreateMkStream(ctx, stream, group, "0").Err(); err != nil && err.Error() != "BUSYGROUP Consumer Group name already exists" {
		return err
	}
	// Start with "0": re-read our own pending entries first (crash recovery),
	// then switch to ">" for new ones. Pending first keeps the order.
	start := "0"
	for ctx.Err() == nil {
		res, err := rdb.XReadGroup(ctx, &goredis.XReadGroupArgs{
			Group: group, Consumer: consumer,
			Streams: []string{stream, start}, Count: 100, Block: 0,
		}).Result()
		if err != nil {
			return err
		}
		if len(res) == 0 || len(res[0].Messages) == 0 {
			start = ">"
			continue
		}
		for _, m := range res[0].Messages {
			if err := handle(m); err != nil {
				// Do not ack and do not skip: the next read of "0" returns
				// this entry again before anything newer.
				start = "0"
				break
			}
			if err := rdb.XAck(ctx, stream, group, m.ID).Err(); err != nil {
				return err
			}
		}
	}
	return ctx.Err()
}
php
<?php

namespace App\Messaging;

use Illuminate\Support\Facades\Redis;

final class RedisShard
{
    public const SHARDS = 8;

    /**
     * crc32 is stable across processes and PHP versions. Never use spl_object_id
     * or anything seeded per process. Changing SHARDS remaps users.
     */
    public static function index(string|int $key): int
    {
        return crc32((string) $key) % self::SHARDS;
    }

    public static function stream(string|int $key): string
    {
        return 'user-events:'.self::index($key);
    }

    public static function queue(string|int $key): string
    {
        return 'user-events-'.self::index($key);
    }

    /**
     * Read one shard with ONE consumer and ack after each success. Stop at the
     * first failure without acking: the entry stays pending and is read again
     * (with id '0') before anything newer. Argument order is phpredis's.
     *
     * @param  callable(string, array<string, string>): void  $handle
     */
    public static function consume(int $shard, callable $handle): void
    {
        $stream = 'user-events:'.$shard;
        $group = 'projector';
        $consumer = 'projector-'.$shard;
        $from = '0'; // own pending entries first, then '>'

        while (true) {
            $batch = Redis::xreadgroup($group, $consumer, [$stream => $from], 100, 5000);
            $entries = $batch[$stream] ?? [];

            if ($entries === []) {
                $from = '>';

                continue;
            }

            foreach ($entries as $id => $fields) {
                try {
                    $handle($id, $fields);
                } catch (\Throwable $e) {
                    report($e);
                    $from = '0';
                    sleep(1);

                    continue 2;
                }

                Redis::xack($stream, $group, [$id]);
            }
        }
    }

    /**
     * Append to the user's shard. Run one consumer per shard stream to keep
     * per-user order. Argument order is the phpredis one: key, id, fields.
     */
    public static function add(int $userId, string $kind): void
    {
        Redis::xadd(self::stream($userId), '*', [
            'user' => (string) $userId,
            'kind' => $kind,
        ]);
    }
}

In Redis Cluster, each stream key lives in one hash slot, so shards spread across nodes naturally; a hash tag like {user-events}:3 would pin them all to one node, which is the opposite of what you want here. Deep dive: Redis Streams & Pub/Sub; the data-structure side is in Redis.

In production systems ​

  • Kafka producer defaults (Java): idempotence "is enabled by default if no conflicting configurations are set"; max.in.flight.requests.per.connection default 5; with idempotence "ordering will be preserved". librdkafka differs: enable.idempotence default false, partitioner default consistent_random.
  • Kafka partition growth is documented as remapping keys with no redistribution of existing data (operations guide, "Modifying topics").
  • RabbitMQ requeue position (confirms guide): "When a message is requeued, it will be placed to its original position in its queue, if possible. If not (due to concurrent deliveries and acknowledgements from other consumers when multiple consumers share a queue), the message will be requeued to a position closer to queue head."
  • RabbitMQ quorum queues default the delivery limit to 20 since 4.0; returned messages go to a returns queue "in the exact order they were returned, regardless of their priority".
  • Redis stream IDs are monotonically increasing per stream; XADD rejects an explicit ID not greater than the last.
  • Laravel (framework source, LuaScripts.php): push rpush, pop lpop, release zadd to the delayed set; SQS FIFO groups are first-class via onGroup().

Mechanics ​

Kafka partitioner in detail: murmur2, sticky, uniform sticky, custom Important ​

With partitioner.class unset the producer uses the built-in logic: an explicit partition wins; else, if the record has a key (and partitioner.ignore.keys=false), murmur2(key) with the sign bit masked, modulo partition count; else the sticky partition. KIP-480 introduced stickiness: "By “sticking” to a partition until the batch is full (or is sent when linger.ms is up), we can create larger batches and reduce latency". KIP-794 (Kafka 3.3) fixed its skew, because the old sticky partitioner "actually distributes more records to slower brokers and can cause "runaway" problems"; the new logic switches after batch.size bytes, and partitioner.adaptive.partitioning.enable (default true) sends more to faster brokers. None of this touches keyed records. RoundRobinPartitioner ignores keys and is listed with a known unevenness issue (KAFKA-9965). A custom partitioner implements org.apache.kafka.clients.producer.Partitioner (Java) or kgo.Partitioner (franz-go); note the producer docs: partitioner.ignore.keys and the adaptive settings have "no effect if a custom partitioner is used".

RecordPartition chosen by
partition set explicitlyThat partition
Key presenttoPositive(murmur2(key)) % numPartitions
Key present, partitioner.ignore.keys=trueUniform sticky (keys ignored)
No keyUniform sticky: switch after batch.size bytes
Custom partitioner.classYour code

Client hash compatibility Important ​

The key→partition mapping is computed by the client, not the broker. Two producers on one topic that hash differently put the same key on different partitions, and order for that key is gone. franz-go documents the Java mapping precisely: murmur2, "mask out the 32nd bit", then mod; it also documents that Sarama "by default uses fnv-1a". librdkafka lists consistent_random ("CRC32 hash of key (Empty and NULL keys are randomly partitioned)") as its default and murmur2_random as "Java Producer compatible ... functionally equivalent to the default partitioner in the Java Producer".

ClientDefault key hashTo match Java
Java producer, Kafka Streamsmurmur2n/a
franz-gomurmur2 via StickyKeyPartitioner(nil) / UniformBytesPartitioner(..., keys=true, nil)Default
librdkafka (PHP rdkafka, Laravel Kafka, confluent-kafka-go, Python, .NET)CRC32 (consistent_random)partitioner=murmur2_random
Saramafnv-1aConfigure a murmur2 hasher

RabbitMQ: queue order, requeue position, SAC, delivery limit Important ​

Messages are enqueued at the tail and delivered from the head. With prefetch N, up to N deliveries are outstanding; if the consumer rejects one with requeue, it returns to its original position "if possible", else closer to the head; with one consumer and prefetch 1 that is the head. Classic queues: basic.nack/basic.reject requeue loops forever unless you count; quorum queues track x-delivery-count and dead-letter or drop at the delivery limit (default 20 since 4.0; since 4.3 only failed deliveries count, basic.nack returns do not; x-acquired-count counts acquisitions). Single active consumer: "The very first registered consumer becomes the single active consumer", others idle; on cancel or death another is chosen. On quorum queues a higher-priority consumer takes over only after the current one's unacked messages are settled, so there is no overlap. Exclusive consumers (exclusive=true on basic.consume) are the older alternative; "Quorum queues will ignore the exclusive flag".

RabbitMQ hashing exchanges and the sharding plugin Good to know ​

OptionShips asHashStable routing per keyOn queue add/removeNotes
x-modulus-hashBuilt-in exchange typeHash of routing key mod NYes, while bindings unchanged, also across restartsAlmost all keys reshuffleIgnores binding keys; bind a queue M times for weight
x-consistent-hashPlugin, ships with RabbitMQJump consistent hash (Lamping & Veach) on routing key, hash-header or hash-propertyNot guaranteed across node restartsFew keys moveBinding key = weight; one binding per queue
rabbitmq_shardingPlugin, ships with RabbitMQUses an exchange (recommended x-modulus-hash)As the exchangeNew node adds shards; old messages not rebalancedClassic non-replicated queues only; consumers attach to a pseudo-queue
Streams + filteringBuilt inn/an/an/aMany consumers of one stream, each sees the full order

Redis Streams IDs and consumer groups Good to know ​

XADD key * field value assigns <ms>-<seq>; if the clock is behind the last ID, Redis reuses the last time and bumps the sequence. XREADGROUP GROUP g c COUNT n STREAMS key > delivers entries never delivered to the group, each to one consumer, and adds them to the PEL; XREADGROUP ... STREAMS key 0 returns this consumer's own pending entries; XACK removes them. XPENDING, XCLAIM and XAUTOCLAIM move idle entries to another consumer, which is where cross-consumer reordering happens. Ack mechanics are owned by Message Acknowledgment.

Laravel queue drivers: lists, release, chains Good to know ​

Redis driver: queue queues:default is a list, pushed with rpush; pop runs a Lua script that lpops the job and zadds it to queues:default:reserved with an expiry; release($delay) removes it from reserved and zadds it to queues:default:delayed; each pop first migrates expired delayed and reserved jobs back with rpush, i.e. to the tail. Database driver: SELECT ... FOR UPDATE SKIP LOCKED ordered by id, so concurrent workers take different jobs (see Isolation Levels). Chains store the remaining jobs in the payload and dispatch the next one when the current one succeeds.

Knobs ​

ProductKnobDefaultEffect on order
Kafka producerenable.idempotencetrue (Java), false (librdkafka)On: retries do not reorder
Kafka producermax.in.flight.requests.per.connection5 (Java)> 1 with idempotence off: may reorder on retry
Kafka produceracksallRequired for idempotence
Kafka producerretries / delivery.timeout.msmax int / 120000Retries are why in-flight matters
Kafka producerpartitioner.classnull (built-in)Custom key→partition
Kafka producerpartitioner.ignore.keysfalsetrue drops per-key order
Kafka producerpartitioner.adaptive.partitioning.enabletrueUnkeyed only
librdkafkapartitionerconsistent_randomSet murmur2_random to match Java
Kafka topicpartition countset at creationChanging it remaps keys
Kafka consumerauto commit (franz-go: on unless DisableAutoCommit())onAuto commit can pass unfinished records
RabbitMQ queuex-single-active-consumerfalseOne consumer at a time
RabbitMQ queuex-max-prioritynonePriorities overtake
RabbitMQ quorumx-delivery-limit / delivery-limit policy20Poison message leaves the head
RabbitMQ channelbasic.qos prefetchunlimited> 1 + concurrency = reordering
RedisXREADGROUP ... COUNTn/aBatch size per read
Laravelqueue:work processes per queue1 per command> 1 = no order
LaravelWithoutOverlapping::releaseAfter / expireAfter0 / noneRetry spacing; lock TTL

Errors and signals you will see ​

SignalProductMeaning for order
OutOfOrderSequenceExceptionKafka Java producerBroker saw an unexpected sequence; continuing "risks reordering" (fatal for transactional)
ConfigException on startupKafka Java producerIdempotence explicitly on with conflicting settings (e.g. in-flight > 5)
redelivered=trueRabbitMQ AMQP 0-9-1This delivery may be out of its original order
x-delivery-count headerRabbitMQ quorum queuesHow many times it failed; near the limit it will leave the head
406 PRECONDITION_FAILEDRabbitMQRedeclared a queue with different arguments (e.g. toggling SAC)
BUSYGROUP Consumer Group name already existsRedisGroup already exists: safe to ignore on startup
Consumer lag on one partition onlyKafkaHot key or poison record (head-of-line)
MaxAttemptsExceededExceptionLaravelWithoutOverlapping releases used up the attempts

Solving the classic problems ​

Projection applies events out of order ​

SolutionHowAdvantageCost
Partition by aggregate idKey = customer_idOrder at the sourceHot keys, repartitioning
Version checkWHERE version < :incomingSurvives every reorderingNeeds a version from the producer
BothKey + versionDefence in depthNone worth mentioning

Code: version.Apply (Go), ApplyIfNewer (Laravel), SQL in versioning.

One failing key stalls the lane ​

SolutionHowAdvantageCost
Retry in place with backoffLoop around the handlerOrder keptLane stalls
Park the keyFailed event + later events of the key go asideOther keys flow, order keptOperator replay, storage for parked events
Dead-letter and continueDLQSimpleBreaks order for that key

Code: retry.OrderedRetrier.

A hot tenant overloads one partition ​

SolutionHowAdvantageCost
Compound keytenant:orderSpreads loadNo cross-order order inside the tenant
Dedicated partitionHotKeyPartitionerFull orderCustom partitioner
Dedicated topicRoute big tenant elsewhereIsolationMore topology

Growing the partition count safely ​

SolutionHowAdvantageCost
Over-provisionStart with enough partitions for 2–3 yearsNo migrationSome overhead
Drain then addPause producers, consumers reach the end, add partitions, resumeClean cutDowntime for the topic
New topicCreate orders.events.v2 with more partitions, dual-read with version checksNo downtimeMigration work

Needing parallelism inside one consumer ​

SolutionHowAdvantageCost
More lanes (partitions/queues)Broker-levelSimpleRepartitioning
Per-key worker poolserialiser.KeyedPoolParallel without new lanesCommit tracking

Choosing a strategy ​

SituationRecommendationExtra techniqueReason
Order lifecycle events across servicesKafka, key = order_idVersion in payload, idempotent producerPer-aggregate order is the real need
Work queue on RabbitMQ that must be per-customer orderedx-modulus-hash + N quorum queues + SACPrefetch 1 or keyed lanes, version checkStable routing per key
Redis already in place, moderate volumeN streams by hash(key) % N, one consumer eachRe-read pending firstNo partitioning built in
Laravel app, per-user sync jobsSQS FIFO onGroup("user-{id}"), or shard queues + 1 worker eachWithoutOverlapping, version checkLaravel drivers have no partition key
Fixed multi-step workflowBus::chain or a workflow engineIdempotent stepsOrder is known up front; see Durable Workflows & Jobs
Events independent of each otherPlain competing consumersIdempotencyOrder costs throughput for nothing
Ledger / balance deltasOne lane per account, sequence numbersGap detection, park on gapDeltas cannot skip versions
Cross-aggregate invariantsNot an ordering problemSaga or a transactionSee Saga Pattern

In architecture: from a single process to a distributed system ​

Monolith: one process, in-process events ​

Laravel events and listeners fired synchronously run in dispatch order in one request. The moment a listener implements ShouldQueue, it goes to the queue and order depends on workers. Simplest correct setup: one queue, one worker for order-sensitive jobs; or Bus::chain when the steps are known. Example: UserRegistered → queued SyncUserToCrm; a later UserDeleted dispatched 50 ms later can overtake it with two workers; fix with one worker on the crm queue plus a version check in the CRM sync.

Modular monolith: modules, one broker ​

Modules talk through an internal bus or one Redis/RabbitMQ instance. Key per aggregate owned by the publishing module; consumers in other modules keep their own read models with version checks. Example: the Billing module consumes orders.events keyed by order_id through an x-modulus-hash exchange with 8 SAC queues; one Billing process per queue.

Microservices ​

Order only exists per producer → lane → consumer chain. Each service publishes from an outbox (one relay per aggregate partition keeps per-key order; see Transactional Outbox) with the aggregate id as key and the aggregate version in the envelope. Consumers never assume causality across topics; they carry causation_id and wait or park when a cause is missing.

text
     Orders svc (outbox)        Kafka orders.events (key order-7)     Billing svc                   Shipping svc
1    tx: UPDATE orders v=3; INSERT outbox(OrderPaid v3)
2    relay -> produce key=order-7 ─────▶ P4 offset 812
3                                                                     apply v3 (view v2 -> v3)
4                                                                                                   reads OrderPaid v3, but its view is at v1:
5                                                                                                   gap -> park order-7 until v2 arrives

Design rules for synchronous vs asynchronous boundaries are in Service Communication and failure handling in Designing for Failure & Reliable Messaging.

Distributed data: multi-region, replication and caches ​

Order is per partition leader. Cross-region replication (MirrorMaker 2, RabbitMQ federation/shovel, Redis replication) preserves order within a replicated partition or queue but not across two regions writing the same key: two regions each producing order-7 events have two sequences with no defined merge. Rule: one home region (single writer) per key, or version vectors and merge logic. Read models behind caches must be versioned too, or a stale cache write can undo a newer one. Database replication lag has the same shape; see Replication & Failover.

Scaling path: 1×, 10×, 100× ​

LoadDesign
1× (hundreds/s)One queue/partition per ordered stream, one consumer, version checks
10×Partition by aggregate id: 12–48 Kafka partitions, or 8–16 RabbitMQ hash queues with SAC; per-key lanes inside consumers
100×Many partitions sized for the future, hot-key handling (compound keys, dedicated partitions), parking instead of blocking, migration plan for partition growth, monitoring lag per partition

Lab ​

Part A: in-process (run on the host). From docs/snippets/messaging/ordering-partitioning/go:

text
$ go test ./...
ok   academy/ordering-partitioning/after/retry        0.6s
ok   academy/ordering-partitioning/after/serialiser   0.6s

$ go run ./after/lab        # 4 keys x 5 events, 3 workers; output from a real run, counts vary per run
competing (3 workers)  applied=20 out-of-order=2
keyed lanes (3 lanes)  applied=20 out-of-order=0
first key in lane order: [{order-0 1} {order-0 2} {order-0 3} {order-0 4} {order-0 5}]
go
// Package main is the in-process half of the lab: 3 competing workers reorder
// one key's events; 3 keyed lanes do not. Run: go run ./after/lab
package main

import (
	"context"
	"fmt"
	"math/rand"
	"sort"
	"sync"
	"time"

	"academy/ordering-partitioning/after/serialiser"
)

const keys, perKey, workers = 4, 5, 3

type rec struct {
	key string
	seq int
}

// work simulates uneven processing time, like a slow downstream call.
func work(r *rand.Rand, mu *sync.Mutex) {
	mu.Lock()
	d := time.Duration(r.Intn(4)) * time.Millisecond
	mu.Unlock()
	time.Sleep(d)
}

func report(name string, out []rec) {
	last := map[string]int{}
	violations := 0
	for _, r := range out {
		if r.seq < last[r.key] {
			violations++
		}
		last[r.key] = r.seq
	}
	fmt.Printf("%-22s applied=%d out-of-order=%d\n", name, len(out), violations)
}

func main() {
	r := rand.New(rand.NewSource(7))
	var rmu, omu sync.Mutex

	// 1) Competing consumers: any worker takes the next event.
	var out []rec
	ch := make(chan rec)
	var wg sync.WaitGroup
	for w := 0; w < workers; w++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			for e := range ch {
				work(r, &rmu)
				omu.Lock()
				out = append(out, e)
				omu.Unlock()
			}
		}()
	}
	for s := 1; s <= perKey; s++ {
		for k := 0; k < keys; k++ {
			ch <- rec{fmt.Sprintf("order-%d", k), s}
		}
	}
	close(ch)
	wg.Wait()
	report("competing (3 workers)", out)

	// 2) Keyed lanes: same 3 goroutines, but a key always uses one lane.
	out = nil
	pool := serialiser.NewKeyedPool(context.Background(), workers, 8, func(_ context.Context, e serialiser.Event) {
		work(r, &rmu)
		var s int
		fmt.Sscan(string(e.Payload), &s)
		omu.Lock()
		out = append(out, rec{e.Key, s})
		omu.Unlock()
	})
	for s := 1; s <= perKey; s++ {
		for k := 0; k < keys; k++ {
			_ = pool.Submit(context.Background(), serialiser.Event{Key: fmt.Sprintf("order-%d", k), Payload: []byte(fmt.Sprint(s))})
		}
	}
	pool.Close()
	report("keyed lanes (3 lanes)", out)

	sort.SliceStable(out, func(i, j int) bool { return out[i].key < out[j].key })
	fmt.Println("first key in lane order:", out[:perKey])
}

Part B: Kafka (expected, not run). A single-node Kafka 4.x on localhost:9092.

text
1  kafka-topics.sh --bootstrap-server localhost:9092 --create --topic orders.events --partitions 3
2  for i in 1 2 3 4 5; do for k in order-0 order-1 order-2 order-3; do echo "$k:$i"; done; done \
     | kafka-console-producer.sh --bootstrap-server localhost:9092 --topic orders.events \
         --property parse.key=true --property key.separator=:
3  # three consumers in one group, one per terminal
   kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic orders.events --group lab \
     --property print.key=true --property print.partition=true
   # expected: each key appears in only ONE terminal, values 1..5 in order
4  kafka-topics.sh --bootstrap-server localhost:9092 --alter --topic orders.events --partitions 5
5  repeat step 2 with values 6..10
   # expected: some keys now appear in a second terminal/partition; within each partition still ordered,
   # but e.g. order-2:6 can print before order-2:5 if the old partition's consumer lags

Part C: RabbitMQ (expected, not run). RabbitMQ 4.x, management plugin on.

text
1  declare exchange orders.events type x-modulus-hash; queues lane.0..lane.2 with
   x-queue-type=quorum, x-single-active-consumer=true; bind each (binding key ignored)
2  start 3 consumers per queue (9 total)            -> UI shows 1 "active" + 2 "waiting" per queue
3  publish order-0..order-3 x 5 on ONE channel     -> each order id always in the same lane, in order
4  kill the active consumer of lane.1               -> a waiting one becomes active, continues in order
5  make the handler reject(requeue=true) order-1:3 three times, then succeed
                                                    -> lane.1 stalls (head-of-line), then order-1:3, :4, :5
6  repeat with x-single-active-consumer=false       -> deliveries round-robin; order-1:4 can finish before :3

Part D: Redis Streams (expected, not run).

text
1  XADD user-events:0 * user 7 kind created ; XADD user-events:0 * user 7 kind paid
2  XGROUP CREATE user-events:0 g 0
3  XREADGROUP GROUP g c1 COUNT 1 STREAMS user-events:0 >     -> created (c1)
4  XREADGROUP GROUP g c2 COUNT 1 STREAMS user-events:0 >     -> paid    (c2)  two consumers, one user: no order
5  with ONE consumer per shard: XREADGROUP GROUP g c1 COUNT 10 STREAMS user-events:0 0 -> pending first, in ID order

Common misconceptions ​

BeliefReality
"Kafka topics are ordered"Only partitions are; and only for records with the same key from a compatible partitioner
"One queue = order, regardless of consumers"Two consumers or prefetch with concurrency reorder processing
"Unique keys give the best distribution, so use the event id"They destroy per-entity order
"Adding partitions fixes a hot partition"A hot key still maps to one partition; adding partitions also remaps other keys
"Kafka moves old data when partitions are added"It does not; old records stay, new ones go elsewhere
"RabbitMQ consistent-hash gives a stable key→queue mapping"Not across node restarts; x-modulus-hash does while bindings are unchanged
"Requeue puts the message at the end"RabbitMQ puts it back at its original position if possible, else closer to the head; Laravel release() puts it at the end
"WithoutOverlapping serialises my jobs in dispatch order"It only prevents concurrency; released jobs come back later
"Idempotence is only about duplicates"In Kafka it is also what keeps retries from reordering with in-flight > 1
"All Kafka clients hash keys the same way"librdkafka defaults to CRC32, Sarama to fnv-1a, Java to murmur2
"A DLQ keeps the rest in order"Removing the head lets the next message of that key overtake it
"Timestamps are enough to order events"Clocks drift and tie; use a per-key version from the single writer
"Redis consumer groups are like Kafka partitions"Partitions there "are only logical"; shard by stream key instead

Cheat sheet ​

TopicRemember
Where order existsOne queue, one partition, one stream; nowhere else
Partition keyThe aggregate id; high cardinality; never changes
Throughput vs orderParallelism = number of lanes
Head-of-line blockingPrice of order; shrink blast radius with more lanes and parking
Kafka key mappingmurmur2(key) & 0x7fffffff % partitions
Kafka producer orderIdempotence on, acks=all, in-flight ≤ 5
librdkafkaSet partitioner=murmur2_random and enable.idempotence=true
Partition growthRemaps keys; over-provision or migrate
RabbitMQ per-keyx-modulus-hash + quorum queues + x-single-active-consumer
RabbitMQ retryReject/requeue with one consumer, prefetch 1; watch delivery limit
Redis StreamsN streams, one consumer each; re-read pending (0) first
LaravelOne worker per ordered queue; onGroup on SQS FIFO; chains for fixed steps
Consumer concurrencyPer-key lanes; commit below lowest in-flight offset
RetriesRetry in place or park the key; delay queues reorder
BackstopVersion check: WHERE version < :incoming

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — Why does a single Kafka partition give total order, and what does it cost? Must-know ​

Answer

Answer: One append-only log read by one consumer of the group: every record is in one sequence. The cost is that throughput is capped by one partition and one consumer, and any slow record blocks everything behind it.

2 — You partition orders.events by event_id. What breaks? Must-know ​

Answer

Answer: Events of the same order land on different partitions and are processed in parallel by different consumers, so paid can be applied before created. Partition by order_id.

3 — A topic has 6 partitions and one tenant produces 50% of the events, keyed by tenant_id. You raise partitions to 24. What happens? Important ​

Answer

Answer: The tenant still hashes to a single partition, so that partition still carries 50% of the load; meanwhile most other keys are remapped and can be read out of order during the switch. Use a compound key or a dedicated partition.

4 — Under which exact Kafka producer settings can retries reorder records? Important ​

Answer

Answer: enable.idempotence=false, retries enabled, and max.in.flight.requests.per.connection greater than 1: a failed first batch retried after a successful second batch lands behind it.

5 — A Go producer (franz-go) and a Laravel producer (laravel-kafka) write the same keys to one topic. What must you configure? Important ​

Answer

Answer: librdkafka's partitioner=murmur2_random (its default is CRC32 consistent_random), so both clients map a key to the same partition; and enable.idempotence=true because librdkafka defaults it to false.

6 — On RabbitMQ, why is x-modulus-hash preferred over x-consistent-hash for ordering? Good to know ​

Answer

Answer: x-modulus-hash guarantees the same routing key goes to the same queue as long as bindings are unchanged, even across node restarts. The consistent-hash ring is rebuilt in memory on restart and "cannot guarantee stable queue routing locality".

7 — Your consumer keeps failing on one message. You send it to a DLQ after 5 tries and continue. What is the ordering risk, and the alternative? Must-know ​

Answer

Answer: The next message for the same key is processed before the failed one (it overtakes). Park the key instead: hold the failed message and all later messages for that key aside, keep other keys flowing, replay the key in order later.

8 — Two Redis Streams consumers in one group read user-events. Is per-user order preserved? Important ​

Answer

Answer: No. The group load-balances entries to whichever consumer is ready. Shard into N streams by user and give each stream exactly one consumer.

9 — Why is WithoutOverlapping not an ordering guarantee in Laravel? Important ​

Answer

Answer: It is a lock: a job that finds the lock taken is released, which puts it in the delayed set and later at the back of the list, so a younger job can run first. It prevents concurrency, not reordering.

10 — Your consumer processes keys in parallel with per-key lanes. Offsets 100 (key A) and 101 (key B) are in flight; 101 finishes first. What do you commit? Important ​

Answer

Answer: Nothing beyond 100: the commit point is the lowest unfinished offset. Committing 102 would lose record 100 on a crash.

11 — When is a version check not enough? Good to know ​

Answer

Answer: For delta events (+10) or commands, where skipping a version changes the result. You need gap detection and to wait or park until the missing version arrives.

Glossary ​

TermMeaning
Total (global) orderOne sequence for every message in a channel
Per-key orderSequence guaranteed only among messages with the same key
Causal orderEffects never seen before their causes (happened-before)
LaneAny ordered unit: queue, partition, stream
PartitionKafka's ordered, append-only sub-log of a topic
Partition key / message keyField hashed to choose a lane
Key cardinalityNumber of distinct key values
Hot keyOne key whose traffic exceeds one lane's capacity
Key skewUneven message count per key
Compound keyKey built from several fields, e.g. tenant:order
Key saltingAppending a suffix to spread one key; gives up its order
Head-of-line blockingItems behind the head wait for it
Poison messageA message that fails every time it is processed
Park the keyMove a failed message and all later ones for its key aside, in order
RepartitioningChanging lane count, remapping keys
murmur2Hash used by the Java Kafka producer for keys
Sticky partitionerKIP-480: unkeyed records stick to one partition per batch
Uniform sticky partitionerKIP-794: switch after batch.size bytes; adaptive to broker speed
Custom partitionerUser code choosing the partition (Partitioner, kgo.Partitioner)
max.in.flight.requests.per.connectionUnacknowledged produce requests per connection
Idempotent producerProducer id + sequence numbers; no duplicates, no reorder on retry
OutOfOrderSequenceExceptionKafka error for an unexpected producer sequence number
Single active consumer (SAC)RabbitMQ: one consumer at a time per queue, automatic failover
x-modulus-hashBuilt-in RabbitMQ exchange: hash(routing key) mod N, stable routing
Consistent-hash exchangeRabbitMQ plugin exchange using a hash ring; weights via binding key
Sharding pluginRabbitMQ plugin creating shard queues behind a pseudo-queue
RequeueReturn a delivery to the queue (basic.reject/basic.nack with requeue=true)
Delivery limitQuorum queue cap on failed deliveries (default 20)
Consumer group (Redis)Server-side load balancer over one stream with a PEL
PELPending entries list: delivered, not yet acked
Per-key worker poolKeyed executor: hash → channel → one goroutine
ResequencerEIP pattern buffering out-of-order messages to emit them in sequence
Sequence number / event versionPer-key monotonic counter from the single writer
Gap detectionNoticing a missing version before applying a later one
Message group (SQS FIFO)Key for sequential processing; Laravel onGroup()
Job chainLaravel Bus::chain: next job only after the previous succeeded
WithoutOverlappingLaravel middleware: lock per key, no ordering

References ​

Built by Morteza Negahi