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 for | Go to |
|---|---|
| The whole topic in three small tables | Everything in one minute |
| Why order is expensive and global order does not scale | Why 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 order | What "ordered" can mean |
| Partition keys, hot keys, head-of-line blocking, repartitioning, producer and consumer order, retries, versions | The concepts, one by one |
| Go code: keyed worker pool, ordered retry, version check | Go |
Laravel code: WithoutOverlapping, chains, SQS FIFO groups, shard queues | Laravel |
| RabbitMQ, Kafka and Redis Streams side by side | Broker differences |
| murmur2, sticky partitioner, client hash compatibility, requeue position, Laravel's lists | Mechanics |
| Every knob and every error you will meet | Knobs, Errors and signals |
| Out-of-order projections, stuck keys, hot tenants, growing partitions | Solving the classic problems |
| Which design for which situation | Choosing a strategy |
| From one process to multi-region | In architecture |
| Reproduce reordering and the fix | Lab |
| Wrong beliefs, cheat sheet, every term defined | Misconceptions, Cheat sheet, Glossary |
Everything in one minute
Kinds of order. Each row is unpacked in What "ordered" can mean.
| Kind | In plain words | Tiny example | Who provides it |
|---|---|---|---|
| Total (global) order | Every message in one sequence | One queue, one consumer | One RabbitMQ queue + one consumer; one Kafka partition; one Redis stream + one reader |
| Per-key order | Messages with the same key stay in sequence; different keys interleave | order-7: created → paid → shipped | Kafka partition by key; RabbitMQ hashing exchange + single active consumer per queue; Redis stream per shard; SQS FIFO message group |
| Causal order | If B was caused by A, everyone sees A before B | A reply never before its question | No broker; you carry causality (same key, or version / vector metadata) |
| No order | Any order | Thumbnails for unrelated uploads | Any competing-consumer queue |
What breaks order, and where.
| Event | RabbitMQ | Kafka | Redis Streams | Laravel queue |
|---|---|---|---|---|
| Two consumers on one lane | Yes: completion order is arbitrary | Impossible inside a group (one consumer per partition) | Yes: consumer group load-balances one stream | Yes: N workers pop one list |
| Producer retry | Only across channels / connections | Yes if idempotence is off and in-flight > 1 | No (XADD is one command) | No |
| Consumer retry / requeue | Requeue goes back to original position "if possible"; other consumers may have moved on | Only if you skip or re-produce the record | Pending entry redelivered later via XCLAIM / XAUTOCLAIM | release() puts the job at the back |
| DLQ replay | Yes | Yes | Yes | queue:retry re-pushes at the back |
| Changing lane count | x-modulus-hash: most keys move; consistent-hash: few keys move | Adding partitions remaps hash % N | Changing shard count remaps keys | Changing shard queue count remaps keys |
| Priorities | Higher priority overtakes | n/a | n/a | --queue=high,default overtakes |
Fix menu.
| Problem | First fix | Backstop |
|---|---|---|
| Related messages processed in parallel | Partition by aggregate id; one consumer per lane | Version check in the consumer |
| Need parallelism inside one consumer | Per-key worker lanes (hash → channel → one goroutine) | Commit only below the lowest offset in flight |
| Failing message for one key | Retry in place, then park the key | Operator replay of the parked key in order |
| Producer retries reorder | Kafka idempotent producer (default on in Java and franz-go, off in librdkafka) | Sequence numbers in the payload |
| Hot key | Compound key, or a dedicated lane | Accept the lane is a bottleneck; scale that consumer vertically |
| Partition count must grow | Over-provision up front | New 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 order | Choose parallelism |
|---|---|
| One lane, one reader | Many lanes, many readers |
| Simple reasoning: state machines just work | Throughput 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 consumer | Ceiling = lanes × consumer speed |
| No reordering by the broker | Order 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
- "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.
- "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.
- "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.
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.
| Broker | How to get total order | Price |
|---|---|---|
| RabbitMQ | One queue, x-single-active-consumer: true, prefetch 1 if handlers can fail; or a stream | One consumer's throughput |
| Kafka | One partition | One partition's write and read throughput; one consumer |
| Redis Streams | One stream, one reader (no group, or a group with one consumer) | One consumer; one Redis shard |
| Laravel | One queue, one queue:work process | One 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.
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 orderReal 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).
| Broker | Per-key primitive |
|---|---|
| Kafka | Record key → partition (built in) |
| RabbitMQ | x-modulus-hash or x-consistent-hash exchange → N queues, each with single active consumer |
| Redis Streams | You shard: hash(key) % N → stream name; one consumer per stream |
| Laravel | SQS FIFO onGroup(); or one queue per shard with one worker each |
| Amazon SQS FIFO | Message group ID |
| NATS JetStream, Pulsar | Subject-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.
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.
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 firstFix: 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
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:
| Question | Good answer | Why |
|---|---|---|
| Whose events must be in order? | The aggregate id: order_id, account_id, device_id | DDD 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 traffic | One 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 order | Coarser key = more order, less parallelism |
| Will the key ever change for an entity? | Never | Changing keys splits an entity's history across lanes |
| Can every producer compute it the same way? | Same bytes, same hash function | See 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."
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)| Remedy | How | Order you keep | Cost |
|---|---|---|---|
| Finer compound key | tenant:order instead of tenant | Per order | No order across one tenant's orders |
| Dedicated lane | Custom partitioner pins the hot key to its own partition | Full order for the hot key | A partitioner to maintain; remap when the table changes |
| Key salting | key#0..key#7 round-robin | None for that key | Consumer must re-merge (Resequencer) or not care |
| Separate topic / queue | Big tenant gets its own channel | Full | More topology |
| Faster single consumer | Batch writes, bigger instance for that lane | Full | Vertical limit |
Fix in code: HotKeyPartitioner and CompoundKey in produce.go.
Head-of-line blocking Must-know
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.
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.
| Strategy | Order for the failing key | Other keys in the lane | Use when |
|---|---|---|---|
| Retry in place forever | Kept | Blocked | The failure is global (DB down) and will pass |
| Retry in place N times, then dead-letter | Broken (next message overtakes) | Freed | Messages are independent after all |
| Retry in place N times, then park the key | Kept | Freed | Per-key state machines, ledgers |
| More lanes | Kept | Fewer keys per lane | Always helps the blast radius |
| Per-key lanes inside the consumer | Kept | Only same-lane keys wait | You 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.
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| Product | What remaps | Built-in help |
|---|---|---|
| Kafka | All keyed producers once they see new metadata | None; plan partitions up front |
RabbitMQ x-modulus-hash | "the routing for almost all keys will be reshuffled" when queues are added or removed | Stable as long as bindings stay the same, even across restarts |
RabbitMQ x-consistent-hash | Few keys on bind/unbind; may also move after a node restart | Minimal movement, no locality guarantee |
| Redis Streams (your sharding) | Whatever your % N does | None |
| Laravel shard queues | Whatever your crc32 % N does | None |
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."
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| Client | Default partitioner | Idempotence default | In-flight default |
|---|---|---|---|
| Java producer | murmur2 for keys; sticky (KIP-480/794) without a key | true (if no conflicting config) | 5 |
| franz-go | UniformBytesPartitioner family; StickyKeyPartitioner(nil) = Java's key hashing | On (DisableIdempotentWrite() to turn off) | 5 with idempotence; 1 without, unless MaxProduceRequestsInflightPerBroker |
| librdkafka (php-rdkafka, Laravel Kafka, confluent-kafka-go) | consistent_random (CRC32) | false | 1000000 |
| RabbitMQ publisher | n/a | n/a: one channel is ordered | Publisher confirms do not reorder a channel |
| Redis XADD | n/a | n/a | Each 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
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.
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| Concern | Rule |
|---|---|
| Hash | Stable across restarts and languages (hash/fnv, crc32); never Go map order or a per-process seed |
| Channel size | Bounded; a full lane blocks the dispatcher: backpressure, see Backpressure & Flow Control |
| Commit / ack | Only below the lowest unfinished offset (Kafka); RabbitMQ: ack each delivery when its lane finished it, never multiple=true past an unfinished one |
| Prefetch | RabbitMQ prefetch > 1 is fine only with keyed lanes inside; with free goroutines it reorders |
| Rebalance | Drain lanes before giving up a partition (franz-go BlockRebalanceOnPoll + AllowRebalance) |
| Shutdown | Stop 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.
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"| Mechanism | Reorders? | Notes |
|---|---|---|
RabbitMQ basic.reject/basic.nack with requeue | Usually 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 returns | Returns go to a returns queue "in the exact order they were returned" | Redelivered before the rest; delivery limit default 20 |
| RabbitMQ TTL + DLX delay queue | Yes | A different queue |
| Kafka retry topic / DLQ topic | Yes | A 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 later | Yes, if the consumer kept reading > | Re-read pending (ID 0) first to keep order |
Laravel release($delay) / failed job + queue:retry | Yes | Released jobs go to the delayed sorted set, then rpush to the back |
| In-place retry with backoff | No | Head-of-line blocking |
| Park the key | No | All 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.
-- 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 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 style | Version check enough? | Extra |
|---|---|---|
| Full-state snapshot ("customer is now X") | Yes | None |
| Delta ("balance +10") | No | Gap detection, park until missing version |
| Command-like ("ship order") | No | State 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.
// 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.
// 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):
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.
// 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
}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.
// 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:
// 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
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
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
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
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:
| Tool | What it gives | What it does not |
|---|---|---|
Bus::chain([...]) | Strict sequence of known steps: "run in sequence after the primary job has executed successfully"; stops on failure | Order 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 shard | Per-key FIFO on redis/database | Survives release(): no, a released job still goes to the back |
ShouldBeUnique | At most one queued instance per key | Order |
| Version column + conditional update | Correct final state whatever the order | Delta 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
| Question | RabbitMQ | Kafka | Redis Streams |
|---|---|---|---|
| Unit of order | Queue (or stream) | Partition | Stream key |
| Key → lane | x-modulus-hash (built in), x-consistent-hash (plugin), sharding plugin | Record key, murmur2 % partitions | Your code: hash(key) % N → stream name |
| One reader per lane | x-single-active-consumer: true (or one consumer) | Automatic inside a consumer group | You assign shards to consumers |
| Failover keeps order? | Yes: SAC promotes a standby | Yes: partition moves to another group member at the committed offset | Yes, if the new owner re-reads the pending list first |
| Retry without reordering | Reject/nack requeue with one consumer, prefetch 1 | Retry in place; do not commit past | Do not XACK; re-read ID 0 |
| Lane count change | Modulus: most keys move; consistent hash: few | Adding partitions remaps keys | Your remap |
| Priorities break order | Yes | n/a | n/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.
// 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,
})
}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.
// 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)
}
})
}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
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.
// 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
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.connectiondefault 5; with idempotence "ordering will be preserved". librdkafka differs:enable.idempotencedefaultfalse,partitionerdefaultconsistent_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;
XADDrejects an explicit ID not greater than the last. - Laravel (framework source,
LuaScripts.php): pushrpush, poplpop, releasezaddto the delayed set; SQS FIFO groups are first-class viaonGroup().
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".
| Record | Partition chosen by |
|---|---|
partition set explicitly | That partition |
| Key present | toPositive(murmur2(key)) % numPartitions |
Key present, partitioner.ignore.keys=true | Uniform sticky (keys ignored) |
| No key | Uniform sticky: switch after batch.size bytes |
Custom partitioner.class | Your 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".
| Client | Default key hash | To match Java |
|---|---|---|
| Java producer, Kafka Streams | murmur2 | n/a |
| franz-go | murmur2 via StickyKeyPartitioner(nil) / UniformBytesPartitioner(..., keys=true, nil) | Default |
librdkafka (PHP rdkafka, Laravel Kafka, confluent-kafka-go, Python, .NET) | CRC32 (consistent_random) | partitioner=murmur2_random |
| Sarama | fnv-1a | Configure 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
| Option | Ships as | Hash | Stable routing per key | On queue add/remove | Notes |
|---|---|---|---|---|---|
x-modulus-hash | Built-in exchange type | Hash of routing key mod N | Yes, while bindings unchanged, also across restarts | Almost all keys reshuffle | Ignores binding keys; bind a queue M times for weight |
x-consistent-hash | Plugin, ships with RabbitMQ | Jump consistent hash (Lamping & Veach) on routing key, hash-header or hash-property | Not guaranteed across node restarts | Few keys move | Binding key = weight; one binding per queue |
rabbitmq_sharding | Plugin, ships with RabbitMQ | Uses an exchange (recommended x-modulus-hash) | As the exchange | New node adds shards; old messages not rebalanced | Classic non-replicated queues only; consumers attach to a pseudo-queue |
| Streams + filtering | Built in | n/a | n/a | n/a | Many 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
| Product | Knob | Default | Effect on order |
|---|---|---|---|
| Kafka producer | enable.idempotence | true (Java), false (librdkafka) | On: retries do not reorder |
| Kafka producer | max.in.flight.requests.per.connection | 5 (Java) | > 1 with idempotence off: may reorder on retry |
| Kafka producer | acks | all | Required for idempotence |
| Kafka producer | retries / delivery.timeout.ms | max int / 120000 | Retries are why in-flight matters |
| Kafka producer | partitioner.class | null (built-in) | Custom key→partition |
| Kafka producer | partitioner.ignore.keys | false | true drops per-key order |
| Kafka producer | partitioner.adaptive.partitioning.enable | true | Unkeyed only |
| librdkafka | partitioner | consistent_random | Set murmur2_random to match Java |
| Kafka topic | partition count | set at creation | Changing it remaps keys |
| Kafka consumer | auto commit (franz-go: on unless DisableAutoCommit()) | on | Auto commit can pass unfinished records |
| RabbitMQ queue | x-single-active-consumer | false | One consumer at a time |
| RabbitMQ queue | x-max-priority | none | Priorities overtake |
| RabbitMQ quorum | x-delivery-limit / delivery-limit policy | 20 | Poison message leaves the head |
| RabbitMQ channel | basic.qos prefetch | unlimited | > 1 + concurrency = reordering |
| Redis | XREADGROUP ... COUNT | n/a | Batch size per read |
| Laravel | queue:work processes per queue | 1 per command | > 1 = no order |
| Laravel | WithoutOverlapping::releaseAfter / expireAfter | 0 / none | Retry spacing; lock TTL |
Errors and signals you will see
| Signal | Product | Meaning for order |
|---|---|---|
OutOfOrderSequenceException | Kafka Java producer | Broker saw an unexpected sequence; continuing "risks reordering" (fatal for transactional) |
ConfigException on startup | Kafka Java producer | Idempotence explicitly on with conflicting settings (e.g. in-flight > 5) |
redelivered=true | RabbitMQ AMQP 0-9-1 | This delivery may be out of its original order |
x-delivery-count header | RabbitMQ quorum queues | How many times it failed; near the limit it will leave the head |
406 PRECONDITION_FAILED | RabbitMQ | Redeclared a queue with different arguments (e.g. toggling SAC) |
BUSYGROUP Consumer Group name already exists | Redis | Group already exists: safe to ignore on startup |
| Consumer lag on one partition only | Kafka | Hot key or poison record (head-of-line) |
MaxAttemptsExceededException | Laravel | WithoutOverlapping releases used up the attempts |
Solving the classic problems
Projection applies events out of order
| Solution | How | Advantage | Cost |
|---|---|---|---|
| Partition by aggregate id | Key = customer_id | Order at the source | Hot keys, repartitioning |
| Version check | WHERE version < :incoming | Survives every reordering | Needs a version from the producer |
| Both | Key + version | Defence in depth | None worth mentioning |
Code: version.Apply (Go), ApplyIfNewer (Laravel), SQL in versioning.
One failing key stalls the lane
| Solution | How | Advantage | Cost |
|---|---|---|---|
| Retry in place with backoff | Loop around the handler | Order kept | Lane stalls |
| Park the key | Failed event + later events of the key go aside | Other keys flow, order kept | Operator replay, storage for parked events |
| Dead-letter and continue | DLQ | Simple | Breaks order for that key |
Code: retry.OrderedRetrier.
A hot tenant overloads one partition
| Solution | How | Advantage | Cost |
|---|---|---|---|
| Compound key | tenant:order | Spreads load | No cross-order order inside the tenant |
| Dedicated partition | HotKeyPartitioner | Full order | Custom partitioner |
| Dedicated topic | Route big tenant elsewhere | Isolation | More topology |
Growing the partition count safely
| Solution | How | Advantage | Cost |
|---|---|---|---|
| Over-provision | Start with enough partitions for 2–3 years | No migration | Some overhead |
| Drain then add | Pause producers, consumers reach the end, add partitions, resume | Clean cut | Downtime for the topic |
| New topic | Create orders.events.v2 with more partitions, dual-read with version checks | No downtime | Migration work |
Needing parallelism inside one consumer
| Solution | How | Advantage | Cost |
|---|---|---|---|
| More lanes (partitions/queues) | Broker-level | Simple | Repartitioning |
| Per-key worker pool | serialiser.KeyedPool | Parallel without new lanes | Commit tracking |
Choosing a strategy
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| Order lifecycle events across services | Kafka, key = order_id | Version in payload, idempotent producer | Per-aggregate order is the real need |
| Work queue on RabbitMQ that must be per-customer ordered | x-modulus-hash + N quorum queues + SAC | Prefetch 1 or keyed lanes, version check | Stable routing per key |
| Redis already in place, moderate volume | N streams by hash(key) % N, one consumer each | Re-read pending first | No partitioning built in |
| Laravel app, per-user sync jobs | SQS FIFO onGroup("user-{id}"), or shard queues + 1 worker each | WithoutOverlapping, version check | Laravel drivers have no partition key |
| Fixed multi-step workflow | Bus::chain or a workflow engine | Idempotent steps | Order is known up front; see Durable Workflows & Jobs |
| Events independent of each other | Plain competing consumers | Idempotency | Order costs throughput for nothing |
| Ledger / balance deltas | One lane per account, sequence numbers | Gap detection, park on gap | Deltas cannot skip versions |
| Cross-aggregate invariants | Not an ordering problem | Saga or a transaction | See 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.
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 arrivesDesign 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×
| Load | Design |
|---|---|
| 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:
$ 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}]// 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.
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 lagsPart C: RabbitMQ (expected, not run). RabbitMQ 4.x, management plugin on.
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 :3Part D: Redis Streams (expected, not run).
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 orderCommon misconceptions
| Belief | Reality |
|---|---|
| "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
| Topic | Remember |
|---|---|
| Where order exists | One queue, one partition, one stream; nowhere else |
| Partition key | The aggregate id; high cardinality; never changes |
| Throughput vs order | Parallelism = number of lanes |
| Head-of-line blocking | Price of order; shrink blast radius with more lanes and parking |
| Kafka key mapping | murmur2(key) & 0x7fffffff % partitions |
| Kafka producer order | Idempotence on, acks=all, in-flight ≤ 5 |
| librdkafka | Set partitioner=murmur2_random and enable.idempotence=true |
| Partition growth | Remaps keys; over-provision or migrate |
| RabbitMQ per-key | x-modulus-hash + quorum queues + x-single-active-consumer |
| RabbitMQ retry | Reject/requeue with one consumer, prefetch 1; watch delivery limit |
| Redis Streams | N streams, one consumer each; re-read pending (0) first |
| Laravel | One worker per ordered queue; onGroup on SQS FIFO; chains for fixed steps |
| Consumer concurrency | Per-key lanes; commit below lowest in-flight offset |
| Retries | Retry in place or park the key; delay queues reorder |
| Backstop | Version check: WHERE version < :incoming |
Self-check: questions & answers
- 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
| Term | Meaning |
|---|---|
| Total (global) order | One sequence for every message in a channel |
| Per-key order | Sequence guaranteed only among messages with the same key |
| Causal order | Effects never seen before their causes (happened-before) |
| Lane | Any ordered unit: queue, partition, stream |
| Partition | Kafka's ordered, append-only sub-log of a topic |
| Partition key / message key | Field hashed to choose a lane |
| Key cardinality | Number of distinct key values |
| Hot key | One key whose traffic exceeds one lane's capacity |
| Key skew | Uneven message count per key |
| Compound key | Key built from several fields, e.g. tenant:order |
| Key salting | Appending a suffix to spread one key; gives up its order |
| Head-of-line blocking | Items behind the head wait for it |
| Poison message | A message that fails every time it is processed |
| Park the key | Move a failed message and all later ones for its key aside, in order |
| Repartitioning | Changing lane count, remapping keys |
| murmur2 | Hash used by the Java Kafka producer for keys |
| Sticky partitioner | KIP-480: unkeyed records stick to one partition per batch |
| Uniform sticky partitioner | KIP-794: switch after batch.size bytes; adaptive to broker speed |
| Custom partitioner | User code choosing the partition (Partitioner, kgo.Partitioner) |
max.in.flight.requests.per.connection | Unacknowledged produce requests per connection |
| Idempotent producer | Producer id + sequence numbers; no duplicates, no reorder on retry |
OutOfOrderSequenceException | Kafka error for an unexpected producer sequence number |
| Single active consumer (SAC) | RabbitMQ: one consumer at a time per queue, automatic failover |
x-modulus-hash | Built-in RabbitMQ exchange: hash(routing key) mod N, stable routing |
| Consistent-hash exchange | RabbitMQ plugin exchange using a hash ring; weights via binding key |
| Sharding plugin | RabbitMQ plugin creating shard queues behind a pseudo-queue |
| Requeue | Return a delivery to the queue (basic.reject/basic.nack with requeue=true) |
| Delivery limit | Quorum queue cap on failed deliveries (default 20) |
| Consumer group (Redis) | Server-side load balancer over one stream with a PEL |
| PEL | Pending entries list: delivered, not yet acked |
| Per-key worker pool | Keyed executor: hash → channel → one goroutine |
| Resequencer | EIP pattern buffering out-of-order messages to emit them in sequence |
| Sequence number / event version | Per-key monotonic counter from the single writer |
| Gap detection | Noticing a missing version before applying a later one |
| Message group (SQS FIFO) | Key for sequential processing; Laravel onGroup() |
| Job chain | Laravel Bus::chain: next job only after the previous succeeded |
WithoutOverlapping | Laravel middleware: lock per key, no ordering |
References
- Redis, "Redis Streams" (consumer groups; "Differences with Kafka (TM) partitions"). redis.io
- Apache Kafka 4.2, Introduction (event keys and partition order). kafka.apache.org
- Apache Kafka 4.2, Producer Configs (
enable.idempotence,max.in.flight.requests.per.connection,retries,partitioner.*). kafka.apache.org - Apache Kafka 4.2, Basic Kafka Operations, "Modifying topics". kafka.apache.org
- Apache Kafka 4.2, Design (idempotent producer, sequence numbers). kafka.apache.org
- Apache Kafka javadoc,
OutOfOrderSequenceException. kafka.apache.org - Apache Kafka source,
BuiltInPartitioner.java. github.com - KIP-480: Sticky Partitioner. cwiki.apache.org
- KIP-794: Strictly Uniform Sticky Partitioner. cwiki.apache.org
- librdkafka,
CONFIGURATION.md(partitioner,enable.idempotence). github.com - franz-go,
pkg/kgo/partitioner.goandconfig.go. github.com, config.go - RabbitMQ, "Queues" (message ordering). rabbitmq.com, source github.com
- RabbitMQ, "Consumers" (single active consumer). rabbitmq.com
- RabbitMQ, "Consumer Acknowledgements and Publisher Confirms" (requeue position). github.com
- RabbitMQ, "Quorum Queues" (delivery limit, returned messages). github.com
- RabbitMQ, "Modulus Hash Exchange". github.com
- RabbitMQ Consistent Hash Exchange README. github.com
- RabbitMQ Sharding Plugin README. github.com
- Hohpe & Woolf, Enterprise Integration Patterns, Resequencer. enterpriseintegrationpatterns.com
- Laravel 13, Queues (
WithoutOverlapping, job chaining, SQS FIFO and fair queues). laravel.com - Laravel framework 13.x source,
Illuminate/Queue/LuaScripts.php. github.com - Laravel Kafka (
mateusjunges/laravel-kafka): publishing, message payload - Go packages: amqp091-go, go-redis