AI Hints
Home›System Design Tutorial›Logs and Guarantees
System Design · Lesson 67 of 120

Kafka and Logs

An ordered history.

⏱ 2 min read▶ Video at 1:20:12🎓 Free
Watch this lesson in the System Design courseWatch on YouTube ↗Full System Design course

Kafka is the most popular tool for streams of events. Unlike a normal queue, it doesn't delete messages once they're read. It keeps them in an ordered log, that many readers can go through at their own pace.

Kafka and Logs
From the video: Kafka and Logs
  • Popular for event streams
  • Messages are kept
  • An ordered log

Readers with offsets

Here's the idea. The log is a list of events that only grows. Each reader remembers its own position, called an offset. Run it. The email service has read everything. Analytics is two events behind, and can catch up whenever it likes. And a brand new service can start from the beginning, and replay the whole history.

kafkalog.pypython
log = ["order 1", "order 2", "order 3", "order 4", "order 5"]
offsets = {"email": 5, "analytics": 3, "new-service": 0}

for reader, pos in offsets.items():
    unread = log[pos:]
    print(f"{reader:>11} at offset {pos}: {len(unread)} to read {unread[:2]}")
Output
      email at offset 5: 0 to read []
  analytics at offset 3: 2 to read ['order 4', 'order 5']
new-service at offset 0: 5 to read ['order 1', 'order 2']

Kafka words

A few Kafka words. A topic is a named log, like orders. Each topic is split into partitions, so it can spread across machines, and order is kept within each partition. Consumers in a group share the partitions between them. And messages are kept for a set time, like seven days.

keyvalue
Topica named log
Partitiona slice, ordered
Consumer groupshares partitions
Retentionkept for days

Summary

Kafka stores events in ordered logs, and each reader tracks its own offset. New readers can replay history. Next, how many times a message really gets delivered.

Key takeaways
  • An append-only log
  • Offsets per reader
  • Replay history
Next up: Delivery Guarantees — at most, at least, exactly once