Scrivio Interview library
DesignAdvanced7 min read · updated 12 November 2026

You must merge sorted event streams from 300 Kafka partitions into one globally time-ordered stream with bounded memory and late events up to 5 seconds. Describe the algorithm and its failure modes.

We run a k-way merge: a min-heap holds the head event of each of the 300 partitions, we repeatedly take the smallest, and refill from that partition, so each event costs O(log 300), about 8 comparisons. To handle events arriving up to 5 seconds late, we buffer and only emit events older than a watermark, the minimum progress across partitions minus 5 seconds. The main failure modes are idle or slow partitions that stall the watermark, which need idleness timeouts, and events later than the bound, which go to a side output rather than being dropped, and in most cases Kafka Streams or Flink should do this instead of custom code.

Why this question is asked

Kafka only orders events within a partition, so any time a system needs one global timeline, for an audit log, a ledger replay or a correlation engine, somebody has to merge partitions. Interviewers ask this design question because it combines a textbook algorithm with the messy reality of distributed streams: partitions that go quiet, consumers that fall behind, and events that arrive after we thought we were done with their time. In this answer, we will recap the k-way merge, explain why it is not enough on its own, add a watermark and a reorder buffer, walk through the failure modes one by one, and end with when to use a stream processor instead.

1A Quick Recap of the K-Way Merge

Merging k sorted lists is the merge step of merge sort generalised to many inputs. We put the first element of each list into a min-heap, keyed by timestamp. We poll the smallest, emit it, and offer the next element from the same list. The heap always holds at most one element per list, so it has k entries and each step costs O(log k). With k = 300, log2(300) is about 8, so every event costs about 8 comparisons regardless of total volume, and memory is bounded by k entries.

Java
record Head(long ts, int partition, Event event) {}
PriorityQueue<Head> heap = new PriorityQueue<>(Comparator.comparingLong(Head::ts)
.thenComparingInt(Head::partition)); // deterministic ties
for (int p = 0; p < 300; p++) {
Event e = next(p); // first event of each partition
if (e != null) heap.offer(new Head(e.ts(), p, e));
}
while (!heap.isEmpty()) {
Head h = heap.poll(); // O(log 300), about 8 comparisons
emit(h.event());
Event n = next(h.partition());
if (n != null) heap.offer(new Head(n.ts(), h.partition(), n));
}

This is correct only if every partition is itself sorted by event time and if we can always see the next event of every partition. In a live stream both assumptions fail, and the rest of the design is about handling that.

2Why the Plain Merge Breaks on Live Streams

First, a live partition may have no next event yet. If partition 17 is empty right now, we cannot know whether its next event will be earlier than the smallest one in the heap, so the strict merge would have to wait forever. Second, producers write events with their own clocks and retry, so a partition is roughly but not strictly ordered by event time: an event stamped 12:00:03 can land after one stamped 12:00:07. The question allows up to 5 seconds of lateness, so we must tolerate disorder within that bound.

So instead of trusting each head, we track progress. For each partition we remember the highest event time we have seen, and we define the watermark as the minimum of those values across partitions, minus the 5 second lateness bound. The watermark is our promise: we do not expect any more events older than it.

3Adding a Watermark and a Reorder Buffer

Every event we read goes into a buffer ordered by timestamp, which is itself a min-heap. After each read we recompute the watermark. Then we emit, in order, every buffered event whose timestamp is at or below the watermark. Events newer than the watermark wait, because a late event could still arrive and need to go before them.

Notice that memory is now bounded by time, not by count: the buffer holds roughly the last 5 seconds of events plus the gap between the fastest and slowest partitions. At 100,000 events per second, 5 seconds is about 500,000 buffered events, which we should size and monitor explicitly. Keeping the per-partition maximum in a second structure, such as a TreeMap of counts or a small heap, lets us find the minimum progress in O(log k).

Step throughProcessing one event
  1. Read event e from partition p
  2. Is e.ts below the current watermark?
    YesSend to the late side outputNoAdd to the reorder buffer
  3. Update progress[p] = max(progress[p], e.ts)
  4. Watermark = min(progress) - 5 sidle partitions excluded
  5. Emit buffered events with ts <= watermarkin timestamp order
  6. Commit offsets up to what was emitted

6 steps in order. Play them, or step through them one at a time.

4Failure Mode: Idle and Slow Partitions

The watermark is a minimum, so the slowest partition controls everything. If one partition receives no traffic for an hour, its progress stays an hour old, the watermark stops moving, and the buffer grows until the JVM runs out of memory. A slow consumer of one partition has the same effect more gently: output latency grows to match the laggard.

The standard remedy is an idleness timeout. If a partition produces nothing for, say, 30 seconds of wall clock time, we mark it idle and leave it out of the minimum. When it produces again, it rejoins, and any events it sends that are now behind the watermark are treated as late. We also alert on consumer lag per partition, because a consistently slow partition is usually a skewed key or a stuck consumer, which is an operational problem, not an algorithmic one.

5Failure Mode: Events Later Than the Bound

An event that arrives with a timestamp below the current watermark is beyond our 5 second promise, for example a phone that was offline for a minute. We must not silently drop it, because a missing event in a ledger is worse than a late one, and we must not insert it into the emitted stream either, because downstream consumers assume global order. The usual answer is a side output, a separate Kafka topic of late events with a counter on it, so that a separate process can reconcile them, and so that we can see when the lateness bound is set too tight.

Failure modes and responses
FailureSymptomResponse
Idle partitionwatermark frozen, buffer growsidleness timeout excludes it
Slow or lagging consumeroutput latency growsalert on lag, rebalance, fix skew
Event later than 5 swould break global orderroute to a late side output topic
Restart or rebalancebuffer lost, duplicatescommit only emitted offsets, dedupe by id
Clock skew in producersevents far in the futurecap timestamps, alert on outliers

6Restarts, Offsets and When to Use a Stream Processor

The buffer is in memory, so offsets must be committed only up to the last emitted event of each partition, not up to the last read one. After a restart we re-read the buffered window, and downstream consumers may see a few duplicates, so they should deduplicate by event id or the output should be written with idempotent keys. A rebalance that moves partitions to another instance needs the same care.

This is a lot of subtle machinery, and Flink implements exactly these concepts: per-partition watermarks, bounded out-of-orderness, idleness detection with withIdleness, side outputs for late data, and checkpointed state so the buffer survives restarts. Kafka Streams offers stream time, grace periods and windowed operations with similar ideas. Unless the requirement is narrow, I would build on one of them and keep custom code for the business logic. The custom merge is reasonable for a bounded replay job that reads historical partitions, where every partition has an end and the plain k-way merge is enough.

7Follow-up questions

Why does the heap need a tie breaker on partition?

Two events can have the same millisecond timestamp. Without a tie breaker their order depends on heap internals and could differ between runs, so a replay would not be reproducible. Breaking ties by partition and then offset gives one deterministic global order.

How do we choose the lateness bound?

From data. We measure the distribution of arrival delay, the difference between processing time and event time, and pick a bound that covers, for example, 99.9 percent of events, then watch the late side output count. A longer bound means fewer late events but more memory and more output latency.

Can we avoid the global merge entirely?

Often yes. If consumers only need order per customer or per account, partitioning by that key already gives the order they need and no merge is required. A global order across 300 partitions is expensive, so it is worth asking whether the business really needs it.

8Conclusion

In this answer, we built a global merge of 300 partitions with a min-heap holding one head per partition, at O(log k) per event. Because live partitions are only roughly ordered, we added per-partition progress, a watermark equal to the minimum progress minus 5 seconds, and a reorder buffer that emits only events below the watermark. We then handled idle partitions with timeouts, sent events later than the bound to a side output, committed offsets only for emitted events, and noted that Flink or Kafka Streams provide all of this out of the box.

What to say in the interviewAbout 90 seconds aloud

Open with

The core is a k-way merge. I keep a min-heap with the head event of each of the 300 partitions, ordered by timestamp with partition as a tie breaker.

Then, if they want more

I poll the smallest, emit it, and pull the next event from that partition, so each event costs log of 300, about eight comparisons, and the heap holds only 300 entries. On a live stream that is not enough, because partitions are only roughly ordered and some may have nothing to read yet.

So I track the highest event time seen per partition and define a watermark as the minimum of those minus the five second lateness bound. Events go into a reorder buffer, and I only emit events at or below the watermark, in order. Memory is then bounded by about five seconds of traffic, which I size and monitor.

The failure modes are the interesting part. An idle partition freezes the watermark and the buffer grows, so I use an idleness timeout to exclude it. A slow partition increases latency, so I alert on lag. Events older than the watermark go to a late side output topic instead of being dropped.

On restart I only commit offsets of emitted events and dedupe by id. In practice I would use Flink, which has watermarks, idleness and side outputs built in, unless this is a simple bounded replay.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "You must merge sorted event streams from 300 Kafka partitions into one globally...": https://scrivio-interview-library.netlify.app/java/algorithms-and-data-structures/7344287113/