Logs, streams and Kafka
The append-only log behind Kafka and change data capture: partitions, consumer groups, delivery semantics, the settings that decide whether acknowledged data survives, compaction, and event-time windows with watermarks.
ConceptCore31 min readUpdated
- 1 architecture diagram
- 8 code samples
- 9 interviewer follow-ups
- 4 self-checks
On this page14 sectionsHLDLLDSenior depth
Read first: Storage engines and indexes, Consensus, leader election and distributed locks
- Explain the log abstraction and why partitioned, replicated logs such as Kafka are the backbone of data pipelines.
- Describe partitions, keys, consumer groups and offsets, and what ordering and delivery guarantees each one gives.
- Choose producer and broker settings (acks, in-sync replicas, unclean election) for the durability you need, and say what each costs.
- Explain compaction, the table-stream duality, event time, watermarks and late data, and where change data capture fits.
Watch a consumer group rebalance
Add, stop and crash consumers and compare range, round robin, sticky and cooperative sticky assignment on the same events.
Open the interactive8 code samples (341 lines), collapsed so the explanation stays in focus.
The simplest data structure in a distributed system is also one of the most useful: an append-only log. Records are added at the end, never changed, and each gets a position number. That is the write-ahead log from the storage engines lesson, the replicated log of Raft, and the thing that Kafka is a distributed, partitioned, replicated version of. Readers keep their own position, so any number of them can read the same data at their own speed, and anyone can go back and read it again.
Once you see the log, many designs become variations of one idea. A database's state is the result of replaying its log. A cache, a search index and a data warehouse are derived views of the same log. A message queue is a log that forgets what has been read. Change data capture turns a database's log into a stream that other systems consume.
A traditional queue (RabbitMQ, SQS) hands each message to one consumer and deletes it when it is acknowledged. A log (Kafka, Pulsar, Kinesis, Redpanda) keeps records for a retention period whether or not they have been read.
| Queue | Log | |
|---|---|---|
| After a message is consumed | It is deleted | It stays until retention expires |
| Several independent consumers | Needs a copy of the queue per consumer | Free: each has its own position |
| Replay and reprocessing | No | Yes: move the position back |
| Ordering | Often per queue | Per partition |
| Scaling a consumer | Add competing consumers | Add consumers up to the number of partitions |
| Good for | Task distribution, work that needs per-message retries and delays | Event streams, pipelines, anything several systems need or may replay |
Neither is better; they answer different questions. If the work is "do this job once, retry it on failure, maybe delay it", a queue fits, and the queues lesson covers it. If the data is "things that happened", that several systems read and that you may need to reread, use a log.
A topic is split into partitions. Each partition is an ordered log on disk, stored as a series of segment files (1 GB each by default), with a small index that maps offsets to file positions. A record's offset is its position in its partition. Records are kept for a retention period (seven days by default) or up to a size, or kept forever in compacted form (below).
Why it is fast. Appending to the end of a file is sequential I/O, which disks and SSDs do best. The operating system's page cache holds recent data, so most reads never touch the disk. Brokers hand data from the page cache to the network without copying it through user space (sendfile). Producers send batches, optionally compressed, and consumers fetch batches. A single broker can move hundreds of megabytes a second, and the cost of a record is mostly network and replication, not computation.
Keys and ordering. A producer chooses the partition: usually a hash of the record's key modulo the number of partitions, so all records for one key (one user, one order) go to the same partition and stay in order. Ordering exists only within a partition. There is no order across partitions, so if two events must be ordered relative to each other they need the same key. The hash must be stable across processes; the sample uses FNV-1a (Kafka uses murmur2), and .NET's string.GetHashCode would be wrong here because it is randomised per process. Changing the number of partitions changes the key-to-partition mapping, so keys move and per-key order is broken across the change.
Consumer groups. Consumers that share a group id divide the topic's partitions between them: each partition is read by exactly one consumer in the group. A group can have at most as many working consumers as partitions, so the partition count is the ceiling on parallelism. Each group remembers, per partition, its committed offset: the position of the next record to read after a restart (stored in an internal topic, __consumer_offsets). When a consumer joins or leaves, the group rebalances the partitions, and the consumers affected pause; newer protocols move fewer partitions and pause less. The gap between the end of a partition and a group's committed offset is consumer lag, the most important number to watch.
Replication. Each partition has a leader that takes all writes and, by default, all reads, and followers that fetch from the leader (since Kafka 2.4 a consumer can be configured to read from the nearest in-sync replica, which saves cross-zone traffic and does not change the guarantees). The leader tracks the in-sync replicas (ISR): the followers that are alive and close behind. A record is committed once every replica in the ISR has it, and the high watermark is the offset below which everything is committed; consumers see only committed records. When a leader fails, a new leader is chosen from the ISR. Kafka keeps its cluster metadata and elects controllers with a Raft-based quorum (KRaft), which replaced ZooKeeper.
A consumer reads a batch, does something with it and then commits its offset. The order of those two actions decides what a crash costs.
- Process, then commit (at-least-once): a crash between them means the batch is read again after the restart, so records may be processed twice but are never skipped. This is the usual choice.
- Commit, then process (at-most-once): a crash between them means the records are skipped, so nothing is processed twice but some may never be processed at all.
- Exactly-once is not a third option in the same sense. It is at-least-once delivery combined with processing that has the effect of happening once (see below).
The sample builds a topic of four partitions with 2,000 records and drains each partition with a consumer that crashes part-way through a batch one time in four, in both modes.
C# · A topic is a set of partitions, and a partition is an append-only list. Position in it…
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
// A topic is a set of partitions, and a partition is an append-only list. Position in it is called an offset.
public sealed class Topic
{
private readonly List<(string Key, string Value)>[] partitions;
public Topic(int partitionCount)
{
partitions = Enumerable.Range(0, partitionCount).Select(_ => new List<(string Key, string Value)>()).ToArray();
}
public int PartitionCount => partitions.Length;
// The same key always goes to the same partition, which is what gives per-key ordering. The hash must be stable
// across processes (Kafka uses murmur2); .NET's string.GetHashCode is randomised per process, so it cannot be used.
public int PartitionFor(string key)
{
uint hash = 2166136261;
foreach (byte b in Encoding.UTF8.GetBytes(key)) hash = (hash ^ b) * 16777619;
return (int)(hash % (uint)partitions.Length);
}
public long Append(string key, string value)
{
var log = partitions[PartitionFor(key)];
log.Add((key, value));
return log.Count - 1; // the new message's offset
}
public long EndOffset(int partition) => partitions[partition].Count;
public IReadOnlyList<(string Key, string Value)> Read(int partition, long from, int max) => partitions[partition].Skip((int)from).Take(max).ToList();
}
// A consumer group remembers, for each partition, the offset of the next message to read after a restart.
public sealed class ConsumerGroup
{
private readonly long[] committed;
public ConsumerGroup(int partitions) { committed = new long[partitions]; }
public long Committed(int partition) => committed[partition];
public void Commit(int partition, long next) { committed[partition] = next; }
// Each partition is read by exactly one consumer of the group. More consumers than partitions means idle consumers.
public static List<int>[] Assign(int partitions, int consumers)
{
var owned = Enumerable.Range(0, consumers).Select(_ => new List<int>()).ToArray();
for (int p = 0; p < partitions; p++) owned[p % consumers].Add(p);
return owned;
}
}
public enum CommitMode { AfterProcessing, BeforeProcessing }
public static class Consumer
{
// Reads one partition to the end in batches of 10. The consumer can die part-way through a batch; it then restarts
// from the last committed offset. When to commit decides what a crash costs.
public static void Drain(Topic topic, int partition, ConsumerGroup group, CommitMode mode, Random random, double crashChance, Action<string> handle)
{
while (group.Committed(partition) < topic.EndOffset(partition))
{
long from = group.Committed(partition);
var batch = topic.Read(partition, from, 10);
bool crash = random.NextDouble() < crashChance;
int handledBeforeCrash = crash ? random.Next(batch.Count) : batch.Count; // how far it got
if (mode == CommitMode.BeforeProcessing)
{
group.Commit(partition, from + batch.Count); // "I have this batch"...
for (int i = 0; i < handledBeforeCrash; i++) handle(batch[i].Value); // ...a crash now loses the rest
}
else
{
for (int i = 0; i < handledBeforeCrash; i++) handle(batch[i].Value);
if (!crash) group.Commit(partition, from + batch.Count); // a crash first means the whole batch repeats
}
}
}
}C#
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
var topic = new Topic(4);
var sent = new List<string>();
for (int i = 0; i < 2_000; i++) { topic.Append("user-" + (i % 50), "m" + i); sent.Add("m" + i); }
(List<string> Handled, ConsumerGroup Group) Run(CommitMode mode)
{
var handled = new List<string>();
var group = new ConsumerGroup(topic.PartitionCount);
var random = new Random(5);
for (int p = 0; p < topic.PartitionCount; p++) Consumer.Drain(topic, p, group, mode, random, 0.25, handled.Add);
return (handled, group);
}
var atLeastOnce = Run(CommitMode.AfterProcessing).Handled;
var atMostOnce = Run(CommitMode.BeforeProcessing).Handled;
int duplicates(List<string> handled) => handled.Count - handled.Distinct().Count();
int missing(List<string> handled) => sent.Except(handled).Count();
Debug.Assert(missing(atLeastOnce) == 0 && duplicates(atLeastOnce) > 0); // commit after processing: nothing lost, some repeated
Debug.Assert(duplicates(atMostOnce) == 0 && missing(atMostOnce) > 0); // commit before processing: nothing repeated, some lost
// A handler that remembers what it has done turns the repeats into no-ops: effectively once.
var applied = new HashSet<string>();
foreach (var m in atLeastOnce) applied.Add(m);
Debug.Assert(applied.Count == 2_000);
// Ordering: within a key, messages are handled in the order they were sent, repeats aside.
var firstTimeOrder = atLeastOnce.Distinct().ToList();
for (int u = 0; u < 50; u++)
{
var mine = firstTimeOrder.Where(m => int.Parse(m.Substring(1)) % 50 == u).Select(m => int.Parse(m.Substring(1))).ToList();
Debug.Assert(mine.SequenceEqual(mine.OrderBy(x => x)));
}
// Consumers in a group share the partitions: with 4 partitions, a fifth consumer has nothing to do.
Debug.Assert(ConsumerGroup.Assign(4, 2).Select(o => o.Count).SequenceEqual(new[] { 2, 2 }));
Debug.Assert(ConsumerGroup.Assign(4, 5).Count(o => o.Count == 0) == 1);With processing before commit, no record was lost and 394 were processed twice. With commit before processing, none was processed twice and 316 were lost. The test also checks that within a key the first-time processing order matches the order sent, and that an idempotent handler (one that remembers what it has applied) ends with exactly 2,000 distinct effects: at-least-once delivery plus an idempotent consumer is effectively-once, as in the distributed transactions lesson.
Kafka offers more than that inside its own boundary:
- The idempotent producer (on by default since Kafka 3.0) gives each producer an id and a sequence number per partition, so a retried send is not appended twice and retries do not reorder records.
- Transactions let a producer write to several partitions and commit consumer offsets atomically. A consumer using the
read_committedisolation level sees only committed transactions. Together they give exactly-once for a read-process-write loop whose input and output are both Kafka topics. - Anything outside Kafka, such as a payment or a database write, is not part of that transaction. It still needs an idempotency key or an inbox.
Poison messages. A record that always fails would block its partition if the consumer retried it forever. Move it to a dead-letter topic after a few attempts and carry on, and alert. Retry topics break ordering for that key, so use them only where order does not matter.
Replication protects against a broker dying, but only if the settings say so. Three settings do most of the work.
ackson the producer:0does not wait,1waits for the leader to write,allwaits until every replica in the ISR has the record.min.insync.replicason the broker or topic: withacks=all, the leader refuses a write if the ISR has fewer than this many replicas.unclean.leader.election.enable: whether, when no ISR member is alive, the controller may promote a replica that is behind. It is off by default.
The simulation models one partition on three brokers. Followers fetch from the leader at random, and during a "slow" window both stop fetching (so they drop out of the ISR). Then the leader crashes. A producer sends one record a tick and keeps a list of the records it was told were safely written, and the test counts how many of them are missing from the surviving leader. Each configuration is run in 300 random trials.
C# · Acks, ReplicatedPartition
using System;
using System.Collections.Generic;
using System.Linq;
public enum Acks { Leader, All }
// One partition replicated on several brokers. A message is just an id; each replica has its own log.
public sealed class ReplicatedPartition
{
private const int MaxLag = 3; // a follower further behind than this leaves the in-sync set
private readonly List<int>[] logs;
private readonly bool[] up;
private readonly int minInsync;
private readonly bool allowUncleanElection;
private readonly List<int> waitingForHighWatermark = new List<int>(); // offsets of acks=all messages not yet acknowledged
public int Leader { get; private set; }
public bool Offline { get; private set; }
public int HighWatermark { get; private set; } // everything below it is on every in-sync replica
public int Rejected { get; private set; } // produce attempts refused for lack of in-sync replicas
public readonly HashSet<int> Acknowledged = new HashSet<int>(); // what the producer was told was safely written
public ReplicatedPartition(int replicas, int minInsync, bool allowUncleanElection)
{
logs = Enumerable.Range(0, replicas).Select(_ => new List<int>()).ToArray();
up = Enumerable.Repeat(true, replicas).ToArray();
this.minInsync = minInsync;
this.allowUncleanElection = allowUncleanElection;
}
// The leader, and the followers that are alive and not far behind it: the in-sync replicas (the ISR).
public IEnumerable<int> InSync =>
Offline ? Enumerable.Empty<int>() : Enumerable.Range(0, logs.Length).Where(r => up[r] && (r == Leader || logs[Leader].Count - logs[r].Count <= MaxLag));
public IReadOnlyList<int> LeaderLog => logs[Leader];
public void Produce(int message, Acks acks)
{
if (Offline) return;
if (acks == Acks.All && InSync.Count() < minInsync) { Rejected++; return; } // refuse rather than accept a weak write
logs[Leader].Add(message);
if (acks == Acks.Leader) Acknowledged.Add(message); // acknowledged as soon as the leader has it
else waitingForHighWatermark.Add(logs[Leader].Count - 1); // acknowledged once every in-sync replica has it
AdvanceHighWatermark();
}
public void Fetch(int follower, int max) // a follower copies up to `max` messages from the leader
{
if (Offline || !up[follower] || follower == Leader) return;
while (max-- > 0 && logs[follower].Count < logs[Leader].Count) logs[follower].Add(logs[Leader][logs[follower].Count]);
AdvanceHighWatermark();
}
private void AdvanceHighWatermark()
{
HighWatermark = InSync.Min(r => logs[r].Count);
foreach (int offset in waitingForHighWatermark.Where(o => o < HighWatermark).ToList())
{
Acknowledged.Add(logs[Leader][offset]);
waitingForHighWatermark.Remove(offset);
}
}
public void CrashLeader()
{
var candidates = InSync.Where(r => r != Leader).ToList(); // a clean election picks from the ISR only
up[Leader] = false;
waitingForHighWatermark.Clear(); // those producers will time out and retry
if (candidates.Count == 0 && allowUncleanElection) candidates = Enumerable.Range(0, logs.Length).Where(r => up[r]).ToList();
if (candidates.Count == 0) { Offline = true; return; }
Leader = candidates.OrderByDescending(r => logs[r].Count).First();
for (int r = 0; r < logs.Length; r++) // the new leader's log is now the truth
if (r != Leader && logs[r].Count > logs[Leader].Count) logs[r].RemoveRange(logs[Leader].Count, logs[r].Count - logs[Leader].Count);
AdvanceHighWatermark();
}
}C# · One message per tick for 400 ticks. Both followers stop fetching for a while, then the…
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
// One message per tick for 400 ticks. Both followers stop fetching for a while, then the leader crashes.
(int Lost, int Acknowledged, int Rejected, bool Offline) Trial(int seed, Acks acks, int minInsync, bool unclean)
{
var random = new Random(seed);
var partition = new ReplicatedPartition(3, minInsync, unclean);
int slowFrom = random.Next(50, 150), slowUntil = slowFrom + random.Next(20, 60);
int crashAt = random.Next(slowFrom + 5, slowUntil + 40);
for (int tick = 0; tick < 400; tick++)
{
partition.Produce(tick, acks);
bool slow = tick >= slowFrom && tick < slowUntil;
for (int r = 0; r < 3; r++) if (!slow && random.NextDouble() < 0.7) partition.Fetch(r, 5);
if (tick == crashAt) partition.CrashLeader();
}
int lost = partition.Offline ? 0 : partition.Acknowledged.Count(m => !partition.LeaderLog.Contains(m));
return (lost, partition.Acknowledged.Count, partition.Rejected, partition.Offline);
}
(int LossyTrials, int Lost, int Rejected, int OfflineTrials) Experiment(Acks acks, int minInsync, bool unclean)
{
int lossy = 0, lost = 0, rejected = 0, offline = 0;
for (int seed = 1; seed <= 300; seed++)
{
var t = Trial(seed, acks, minInsync, unclean);
if (t.Lost > 0) lossy++;
lost += t.Lost; rejected += t.Rejected;
if (t.Offline) offline++;
}
return (lossy, lost, rejected, offline);
}
var leaderOnly = Experiment(Acks.Leader, 1, false);
var allButOneIsEnough = Experiment(Acks.All, 1, true);
var allWithTwo = Experiment(Acks.All, 2, false);
var allWithTwoUnclean = Experiment(Acks.All, 2, true);
Debug.Assert(leaderOnly.Lost > 0); // acknowledged by the leader alone: gone when it dies
Debug.Assert(allButOneIsEnough.Lost > 0); // "all" of a one-replica ISR is just the leader
Debug.Assert(allWithTwo.Lost == 0 && allWithTwo.Rejected > 0); // safe, and it said no during the outage instead
Debug.Assert(allWithTwoUnclean.Lost > 0 && allWithTwoUnclean.Lost < allButOneIsEnough.Lost); // an unclean election defeats even min=2| Settings | Trials that lost acknowledged records | Records lost | Writes refused | Trials ending with no leader |
|---|---|---|---|---|
acks=1, clean election | 14 | 22 | 0 | 185 |
acks=all, min.insync.replicas=1, unclean election | 189 | 4,412 | 0 | 0 |
acks=all, min.insync.replicas=2, clean election | 0 | 0 | 8,928 | 136 |
acks=all, min.insync.replicas=2, unclean election | 136 | 544 | 11,275 | 0 |
Each row is a trade. acks=1 is acknowledged by the leader alone, so whatever it had not yet replicated dies with it. acks=all with min.insync.replicas=1 sounds safe and is not: when the followers fall out of the ISR, "all replicas in the ISR" is just the leader, and 4,412 acknowledged records vanished. Only the third row never lost an acknowledged record, and it paid for that twice: it refused thousands of writes during the outage, and in 136 trials the partition had no leader at the end, because the only up-to-date replica was the dead one and the others were not allowed to take over. The fourth row shows what the unclean election switch does: it restores availability (no trial ended leaderless) and brings back data loss, even with two required replicas. That is the choice every Kafka deployment makes: durability or availability when replicas fall behind. For data you cannot lose, use a replication factor of 3, acks=all, min.insync.replicas=2 and no unclean elections, and accept that writes stop when two of the three brokers are unhealthy.
A topic can discard old records in two ways. Retention deletes whole segments after a time or size limit: right for events. Compaction keeps the newest record for each key and removes the older ones: right for state. A tombstone, a record with a key and no value, means the key was deleted and eventually removes it.
A compacted log is a table. Replay it from the start and you get the current value for every key; read it forever and you get every change. This stream-table duality is how Kafka keeps its own consumer offsets, how stream processors back up their local state (the state is a table and its change log is a compacted topic), and how a new service can load a complete snapshot of a dataset without asking the owner.
C# · An event in a log. A null value is a tombstone: "this key was deleted".
using System;
using System.Collections.Generic;
using System.Linq;
// An event in a log. A null value is a tombstone: "this key was deleted".
public sealed record Change(string Key, string Value);
public static class Compaction
{
// Keep only the newest event for each key, in their original order, and drop keys whose newest event is a tombstone.
// (Kafka keeps tombstones for a while so every consumer gets to see the delete; this model drops them at once.)
public static List<Change> Compact(IReadOnlyList<Change> log)
{
var newest = new Dictionary<string, int>();
for (int i = 0; i < log.Count; i++) newest[log[i].Key] = i;
return log.Where((c, i) => newest[c.Key] == i && c.Value != null).ToList();
}
// Replaying a log from the start builds the table of current values.
public static Dictionary<string, string> Replay(IEnumerable<Change> log)
{
var table = new Dictionary<string, string>();
foreach (var c in log) { if (c.Value == null) table.Remove(c.Key); else table[c.Key] = c.Value; }
return table;
}
}C#
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
var changeRandom = new Random(21);
var changes = new List<Change>();
for (int i = 0; i < 10_000; i++)
{
string key = "customer-" + changeRandom.Next(200);
changes.Add(new Change(key, changeRandom.Next(10) == 0 ? null : "v" + i)); // one event in ten deletes the key
}
var compacted = Compaction.Compact(changes);
var before = Compaction.Replay(changes);
var after = Compaction.Replay(compacted);
Debug.Assert(before.Count == after.Count && before.All(kv => after[kv.Key] == kv.Value)); // the same table, from a far shorter log
Debug.Assert(compacted.Count <= 200 && compacted.Count == before.Count);A log of 10,000 changes to 200 customers compacted to 177 records and replayed to exactly the same table. Compaction only makes sense when every record has a key and later records for a key supersede earlier ones. It is not a way to save space on an event log that needs its history.
A stream processor (Kafka Streams, Apache Flink, Spark Structured Streaming) reads from logs, transforms the records and writes to other logs or stores. Stateless operations such as filtering and mapping are easy to scale. Stateful ones (counting, joining, deduplicating) keep state in a local store that must survive a crash: Kafka Streams backs each store with a compacted changelog topic, and Flink takes periodic consistent checkpoints of all state together with the input positions, so after a failure it rewinds both to the last checkpoint and the results are as if nothing failed.
Windows. Aggregations over an unbounded stream need a window: tumbling (fixed, non-overlapping, such as each minute), hopping or sliding (overlapping), and session (a burst of activity ended by a gap). Streams can also be joined: two streams within a time window, or a stream against a table (enrichment).
Event time and watermarks. Which time do you window by? Processing time (when the processor sees the event) is simple and wrong whenever events are delayed or arrive out of order: a mobile app that was offline sends its events an hour late. Event time (when it happened, recorded in the event) gives correct results but needs a rule for when a window is complete. That rule is the watermark: a claim that no event older than this will arrive. A common watermark is the newest event time seen minus an allowed lateness. When the watermark passes the end of a window, the window's result is final, and any event that arrives later is late data: drop it, count it separately, or update the result.
The sample counts events in one-second tumbling windows. Twenty thousand events happen one per millisecond, so every window truly holds 1,000, and each event is delayed in the network by up to a second before it arrives.
C# · Counts events per tumbling window of event time. A window is final once the watermark…
using System;
using System.Collections.Generic;
using System.Linq;
// Counts events per tumbling window of event time. A window is final once the watermark, which trails the newest event time
// seen by the allowed lateness, has passed its end. An event for a window that is already final is too late.
public sealed class TumblingCounter
{
private readonly long size, allowedLateness;
private readonly Dictionary<long, int> open = new Dictionary<long, int>();
private long watermark = long.MinValue;
public readonly Dictionary<long, int> Results = new Dictionary<long, int>(); // window start -> count, once final
public int Dropped { get; private set; }
public TumblingCounter(long size, long allowedLateness) { this.size = size; this.allowedLateness = allowedLateness; }
public void Add(long eventTime)
{
long window = eventTime - eventTime % size;
if (window + size <= watermark) { Dropped++; return; }
open[window] = open.GetValueOrDefault(window) + 1;
watermark = Math.Max(watermark, eventTime - allowedLateness);
foreach (long w in open.Keys.Where(w => w + size <= watermark).ToList()) { Results[w] = open[w]; open.Remove(w); }
}
public void Flush() { foreach (var w in open) Results[w.Key] = w.Value; open.Clear(); }
}C# · 20,000 events, one per millisecond of event time, so every 1,000 ms window truly holds…
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
// 20,000 events, one per millisecond of event time, so every 1,000 ms window truly holds 1,000. They arrive out of order:
// each is delayed in the network by up to 1,000 ms.
var delayRandom = new Random(9);
var arrivals = Enumerable.Range(0, 20_000).Select(t => (EventTime: (long)t, ArrivalTime: (long)t + delayRandom.Next(0, 1_001)))
.OrderBy(e => e.ArrivalTime).ToList();
(int Dropped, int WrongWindows) CountByEventTime(long allowedLateness)
{
var counter = new TumblingCounter(1_000, allowedLateness);
foreach (var e in arrivals) counter.Add(e.EventTime);
counter.Flush();
return (counter.Dropped, Enumerable.Range(0, 20).Count(w => counter.Results.GetValueOrDefault(w * 1_000L) != 1_000));
}
var results = new[] { 0L, 100L, 500L, 1_000L, 2_000L }.Select(l => (Lateness: l, Result: CountByEventTime(l))).ToList();
Debug.Assert(results[0].Result.Dropped > 0); // no tolerance for lateness: late events are lost
Debug.Assert(results.Zip(results.Skip(1), (a, b) => a.Result.Dropped >= b.Result.Dropped).All(x => x)); // more tolerance, fewer drops
Debug.Assert(results[3].Result.Dropped == 0 && results[3].Result.WrongWindows == 0); // tolerating the full delay: exact counts
// Processing-time windows (by arrival) put late events in the wrong window, whatever the tolerance.
var byArrival = arrivals.GroupBy(e => e.ArrivalTime / 1_000).ToDictionary(g => g.Key, g => g.Count());
int wrongByArrival = Enumerable.Range(1, 18).Count(w => byArrival[w] != 1_000);
Debug.Assert(wrongByArrival > 0);| Allowed lateness | Events dropped as too late | Windows with a wrong count (of 20) |
|---|---|---|
| 0 ms | 8,790 | 19 |
| 100 ms | 7,106 | 19 |
| 500 ms | 2,028 | 19 |
| 1,000 ms | 0 | 0 |
| 2,000 ms | 0 | 0 |
Windows by arrival time, the processing-time approach, had the wrong count in 16 of 18 windows. Event time with enough lateness gave exact counts, and the price is latency: a window cannot be emitted until the watermark passes it, so tolerating a second of lateness delays every result by a second. Choose the lateness from the real delay distribution (often a high percentile), send the rare later events to a side output or a correction, and accept that no choice is both instant and exact.
Batch versus stream. The lambda architecture ran a batch and a streaming pipeline side by side and merged results. The kappa idea uses the log as the single source: to reprocess, start a second copy of the job from offset zero, write to a new output, and switch over. It works when the log keeps enough history and the job is deterministic.
Change data capture (CDC) reads a database's own log (the write-ahead log of PostgreSQL, the binlog of MySQL) and publishes each row change as an event. Tools such as Debezium do this: first a consistent snapshot of the table, then the stream of changes. It is the dependable way to get data out of a database without changing the application: to keep a search index or cache up to date, to feed analytics, and to relay an outbox table (the distributed transactions lesson), because the database log already has the commit order. Expect at-least-once delivery, changes ordered per row, and schema changes that must be handled.
Event sourcing goes further: the events are the source of truth and the current state is computed from them. It gives a complete audit trail, easy time travel and new read models built by replay, and it costs schema evolution of old events forever, replay time (solved with snapshots) and awkward deletion (privacy law may require erasing a person's events). It is often confused with event streaming: publishing events from a conventional database is not event sourcing.
traffic: 100,000 messages/s x 1 KB = 100 MB/s into the topic
replication: factor 3 = 300 MB/s of disk writes across the brokers
retention: 7 days x 8.6 TB/day = 60 TB, or 181 TB with 3 copies
consumers: 5 groups each reading everything = 500 MB/s out
partitions: at ~10 MB/s per partition (measure it) = 10 minimum; use 30+Partitions are the unit of parallelism, so choose the count from the target consumer parallelism and the throughput per partition, with headroom, because it is hard to change. You can add partitions but not remove them, and adding them moves keys. Too many partitions cost open files, memory, longer failover and slower controller operations.
Watch these: consumer lag per group and partition (growing lag means consumers cannot keep up), under-replicated partitions and ISR shrinks (replicas falling behind), request and disk latency, and skew (one partition much hotter than the rest, because of a hot key). Evolve message formats with a schema (Avro or Protobuf) and a registry that enforces compatibility, so a producer cannot break its consumers.
| Situation | What happens | Defence |
|---|---|---|
| A hot key | One partition gets most of the traffic and its consumer lags | Better keys, a salt for known hot keys (and accept losing their strict order), or more consumers per partition via a different design |
| Consumers slower than producers | Lag grows until data expires before it is read | Scale consumers up to the partition count, speed up processing, batch, add partitions |
| A rebalance storm | Consumers repeatedly pause while the group re-forms | Cooperative rebalancing, static membership, longer session timeouts, shorter processing per poll |
| A poison message | One record fails forever and blocks a partition | Bounded retries, dead-letter topic, alerting |
| Producer retries without idempotence | Duplicates and reordering | Idempotent producer, bounded in-flight requests |
| ISR shrinks to the leader | acks=all acknowledges a write held by one broker | min.insync.replicas of 2 or more; alert on ISR shrinks |
| An unclean leader election | Acknowledged records are lost | Keep it off for data you cannot lose |
| Late events | Wrong window results | Event time, a lateness bound, side output for stragglers |
| Reprocessing after a bug | Reading old data again produces duplicate effects downstream | Idempotent sinks, or write to a new output and switch |
| Retention too short | A slow or new consumer finds its data gone | Retention longer than the worst outage; monitor lag against it |
Interviewer follow-upL5How is Kafka different from RabbitMQ or SQS, and when would you use each?How to answer
A queue gives a message to one consumer and removes it, which suits task distribution, per-message retries and delays. Kafka is a log: records are retained, many independent consumer groups each read everything at their own position, and a group can replay by moving its offset. Use a queue for jobs, Kafka for events that several systems need, for pipelines and for anything you may want to reprocess. Ordering in Kafka is per partition.
Interviewer follow-upL5Why is Kafka fast?How to answer
It appends to files sequentially, which is the cheapest disk access, and serves recent data from the operating system's page cache. It batches and compresses records, replicates by having followers fetch batches, and sends data from the page cache to the network without copying it through user space. The design avoids per-message random I/O and per-message state on the broker, so the cost of a record is mostly network and replication.
Interviewer follow-upL6How do you guarantee ordering?How to answer
Order exists only within a partition, so give events that must be ordered the same key (a user or order id) so they land in one partition, and have a single consumer read it. With retries, enable the idempotent producer and keep in-flight requests bounded so a retry cannot reorder. Say what you give up: a hot key is a hot partition, adding partitions later remaps keys, and retry topics break order for the keys they carry.
Interviewer follow-upL6Explain at-most-once, at-least-once and exactly-once for a consumer. How do you get the effect of exactly-once?How to answer
Commit before processing and a crash loses records: at-most-once. Process before commit and a crash repeats records: at-least-once, the usual choice. Exactly-once delivery cannot be had across an unreliable boundary, so get exactly-once effect by making processing idempotent (an id kept in an inbox, written with the effect) or, inside Kafka, by transactions that write the output and commit the input offset atomically.
Interviewer follow-upL6Configure a topic so that acknowledged data is not lost.How to answer
Replication factor 3, producer acks=all, min.insync.replicas=2, unclean leader election off, the idempotent producer on, and consumers that commit after processing. State the cost: when two of three brokers are unhealthy writes are refused, and if the only up-to-date replica is down the partition has no leader until it returns. The simulation shows the alternatives losing thousands of acknowledged records.
Interviewer follow-upL6A consumer group keeps falling behind. What do you do?How to answer
Check lag per partition. If one partition lags, it is a hot key or a slow record; if all do, the consumers are too slow. Speed up the processing (batch database writes, avoid a network call per record, process in parallel by key within a consumer), add consumers up to the number of partitions, and add partitions if you are at the limit and can accept remapped keys. Make sure retention is longer than the lag so data is not deleted before it is read, and apply backpressure or shed load downstream if the sink is the bottleneck.
Interviewer follow-upL7Design a real-time analytics pipeline with late events and exact results.How to answer
Producers write events with an event timestamp and a stable key to a partitioned topic. A stream processor windows by event time with a watermark and an allowed lateness taken from the measured delay distribution, keeps its state in a checkpointed store, and writes results idempotently (keyed by window and key) to a serving store. Stragglers beyond the lateness go to a side output that corrects the numbers later. The log's retention lets you fix a bug and reprocess from an earlier offset into a new table. Say the trade-off: lateness delays every result.
Interviewer follow-upL7Per-user ordering at scale, but a few users produce most of the traffic. What do you do?How to answer
Key by user so each user's events stay ordered, which makes heavy users hot partitions. Measure the skew first. For the few heavy users, spread them over several sub-keys (user plus a small number) and either accept that their events are ordered only within a sub-key, or restore order downstream with a sequence number the consumer uses. Make sure a consumer can scale for the hot partition, for example by processing independent entities inside one partition in parallel, or consider giving those users a separate topic.
Interviewer follow-upL7When would you use event sourcing, and when not?How to answer
When the history is the point: audit and compliance, domains where "what happened and when" matters (accounts, orders), and when many read models or time travel are needed. Not for a simple CRUD application, where it adds permanent costs: old event schemas to support for ever, replay time, snapshots and the difficulty of deleting personal data. And distinguish it from publishing events with CDC or an outbox, which keeps the database as the source of truth and is much cheaper.
When a design has several systems that need the same stream of events, or needs replay, say "a partitioned, replicated log" and then answer the four questions an interviewer will ask: the key (what needs ordering), the partition count (consumer parallelism and throughput, with headroom), the delivery guarantee (at-least-once with idempotent consumers, and where exactly-once is real) and the durability settings (replication 3, acks=all, two in sync, no unclean election). Then say what you watch: lag and ISR.
A log is an ordered, append-only sequence that many readers consume from their own position. Kafka partitions it for scale and replicates each partition, ordering records only within a partition, so the key decides what is ordered. Consumer groups divide partitions, commit offsets, and rebalance, and the order of commit and processing decides whether a crash loses records or repeats them; idempotent consumers or transactions inside Kafka give exactly-once effect. Durability depends on acks, the minimum in-sync replicas and unclean election, and the simulation shows only one combination keeps every acknowledged record, at the cost of refused writes and possible unavailability. Retention suits events and compaction suits state, since a compacted log is a table. Stream processors window by event time using watermarks, trading result latency against late data, and keep fault-tolerant state. Change data capture publishes a database's own log, and event sourcing makes the events the truth.
Try answering out loud before you reveal each answer.
QuestionA consumer processes a batch and crashes before committing its offset. What happens after the restart, and what must the consumer be to make that safe?Reveal answer
It restarts from the last committed offset and reads the same batch again, so some records are processed twice. That is at-least-once delivery. It is safe if processing is idempotent: the effect of a record applied twice equals applying it once, for example by recording processed ids in the same transaction as the effect.
QuestionA topic has 12 partitions. How many consumers in one group can do useful work, and what happens with 20?Reveal answer
At most 12: each partition is read by exactly one consumer of the group. With 20 consumers, 8 sit idle and are only useful as standbys. To go beyond 12 working consumers you need more partitions, which remaps keys, or a design that parallelises inside a consumer.
QuestionA team sets acks=all and believes no acknowledged record can be lost. Under what condition are they wrong?Reveal answer
When min.insync.replicas is 1, or when the in-sync set has shrunk to the leader alone. "All replicas in the ISR" then means one broker, so the record is acknowledged while held by only the leader, and if that broker dies and another replica is promoted the record is gone. They also need unclean leader election off. In the simulation this setting lost 4,412 acknowledged records.
QuestionWindows by event time give correct counts but later than windows by arrival time. Why, and how do you choose the allowed lateness?Reveal answer
A window is final only when the watermark says no older event will arrive, and the watermark trails the newest event by the allowed lateness, so every result waits at least that long. Choose it from the measured delay of events, often a high percentile, send events later than that to a side output, and accept the trade between exactness and latency: in the sample, a lateness of 1,000 ms gave exact counts and 0 ms dropped 44% of the events.
- Jay Kreps, The Log: What every software engineer should know about real-time data's unifying abstraction (opens in a new tab) (LinkedIn Engineering, 2013): the idea behind this lesson.
- Apache Kafka documentation, Design (opens in a new tab): persistence, replication, the producer and consumer, and message delivery semantics, plus the configuration reference for
acks,min.insync.replicasandunclean.leader.election.enable. - Confluent, Exactly-once Semantics are Possible: Here's How Kafka Does it (opens in a new tab), and KIP-98 (opens in a new tab): idempotent producers and transactions.
- Tyler Akidau et al., The Dataflow Model (opens in a new tab) (VLDB 2015), and his Streaming 101 (opens in a new tab): event time, windows, watermarks and triggers.
- Apache Flink documentation, Timely stream processing (opens in a new tab): event time and watermarks in practice.
- Debezium, documentation (opens in a new tab): change data capture from PostgreSQL, MySQL and others.
- Martin Kleppmann, Designing Data-Intensive Applications (opens in a new tab), the chapters on batch and stream processing.