Full answer
The problem
- With a shared queue and N workers, messages are taken in order but finish in any order. "Update email" followed by "delete account" can run backwards.
- Retries also break order: message 1 fails and is retried after message 2 has succeeded.
Partitioning
- The producer computes partition = hash(key) mod partitionCount. All messages with the same key land in the same partition, which keeps their order. Each partition is read by one consumer at a time in a consumer group, one message after another.
- Throughput scales with the number of partitions, and a hot key can overload one partition.
- Changing the partition count changes the mapping, so plan it in advance.
Practical rules
- Define what really needs order: per entity (one order's events), almost never global.
- Make consumers tolerant: put a version or sequence number in each message and ignore messages older than the stored version. This also handles duplicates and late arrivals.
- A failing message in a partition blocks later messages for that key (head of line blocking). Decide: pause, retry with limits, or move it aside to a DLQ and accept the order impact.
- Use idempotent consumers, because redelivery after a crash replays a partition from the last committed offset.
javascript
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const events = [
{ key: 'account-1', seq: 1, ms: 240, name: 'create' },
{ key: 'account-1', seq: 2, ms: 40, name: 'rename' },
{ key: 'account-2', seq: 1, ms: 80, name: 'create' },
{ key: 'account-1', seq: 3, ms: 20, name: 'delete' },
];
const handle = async (e, log) => { await sleep(e.ms); log.push(e); };
const perKey = (log) => Object.entries(log.reduce((acc, e) => ((acc[e.key] ??= []).push(e.seq), acc), {})).map(([k, v]) => `${k}: ${v.join(',')}`).join(' | ');
(async () => {
// 1. One shared queue, three parallel workers.
const shared = [...events], log1 = [];
await Promise.all(Array.from({ length: 3 }, async () => { while (shared.length) await handle(shared.shift(), log1); }));
console.log('shared queue, 3 workers ->', perKey(log1), '(account-1 is out of order)');
// 2. Partitioned by key: each partition is processed one message at a time.
const partitionCount = 3;
const hash = (key) => [...key].reduce((h, c) => h + c.charCodeAt(0), 0) % partitionCount;
const partitions = Array.from({ length: partitionCount }, () => []);
events.forEach((e) => partitions[hash(e.key)].push(e));
const log2 = [];
await Promise.all(partitions.map(async (list) => { for (const e of list) await handle(e, log2); }));
console.log('partitioned by key ->', perKey(log2), '(in order per key)');
console.log('same key, same partition:', hash('account-1') === hash('account-1'), '| partitions used:', partitions.filter((p) => p.length).length);
// 3. A sequence number makes consumers safe against old messages.
const stored = { version: 0 };
const apply = (e) => (e.seq > stored.version ? ((stored.version = e.seq), 'applied') : 'ignored (older or duplicate)');
console.log('apply seq 2, then 1, then 2 again:', [2, 1, 2].map((seq) => apply({ seq })).join(' | '));
})();Real timers with 20 ms or more between the finishing times, so the order of completion is stable. Kafka and SQS FIFO implement the partition idea inside the broker. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): shared queue, 3 workers -> account-1: 2,3,1 | account-2: 1 (account-1 is out of order) partitioned by key -> account-2: 1 | account-1: 1,2,3 (in order per key) same key, same partition: true | partitions used: 2 apply seq 2, then 1, then 2 again: applied | ignored (older or duplicate) | ignored (older or duplicate)
Key points
- Parallel consumers on one queue do not keep order.
- A partition key keeps order per entity and allows parallelism across entities.
- A partition is processed sequentially by one consumer.
- Sequence numbers let consumers detect old or duplicate messages.
- A failing message can block its partition.
Common mistakes
- Expecting a global order from a parallel system.
- Using a random or missing partition key.
- A hot key that sends most traffic to one partition.
- Changing the partition count without a plan.
- Letting a retry jump over later messages of the same key.
Follow-ups
- How do SQS FIFO message groups work?
- What is head-of-line blocking?
- How would you handle ordering across two different keys?
Tips
- State the guarantee per key.
- Explain why parallel workers reorder.
- Mention version numbers.