SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
  • Message Queues
  • Pub/Sub
  • Message Brokers
  • Delivery Semantics
  • Dead Letter Queues
  • Kafka Deep Dive
  • Retries with Backoff
  • RabbitMQ and SQS
  • Event Streaming vs Message Queues
  • Message Ordering
  • Task Queues, Workers and Scheduled Jobs
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/APIs and Communication/Asynchronous Communication

Message Ordering

When order matters, how to keep it, and what it costs in speed.

⏱ 13 min readAdvancedInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

Message ordering is about one question: will messages be handled in the same order they were sent? In a distributed system the honest answer is usually "only inside one lane".

  • There is no free global order across many queues, partitions or workers.
  • Order is normally kept per key: all messages of one order, user or account stay in sequence.
  • More parallel workers means more speed but less order. You choose where to draw the line.

02Concept: What is it?

In one program with one thread, order is easy: first in, first out. In a distributed system, messages travel over networks with different delays, are split over several queues or partitions, and are picked up by several workers at the same time. Any of these can swap the order.

How order gets lost
📨1: create order
📨2: update order
→↓two workers
🐢Worker 1handles 1, slow
🐇Worker 2handles 2, fast
→↓database sees
⚠️2 then 1update before create!
Message 1 is slow (a retry, a busy worker, a long network path), so message 2 finishes first.

What can reorder messages

CauseWhat happens
Several consumers in parallelA fast worker finishes a later message before a slow worker finishes an earlier one
RetriesA failed message is tried again later, after newer messages were already handled
Several queues or partitionsEach lane has its own order, with none between lanes
Network delaysMessages take different routes or are resent, and arrive out of sequence
Multiple producersTwo senders have no shared clock, so “first” may not even be defined
🧠The usual rule
A system typically guarantees order only within one partition, queue or message group. Everything else is your job to design for.

03Real-Life Example

🍵A bank statement
A customer deposits 100, then withdraws 80. If the bank processes the withdrawal first, the account looks overdrawn for a moment and a fee may be charged. The order of two events for the same account matters a lot. But the order between two different customers does not matter at all. So the bank gives each account its own queue (a lane), keeps each lane in order, and runs many lanes at the same time.
Bank
Messaging system
One account's transactions, in order
All messages with the same key
A separate lane for each account
A partition or message group per key
One clerk per lane
One consumer per partition
Many lanes open at once
Parallelism across keys
Transaction numbers on every slip
Sequence numbers or versions
Ignoring a slip older than one already booked
Dropping stale messages
Order per key, parallel across keys
📨EventsA1 B1 A2 C1 B2 A3
→↓hash the key
🛤️Lane 1: A1 A2 A3
🛤️Lane 2: B1 B2
🛤️Lane 3: C1
→↓one worker each
✅Each key in orderkeys run in parallel

04Why Do We Need It?

🧮Correct state
Applying events in the wrong order leaves wrong data: a deleted record that comes back, or an old price that wins.
💳Money and counts
Deposits, withdrawals and stock changes depend on sequence to stay valid.
🔗Cause and effect
“Create” must come before “update”, and “order placed” before “order shipped”.
🪞Replicas that agree
Copies of data that apply changes in the same order end up equal.
🚦A fair speed trade
Knowing where order matters lets you run everything else in parallel.
🐞Fewer odd bugs
Ordering bugs only show up under load or after a retry, which makes them hard to find.
Do not ask for order everywhere. Find the key where order really matters, and keep order only per key.

05Where Do We Use It?

🏦Accounts and payments
Events for one account must apply in sequence.
🛒Order lifecycles
Created, paid, shipped and cancelled must not run backwards.
🗃️Change data capture
Row changes must reach the copy in the order they happened.
💬Chat and comments
Messages in one conversation must show in the order they were sent.
📦Inventory
Stock added and stock removed for the same item must be applied in order.
📜Event sourcing
The sequence of events defines the current state.

06Types / Parts / How It Works

Levels of ordering

LevelWhat is promisedCost
No orderingMessages can arrive in any orderFastest and simplest. Fine for independent tasks
Per key (partition)Order among messages with the same keyParallel across keys. A hot key limits speed
Per queueOrder of one whole queue, with one consumerOne worker's speed only
Total (global) orderOne order for every message in the systemNeeds a single sequencer or consensus. Slow and a bottleneck
Causal orderIf one event caused another, they stay in that orderNeeds logical clocks. Unrelated events may differ

Ways to keep or repair order

Four tools
Keyed lanes
🔑Partition by keysame key, same lane
One reader per lane
🧍Single consumerno racing inside a lane
Sequence numbers
🔢Version checkignore stale updates
Idempotent handling
🔁Safe to repeatretries do no harm
Prevents reordering Detects and repairs it
Often you combine two: keyed lanes to keep order, and sequence numbers as a safety net.

Event time vs processing time

Event time is when something happened. Processing time is when your system saw it. A mobile app that was offline may send events from an hour ago, so they arrive late. If you need the true order of events, sort or window by event time, and decide how long to wait for late ones.

VisualizerOne queue, many workers: when does order break?Start with any free worker and see events applied out of order (red). Then choose same key, same worker, and finally one worker only. Turn retries on, and compare the speed.
How are events handed to workers?
Retries
12 events for three orders, sent in numbered order. Each box is one event: A, B, C with its step (1 = create, 2 and 3 = update, 4 = delete). Red = applied out of order.
Worker 1
#1 A1
#6 A3
#8 B3
#10 C3
Worker 2
#2 B1
#4 C1
#9 A4
#11 B4
Worker 3
#3 A2
#5 B2
#7 C2
#12 C4
Order in which the events finished (what the database saw):
B1
A2
A1
B2
C1
A3
C2
B3
A4
B4
C4
C3
Out of order
4
events applied too early or late
Time to finish
7 ticks
illustrative
Speed vs one worker
2.6x
illustrative
4 events were applied out of order (marked in red below). For example an update can run before the create it belongs to, or a delete before the last update. Workers run in parallel, and a slow or retried event lets a newer one overtake it.

A simplified model with a fixed event list, fixed processing times (1 to 3 ticks, 3 extra for a retry) and no random numbers, so the same settings always replay the same story. The tick counts are illustrative, not measurements.

07How to Use It / Steps / Implementation

Designing for order

  1. 1
    Decide where order really matters
    Usually it is per entity (one order, one account). Write that down. Do not ask for global order unless you must.
  2. 2
    Use that entity's id as the key
    In a log such as Kafka the key picks the partition. In a FIFO queue use a message group id. Same key, same lane.
  3. 3
    One consumer per lane
    Do not let two workers race inside one lane. Scale by adding lanes, not by adding workers to a lane.
  4. 4
    Put a sequence number or version on events
    The consumer keeps the last number it saw for each key, and ignores or parks anything older. This catches reordering that slipped through.
  5. 5
    Make handling idempotent
    Retries and replays will repeat messages. Applying the same message twice should be harmless.
  6. 6
    Think about retries
    A retried message must not let newer ones overtake it. Either block the lane until it succeeds, or use versions so a late arrival does no damage.
  7. 7
    Choose a sensible number of lanes
    More lanes give more parallelism, but a hot key still sits in one lane.
💡Last write wins, safely
For simple updates, store a version with each record and only apply a change if its version is higher than the stored one. Then an old message that arrives late is harmless.
⚠️FIFO costs speed
A strict FIFO queue serialises work inside each group. It is easy to use, but throughput per group is limited, and one slow message holds back the messages behind it.

08Key Terms to Know

TermMeaning in easy words
FIFOFirst in, first out: the oldest message is handled first
Total orderOne agreed order for every message in the whole system
Partial / per-key orderOrder that holds only among related messages
Partition keyThe value that decides which lane a message goes to
Message groupA FIFO-queue label: messages in one group are handled in order
Sequence numberA counter on each message, so a receiver can spot gaps and old messages
Out-of-order deliveryA message arriving or being handled after a later one
Head-of-line blockingA stuck message holding up everything behind it in a lane
Hot keyA key with so much traffic that its lane becomes a bottleneck
Event timeWhen the thing actually happened
Processing timeWhen your system got to see it

09Pros, Cons and Trade-offs

✅ Pros
  • Correct state for each entity
  • Easier to reason about and test
  • Replicas and copies stay equal
  • Per-key order still scales across many keys
  • Clear rules for retries
⚠️ Cons
  • Less parallelism inside a key
  • A slow message blocks the ones behind it
  • A hot key limits throughput
  • Global order is expensive
  • Needs a good key and extra metadata

Trade-offs

ChoiceWe gainWe lose
No ordering, many workersTop speed, simple scalingCorrectness for anything order-sensitive
Order per keyCorrect per entity, parallel across keysA hot key is a bottleneck. Rebalancing keys can break order briefly
One single consumerTotal order, easy to understandSpeed of one worker, and a single point of failure
Global orderEverything is sequencedA sequencer or consensus on every message, which is slow
Sequence numbers and drop-staleSafe even if delivery reordersMore code and state per key
Block the lane on retryOrder is kept exactlyOne failing message stops all behind it, so you need a dead letter path

10Common Problems and Mistakes

Common mistakes

  1. Assuming a queue is ordered. Many queues are only "best effort" ordered. Read what your product really promises.
  2. Adding workers to the same lane. Two consumers of one lane can finish in any order.
  3. Forgetting retries. A retried message arrives after newer ones and overwrites newer state.
  4. A bad key. Using a constant or very coarse key puts everything in one lane. Using a random key spreads one entity over many lanes.
  5. Changing the partition count. It changes where keys map, so old and new events of one key may land in different lanes.
  6. Trusting wall clocks. Timestamps from different machines can disagree. Prefer sequence numbers or versions from a single owner.
  7. Asking for global order by default. It is slow and rarely needed. Ask whether per-key is enough.

Things to watch

🔥Hot keys
One busy key can make one lane the slowest part of the system.
⛔Head-of-line blocking
A poison message can stop a whole lane. Use a retry limit and a dead letter queue.
🕳️Gaps in sequence numbers
A missing number means a lost or delayed message. Decide whether to wait, ask for a resend or move on.
⏱️Late events
In stream processing, decide how long to wait for stragglers before closing a window.

11Real-World Examples

📜Kafka
Order is guaranteed inside a partition. Producers use a key so related events share a partition.
📬Amazon SQS FIFO
FIFO queues keep order within a message group id, and standard queues do not promise strict order.
🐇RabbitMQ
A single queue with one consumer keeps order, but competing consumers and requeued messages can reorder things.
🗃️Database replication
Replicas apply the leader's log in order, so they end up with the same data.
💬Chat apps
Messages in one conversation carry a sequence number so the client can sort and spot gaps.
🌐TCP
TCP itself puts bytes back in order for a connection using sequence numbers.
📝Note
Product guarantees change over time and depend on settings. Check the documentation for exact ordering rules before you rely on them.
Mini case: order events
🛒Order servicekey = order id
→↓partition by key
📜Lanesone consumer each
→↓apply if version is newer
🗄️Databasestores the version
Keyed lanes keep each order correct, and a version check protects against late retries.

12Related Topics to Read Next

Kafka Deep Dive→

Order inside a partition, and the key that picks it.

RabbitMQ and SQS→

FIFO queues and message groups.

Delivery Semantics→

Retries and duplicates are the main cause of reordering.

Idempotency→

Safe repeats make reordering and retries harmless.

Lamport Timestamps→

Logical numbers that order events across machines.

Vector Clocks→

Tell whether two events were related or concurrent.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔Fact: there is no free global order. Order exists inside one lane.
  • ✔Lane: partition, FIFO queue or message group. Same key, same lane.
  • ✔Breakers: parallel workers, retries, several lanes, network delay.
  • ✔Fixes: key by entity, one consumer per lane, sequence numbers, idempotent handling.
  • ✔Trade-off: more order, less parallel speed. Keep the ordered scope small.
  • ✔Retries: block the lane or check versions, so a late message does no harm.
  • ✔Avoid: wall-clock timestamps and global order unless truly needed.
  • ✔One line: “Order per key, parallel across keys.”
← Previous
Event Streaming vs Message Queues
Next →
Task Queues, Workers and Scheduled Jobs