Ordering and out-of-order events
Events rarely arrive in the order they happened. Phones buffer while offline, producers retry, and a stream runs on many machines at once. This lesson shows what order Kafka and Spark really keep, and how to get correct results when the order is wrong.
Step 4 · Structured Streaming · Silver · Correct results end to end, lesson 2 of 3
On this page
Read first: Sources and sinks · Watermarks and late data (skip if you know them)
In plain words first
A supermarket has six checkout lanes. Customers in the same lane leave in the order they queued; across lanes, nobody can say who left first. The shop has three options:
One lane for everyone
One lane per family
Stamp every receipt
Real pipelines use the second and the third, almost never the first.
Kafka: in order within a partition, never across
A topictopic: A named stream of events in Kafka or Pub/Sub, such as "orders". Producers write to it; consumers read from it. Learn more → is split into partitions, and KafkaKafka: A system that stores streams of events in topics, in order within each partition, so many readers can read them, and read them again, at their own pace. Learn more → guarantees that a consumerconsumer: An application that reads events from a topic and keeps track of how far it has read. Learn more → reads each partition in exactly the order it was written. There is no order across partitions. Which partition a message goes to depends on its key: by default the producerproducer: An application that writes events to a topic. Learn more → takes a hash of the key modulo the number of partitions, so every message with the same key lands in the same partition, in order. A message without a key goes to whichever partition the producer is filling at the moment.
(balances .select(F.col("account_id").cast("string").alias("key"), F.to_json(F.struct("*")).alias("value")) .writeStream.format("kafka") .option("kafka.bootstrap.servers", "broker:9092") .option("topic", "balance-updates") .option("checkpointLocation", "s3://chk/balance_updates/") .start())
| You need order... | Do this | It costs |
|---|---|---|
| Per account, device or order | Key by that id | Nothing: the usual case |
| Across everything | One partition | All traffic through one partition and one reader |
| Not at all | No key | Nothing: the best spread across partitions |
Why global order is expensive
A single partition has one leader brokerbroker: One server in a Kafka cluster. Each stores some partitions and serves reads and writes for them. Learn more → and is read by one consumer in a group at a time, so the whole topic gets the throughput of one machine. Anything that sequences events across partitions needs coordination, which is slower still. Most requirements that sound like "everything in order" turn out to be "each account in order" or "results by when it happened". In an interview, ask: order of what, relative to what?
What order Spark keeps
- Within a micro-batchmicro-batch: One small round of a stream: Spark takes the data that arrived since the last round, processes it like a little batch job, and saves its progress. Learn more →, the rows of one Kafka partition are read in offsetoffset: The position of a message inside a Kafka partition: 0, 1, 2, ... A stream stores the offsets it has read in its checkpoint. Learn more → order by one tasktask: The work for one partition in one stage, run on one CPU core. Learn more →. With
minPartitionsabove the partition count, Spark splits a partition into ranges read in parallel. - Any shuffleshuffle: Moving rows between machines so that all rows with the same key end up together. Needed by joins, groupBy and sorting, and usually the most expensive step of a job. Learn more → (
groupBy, a join,repartition) mixes rows from all tasks, and keeps no order. - You cannot sort a stream: sorting is only allowed after an aggregation, in complete mode. Inside
foreachBatchthe batch is a normal DataFrame, so you can sort or rank it per key.
Put events in order with event time
Do not rely on arrival order. Give every event the information to order it, and let the logic use it:
| Question | Tool |
|---|---|
| Counts per period, though events arrive late | Event-time windows with a watermarkwatermark: In streaming, how late data may arrive. Spark uses it to know when old state can be dropped. Learn more → (Watermarks) |
| The latest state per key | "Latest wins": compare a sequence number, so an older update arriving late is ignored |
| Every step per key, strictly in sequence | Custom state that holds early events until the gap is filled (transformWithState) |
newest = Window.partitionBy("account_id").orderBy(F.col("seq").desc()) latest = (batch_df.withColumn("rn", F.row_number().over(newest)) .where("rn = 1").drop("rn")) (DeltaTable.forName(spark, "silver.balances").alias("t") .merge(latest.alias("s"), "t.account_id = s.account_id") .whenMatchedUpdateAll(condition="s.seq > t.seq") # older updates lose .whenNotMatchedInsertAll() .execute())
Common mistakes
- Assuming a topic is in order — Only each partition is. Two events of one account in different partitions can be read either way round.
- Adding partitions to a keyed topic casually — Keys move to new partitions, and old and new events of one key can be read out of order.
- Last write wins by arrival — An old update that arrives late overwrites a newer one. Compare a sequence number.
- Asking for global order by default — One partition caps the whole pipeline at one reader. Ask what really needs to be in order.
Key takeaways
- Kafka orders messages within a partition only; the key picks the partition.
- Global order means one partition and one reader: ask what really needs order, usually one entity.
- A shuffle keeps no order, and streams cannot be sorted: do not rely on arrival order in Spark.
- Order with event time and sequence numbers: windows with watermarks, latest-wins MERGE, or custom state.
Interview prep
THE QUESTION
"Balance updates for each account must be applied in order. How do you design the topic and the stream?"
Avoid: "Kafka keeps messages in order" without saying that order holds only within a partition, and only for messages with the same key.
Follow-ups · answer out loud, then open
Follow-up"Why not put everything in one partition so it is all in order?"
Scenario"Phones buffer readings while offline and send them hours later. You need the latest reading per device in a table."
Trap"Spark reads each Kafka partition in order, so my groupBy sees each key's events in order."
Check yourself
3 questionsTwo messages with the same key go to a topic with 6 partitions. What does Kafka guarantee?
Show the answer
They go to the same partition and are read in the order written. The key's hash picks the partition, and each partition is read in order.
A keyed topic grows from 6 to 12 partitions. What can happen?
Show the answer
New events of a key can land in a different partition, and be read out of order with older ones. The partition is hash(key) modulo the partition count, so the mapping changes.
Updates for one customer arrive out of order. Which MERGE keeps the newest?
Show the answer
whenMatchedUpdateAll(condition="s.seq > t.seq"). Only an update with a higher sequence number replaces the stored row.
Practise this
Interview problems on streaming, graded on hidden tests
Keep going
Up next · Correct results end to end · lesson 3 of 3 · 10 min readBad records and dead-letter queues
Split valid and invalid rows in foreachBatch, keep bad ones with the reason they failed, alert on the rate and replay them after a fix.
Related lessons
Watermarks and late dataStructured Streaming · 6 min read
Custom state with transformWithStateStructured Streaming · 7 min read
Streaming into Delta tables
Previous: Delivery guarantees end to end
Primary sources: Kafka: topics, partitions and order · Kafka producer config: partitioner.class · Spark Kafka integration: minPartitions · Unsupported operations (sorting)