← Complete program

Chapter 17 · Course 2 c17-m02

How do we resume reading a stream?

Your goal Explain and simulate a per-partition Kafka restart that finds OPEN-18 without repeating OPEN-17's effect.

The lesson, the vocabulary, the worked example and the mission are separate blocks. You can follow them in order or return to the one you need.

Video explanation

This English explanation has English subtitles. Its examples may use a separate practice dataset; use the data stated in the written mission for your answers.

01

Story · optional context

The story so far

You are Aster Motors' new data recruit. Luca was hurt when a car resembling Noctis 01 crashed; the prototype is missing and Voss accuses you. Mara Sol and Imani found two distinct commands, OPEN-17 and OPEN-18, among four messages linked to SUPPLIER-SVC. A message reader stopped just after processing its first record. On restart it must find the second command without opening twice for the first.

This lesson stands alone. Kafka stores event streams in named topics. A topic is split into partitions, and an offset numbers a message's position within one partition. A consumer group keeps a reading position for each partition. You will resume a fictional copy from two offsets, count reread messages, and apply the prior lesson's idempotent rule. No Kafka server is needed.

02

Before the lesson

Purpose of this course

Explain and simulate a per-partition Kafka restart that finds OPEN-18 without repeating OPEN-17's effect.

Topics covered

Define topic, partition, offset, and consumer group.; Read a separate restart position for each partition.; Distinguish reread messages from new business actions.; Explain early and late offset commits and the limit imposed by retention.

What you will learn

  • Define topic, partition, offset, and consumer group.
  • Read a separate restart position for each partition.
  • Distinguish reread messages from new business actions.
  • Explain early and late offset commits and the limit imposed by retention.

PART 1 · THE LESSON

Understand step by step

1

Lesson · explanation

A reader stops in the middle of the investigation

You are Aster Motors' new data recruit. Luca was hurt when a car resembling Noctis 01 crashed; the prototype is missing, and Voss accuses you. Mara and Imani find two distinct commands, OPEN-17 and OPEN-18, among four messages linked to SUPPLIER-SVC. A message reader stops just after handling the first record. On restart it must find OPEN-18 without repeating OPEN-17's effect.

Picture a mail carrier reading envelopes on two shelves. A failure interrupts them after one envelope. When they return, they need to know the shelf and place where they stopped. A single number on a note is insufficient if each shelf numbers its envelopes separately. The carrier needs one bookmark per shelf.

Kafka is a system for storing and distributing message streams. A producer publishes messages and a consumer reads them. A named stream is a topic. The fictional topic here is gate_commands. The lesson uses four records in a Python list, without a Kafka server or an actual command to a physical door.

Reading the right messages is only part of the goal. The same business command, here an opening, must not produce its effect twice. Reading and acting are different. The story meeting adds pressure for Mara and Imani, but there is no real exercise timer. Follow each position slowly on paper.

Pause and think

Why does this topic need two bookmarks?

See the explanation

It has two partitions, each with its own offset numbering and restart position.

2

Lesson · explanation

Understand topic, partition and offset

A topic is a named stream where producers put messages. Kafka divides it into partitions, like separate shelves. Within one partition, messages have numbered positions called offsets. The pair partition plus offset identifies a reading position. The number alone can be ambiguous because another partition may also have it.

Partition 0 of gate_commands has three records: offset 40 carries E1/OPEN-17, offset 41 carries E1/OPEN-17 again, and offset 42 carries E2/OPEN-18. Partition 1 has offset 12 with E3/OPEN-17. E1, E2 and E3 identify event envelopes; OPEN-17 and OPEN-18 identify business commands.

Offsets 40, 41 and 42 order those three messages within partition 0. Offset 12 in partition 1 is not a timestamp and cannot be placed before 40 in a topic-wide order. Think of two books, each with a page 12: page 12 of the second book does not automatically precede page 40 of the first in the story they tell.

Kafka guarantees order within a partition, not across all partitions. The local script sorts by partition and offset only to display a readable list. That display order does not prove E3 arrived after E2 or reveal the real times of the commands. Time comparisons need other reliable timestamps and knowledge of how they were made.

Pause and think

Is position 1/12 necessarily earlier than 0/40?

See the explanation

No. Offsets are local to each partition and create no global order between shelves.

3

Lesson · explanation

A group keeps a position for every partition

A consumer group includes readers sharing work on a topic. It tracks restart positions separately for its assigned partitions. In this exercise the group is investigation_copy. It has already handled message 0/40 and stores the next offsets to read: partition 0 → 41 and partition 1 → 12.

A committed offset here means the next message to request, not the last message handled. For partition 0, starting at 41 excludes 40 and includes 41 and 42. For partition 1, starting at 12 includes message 12. Apply that rule separately to each shelf. Three positions are selected after restart: 0/41, 0/42 and 1/12.

At those positions, 0/41 repeats E1/OPEN-17, 0/42 holds E2/OPEN-18 and 1/12 holds E3/OPEN-17. Reading only the largest offset 42 would ignore partition 1. Starting partition 1 at 41 would also be wrong, because its own series has the relevant message at 12.

The simulation filters each record with record['offset'] >= next_offset[record['partition']]. It shows the idea with four items. A real Kafka reader uses positions tracked for its group and must obey system behavior and access rules. The small Python list changes no production group.

Pause and think

Which positions does investigation_copy examine after restart?

See the explanation

0/41, 0/42 and 1/12, because P0 resumes at 41 and P1 at 12.

4

Lesson · explanation

Three seen messages but only one new command

A message is a received envelope; a business command is the action requested inside it. Positions 0/41 and 1/12 both have command_id = OPEN-17, despite their different event IDs E1 and E3. Position 0/42 has command_id = OPEN-18. Counting three envelopes as three new openings would invent actions beyond the distinct commands.

The scenario says OPEN-17 already produced its effect before failure and that this fact was stored durably. When 0/41 and 1/12 are seen, preserve their raw messages for audit but do not perform OPEN-17 again. OPEN-18 is not yet in the applied-command record, so it becomes the only new effect on restart.

Imagine three slips handed to a guard: two contain the same numbered order OPEN-17, and the third has OPEN-18. The guard durably records completed order numbers. Seeing another OPEN-17 slip confirms its existence without turning the same key again. OPEN-18 requests a new action. The business command ID is the useful key against duplicates.

The small script therefore selects three positions, adds one new command OPEN-18 and ends with OPEN-17 and OPEN-18 in its applied set. Its sorting does not reveal actual chronology across partitions. The result also assumes that OPEN-17's applied state survived the failure; a set held only in memory would vanish.

Pause and think

What is the only new effect if OPEN-17 is already recorded as applied?

See the explanation

OPEN-18; both OPEN-17 messages remain visible without a second opening.

5

Lesson · explanation

Separate reading position from real-world effect

An offset tells the reader where to resume. It does not guarantee that a command was stored in a database, sent to a gate or carried out by the destination. It resembles a bookmark in a manual: it names the next page but does not prove you performed the experiment on the previous page. Confusing position and effect can lose or repeat an action.

Suppose the reader performs OPEN-17, then fails before saving its new position. On restart, it may see the message again. Without a command_id check, rereading could perform OPEN-17 twice. The bookmark then lags behind completed work. Rereading can be normal; repeating a business effect is what must be prevented.

Now suppose the reader saves the next offset first, then the effect fails. After restart, the group starts after the message even though the opening never happened. The bookmark is ahead of the action. Committing offsets as early as possible is therefore not a full solution to duplicate effects: it could make OPEN-18 disappear from actual work.

The right design depends on destination storage. A unique command key, atomic writing of effect and ID, or an appropriate transaction can coordinate the steps. Our simulation demonstrates only the idea. It does not promise end-to-end exactly-once behavior because producer, consumer, configuration and destination all matter.

Pause and think

What can happen if an offset is committed before an effect that then fails?

See the explanation

The group may skip the message after restart even though the business action never happened.

6

Lesson · explanation

Keep idempotence durable after a stop

Idempotence means replaying a command with the same identifier does not change business state a second time. In the exercise OPEN-17 is already in already_applied. The script checks each command_id and adds only IDs it has not seen. This protects the three-message restart from another OPEN-17 opening.

Yet already_applied is an in-memory Python set. If this script were a real restarting consumer, its contents would vanish unless rebuilt from durable storage. The exercise provides OPEN-17 as durably recorded. In production, a table of applied commands with a unique key or equivalent mechanism must preserve that state together with the effect.

One command can arrive in several envelopes. E1/OPEN-17 occurs at 0/40 and 0/41, while E3/OPEN-17 occurs in partition 1. Using only event ID E1 would miss E3 as the same business command. Conversely, do not merge OPEN-18 with OPEN-17 merely because both messages are linked to SUPPLIER-SVC.

Keep all three messages seen after restart to explain what circulated, and record new effects separately. An audit with three message rows and one new action row is consistent. Like three receipts concerning two numbered orders, the number of papers should not become the number of door openings.

Pause and think

Why is an in-memory already_applied set insufficient after a real crash?

See the explanation

It would be lost on restart; command ID and effect need coordinated durable storage.

7

Lesson · explanation

Retention limits how far back you can reread

Kafka keeps messages according to a time or volume retention policy. A group can return to a position only while the requested messages are available. If 0/41 has left retention, moving the bookmark back to 41 will not recreate it. It is like returning to a numbered notebook page that has been discarded: you know the number but lack the contents.

Before promising replay, check that needed offsets are still available. In our fictional list all four messages exist, so restart is possible. In a real topic, a long delay or short retention policy can remove old records. Another archive or source might then help, but that differs from direct Kafka replay at the desired offset.

A separate audit group can have its own reading positions without moving those of investigation_copy, if messages remain retained and access permits it. Think of two readers with separate bookmarks in the same book. Do not change a production group's offsets just to experiment, since that could disrupt its ordinary work.

Retention does not resolve human identity either. The messages are linked to SUPPLIER-SVC, a service identity, but that does not name who ordered the openings. Cross-partition order remains unknown without further evidence. Offsets show positions and retention says whether they can still be read, not the author or real time of each decision.

Pause and think

When does a known offset no longer allow direct replay?

See the explanation

When Kafka no longer retains the requested message under the topic's retention policy.

8

Lesson · explanation

Explain the restart without inventing a culprit

Mara gives you the two bookmarks before the fictional meeting. First list positions: P0 has 40 E1/OPEN-17, 41 E1/OPEN-17 and 42 E2/OPEN-18; P1 has 12 E3/OPEN-17. The group resumes P0 at 41 and P1 at 12. It examines 0/41, 0/42 and 1/12, keeping three messages for audit.

Then explain effects: OPEN-17 was already durably recorded. Its messages at 0/41 and 1/12 cause no new opening. OPEN-18 at 0/42 is the only new effect. This answers Voss's claim that the second command must have vanished and Imani's worry about a repeated opening. The result depends on correct tracking of command IDs.

State the limits. An offset does not confirm an effect, and its commit timing can risk loss or repetition. Messages must still be retained to replay. An offset in partition 1 cannot be compared as time with one in partition 0. The SUPPLIER-SVC link does not automatically identify a responsible human.

The next lesson checks JSON message shapes: a command field that changes unexpectedly might stop an older reader from distinguishing OPEN-17 and OPEN-18. For now, you can restart a fictional stream per partition and count messages separately from actions. That is what the investigation needs before making claims about openings.

Pause and think

Which sentence summarizes the result without claiming global order or a human author?

See the explanation

The copy examines 0/41, 0/42 and 1/12 after restart; OPEN-18 is the only new command, with no proven cross-partition order.

Visual guide

Resume two partitions

  1. 1P0: 40 E1/OPEN-17 | 41 E1/OPEN-17 | 42 E2/OPEN-18
  2. 2P1: 12 E3/OPEN-17
  3. 3Group: next P0=41; next P1=12
  4. 4Replay: 3 messages; new effect: OPEN-18

Offsets belong to partitions; the business key prevents a repeated effect.

Code · read each line

Simulate resuming from offsets

records = [
    {"partition": 0, "offset": 40, "event_id": "E1", "command_id": "OPEN-17"},
    {"partition": 0, "offset": 41, "event_id": "E1", "command_id": "OPEN-17"},
    {"partition": 0, "offset": 42, "event_id": "E2", "command_id": "OPEN-18"},
    {"partition": 1, "offset": 12, "event_id": "E3", "command_id": "OPEN-17"},
]
next_offset = {0: 41, 1: 12}
already_applied = {"OPEN-17"}
replayed = [
    record for record in records
    if record["offset"] >= next_offset[record["partition"]]
]
new_effects = []
for record in sorted(replayed, key=lambda item: (item["partition"], item["offset"])):
    if record["command_id"] not in already_applied:
        already_applied.add(record["command_id"])
        new_effects.append(record["command_id"])
print("replayed_positions", [(r["partition"], r["offset"]) for r in replayed])
print("new_effects", new_effects)
print("all_commands", sorted(already_applied))

The local script selects positions 0/41, 0/42, and 1/12, then uses previously applied OPEN-17 to add only OPEN-18 to new effects. Positions and state are fictional copies, with no Kafka connection.

PART 2 · WATCH IT WORK

A complete worked example

Follow each step, then the result

Worked example: resume after E1

The group handled 0/40 and stores P0→41, P1→12. OPEN-17 is durably marked applied.

  1. On P0, read from 41: E1/OPEN-17 then E2/OPEN-18.
  2. On P1, read from 12: E3/OPEN-17; do not compare 12 and 41 as times.
  3. Compare command IDs with durable state: OPEN-17 is already applied, so neither reread has another effect.
  4. OPEN-18 is new: add it once and retain a record of all three observed messages.
What this shows

Resuming the read and safely applying effects are two complementary checks.

How this helps with your mission

For Mara and Imani, keep one bookmark per partition: P0 resumes at 41 and P1 at 12. Examine 0/41 E1/OPEN-17, 0/42 E2/OPEN-18 and 1/12 E3/OPEN-17. Three messages are seen, but OPEN-17 was already durably applied, so only OPEN-18 is a new effect. Keep raw messages, coordinate offset and effect, check retention, and infer neither global order nor a person behind SUPPLIER-SVC.

PART 3 · YOUR TURN

Use the lesson to solve the mission

Story scene · practical task

Mission: bookmarks after the failure

The service screens restart. Voss claims the second command was lost during the stop; Imani fears a naive replay might open the same door twice. Mara gives you the group's two bookmarks and four practice records. Prepare a replay plan before the fictional meeting. No real system is touched, and this exercise has no timer.

Your task

  1. List messages in each partition with offsets.
  2. List positions read after restart.
  3. Name new commands applied when OPEN-17 is already durably recorded.
  4. Explain why an offset alone does not ensure a unique effect and when retention prevents replay.

How to know you have succeeded

  • P0 has 40,41,42; P1 has 12.
  • Replayed positions 0/41, 0/42, 1/12.
  • Only OPEN-18 is new; OPEN-17 is not reapplied.
  • Offset and effect differ; an expired record cannot be reread from that point.
Open this mission in the browser workspace

Try code or SQL and keep a local draft. The mission questions are checked separately below.

Check the facts in your mission

Answer each factual question, then write your report in your own words. The program checks the choices; compare the report with the worked answer below.

1. In the `gate_commands` copy, which message layout by partition is correct?
2. The `investigation_copy` group resumes at P0→41 and P1→12. Which positions does it read in this copy?
3. If OPEN-17 is already durably applied, which new business effect should the replay produce?
4. What can be inferred from P1/12 and P0/40?
5. Which risk matches each order of committing the offset and producing the effect?
6. If retention has already removed the record at the requested offset, what can direct replay from that offset do?
See the worked answer
  1. P0 has E1/OPEN-17 at 40, E1/OPEN-17 at 41, E2/OPEN-18 at 42. P1 has E3/OPEN-17 at 12.
  2. The group resumes P0 at 41 and P1 at 12. It sees 0/41, 0/42, and 1/12. Offsets do not form a global order.
  3. Durable command-ID state knows OPEN-17 already produced its effect. E1 and E3 remain visible without more effects; OPEN-18 is the only new action.
  4. Committing before the effect can lose it; committing after may cause rereading. Coordinate state and effect. If the requested offset precedes Kafka's retained data, direct replay from that point is impossible.

You can restart a stream without mixing partitions or doubling a command. Next you will check whether a message's shape can evolve without breaking older readers.

Before you leave

Remember this

  • A Kafka topic has partitions, each with its own ordered offsets.
  • investigation_copy resumes P0 at 41 and P1 at 12; those numbers are not comparable as times.
  • It examines 0/41, 0/42 and 1/12: three messages.
  • OPEN-17 already had its effect; OPEN-18 is the only new business command.
  • Committing too early can lose an effect; too late can cause a reread that must be controlled.
  • Direct replay requires retained messages and cannot alone identify a human author.

Continue with the integrated lessons

After the lesson and its mission, work through the additional lessons below in order. Each workshop supplies its own fictional data: do not merge identifiers or times from separate exercises into the story timeline.

A–Z

Part of the lesson · keep nearby

New words, explained

These are the names of ideas used in the lesson above. Return here whenever a word feels unfamiliar.

Kafka
A system that stores and distributes message streams.
Topic
A named stream where producers publish events.
Partition
An ordered part of a topic with its own offsets.
Offset
A message's position number within a particular partition.
Consumer group
Readers sharing work and tracked positions on a stream.
Committed offset
Stored restart position for a group, usually the next message to read.
Retention
The time or data volume for which messages remain available to reread.

Approfondissements de ce cours

Définir les liens et la reprise des nœuds

Un modèle de système décrit séparément le réseau, les nœuds et le temps. Un algorithme n’est correct que sous ses hypothèses. Les coupures peuvent provenir d’un câble, d’une saturation ou d’une attaque ; les notes utilisent aussi des exemples d’animaux endommageant des câbles pour rappeler que la cause physique varie. On raisonne ensuite sur les effets observables plutôt que sur chaque anecdote.

Un lien point à point bidirectionnel relie deux nœuds. Un lien parfait livre un message si et seulement s’il a été envoyé, sans exiger l’ordre d’envoi. Un lien à pertes équitables peut perdre, dupliquer ou réordonner, mais des tentatives répétées finissent par passer. Un lien arbitraire peut subir écoute, modification, falsification, répétition ou suppression par un adversaire actif. Une partition réseau est une période où certains liens perdent ou retardent toutes les communications ; elle n’est pas nécessairement une machine arrêtée.

Sur un lien à pertes équitables, retransmettre indéfiniment et dédupliquer à réception permet de construire une livraison fiable, à condition que l’émetteur reste capable de poursuivre les tentatives et que la coupure ne dure pas éternellement. TCP réalise des mécanismes comparables au niveau des paquets mais peut abandonner après un délai configuré. Pour une interruption plus longue, la reprise et la déduplication applicatives restent nécessaires.

TLS protège la confidentialité, l’intégrité et l’authentification appropriée de communications, avec validation des identités et une configuration correcte. Il ne force pas un adversaire à livrer les messages. Le support simplifie sa protection contre la répétition : en TLS 1.3, les données précoces 0-RTT demandent notamment une analyse anti-rejeu au niveau applicatif. Une protection cryptographique n’autorise donc pas à considérer une opération non idempotente comme répétable sans contrôle.

Dans le modèle crash-stop, un nœud arrêté ne revient pas ; un redémarrage est traité comme une nouvelle identité si le protocole l’exige. Le modèle crash-recovery autorise un retour, perd la mémoire volatile et suppose la persistance correcte des données écrites sur disque ; aucun délai de retour n’est garanti. Le modèle byzantin permet toute déviation du programme. Contrairement à certains liens qu’un protocole peut renforcer, ces modèles de nœuds ne se convertissent pas tous par un simple habillage générique. Un nœud qui respecte les hypothèses est appelé correct.

Exemple appliqué aux données

# Modèle local : résultat et effet font partie du même état.
def traiter(état, identifiant, quantité):
    if identifiant in état['résultats']:
        return état['résultats'][identifiant]
    état['total'] += quantité
    état['résultats'][identifiant] = état['total']
    return état['total']
état = {'total': 0, 'résultats': {}}
assert traiter(état, 'requête-7', 12) == 12
assert traiter(état, 'requête-7', 12) == 12
assert état['total'] == 12
# En production : persister atomiquement effet et résultat.
# Ne jamais réutiliser un identifiant pour un autre contenu.

Simulation Python locale à exécuter séparément. Les assertions vérifient les cas présentés ; ce code ne constitue pas une implémentation distribuée de production.

À toi de jouer

Un serveur conserve en mémoire les identifiants de requêtes déjà traitées. Explique ce qui manque après un redémarrage pour dédupliquer une requête reçue une seconde fois.

Voir la correction expliquée

La mémoire a disparu ; il faut un état durable des identifiants et résultats, enregistré de façon cohérente avec l’effet de la requête. Prévoir aussi une identité ou époque durable du client et une politique de conservation. Sinon une ancienne requête peut produire un nouvel effet ou entrer en collision avec une nouvelle requête.

Références : Notes originales de Martin Kleppmann — Cambridge 2025/26 · TLS 1.3 et rejeu — RFC 8446.

Adapté de Distributed Systems — notes de cours 2025/26, Martin Kleppmann, University of Cambridge, pages 21–23. Consulter le PDF source et ses illustrations · Provenance. Creative Commons Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) — adaptation française et exemples modifiés

Official references