← Complete program

Chapter 17 · Course 4 c17-m04

Does a stream still work after a stop?

Your goal Check after a stop that useful messages remain available and OPEN-17 and OPEN-18 are each applied exactly once in the simulation.

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 traced a test shell to a discreet depot, then found two distinct commands under the technical identity SUPPLIER-SVC. The message producer may have resent a command after uncertainty about delivery; the consumer stopped after the first. The team must show that restarting keeps the second command without multiplying openings.

This lesson stands alone. A producer writes to a Kafka topic, a consumer reads messages, and Kafka retains them for a configured period. A stop can lead to rereading. You will simulate failure and restart, compare raw messages with business effects, and read commands for a local Kafka lab. This page launches no real broker and never activates the story's door.

02

Before the lesson

Purpose of this course

Check after a stop that useful messages remain available and OPEN-17 and OPEN-18 are each applied exactly once in the simulation.

Topics covered

Describe producer, topic, consumer, and retention.; Compare produced messages, reread messages, and distinct effects.; Check missing commands and repeated effects separately.; Explain what to do if a necessary message is no longer retained.

What you will learn

  • Describe producer, topic, consumer, and retention.
  • Compare produced messages, reread messages, and distinct effects.
  • Check missing commands and repeated effects separately.
  • Explain what to do if a necessary message is no longer retained.

PART 1 · THE LESSON

Understand step by step

1

Lesson · explanation

A received message is not necessarily a new action

After an outage, Imani examines a small stream of door-opening commands. Voss claims that the second opening vanished; another report claims there were four openings. Both statements confuse messages with effects. A message is a record carried by the stream. An effect is an action applied by the receiving system. The same command identifier may appear in several messages, especially during replay. Counting four messages therefore does not prove that four doors were actually opened.

Imagine a mail carrier delivering two copies of the same invitation. You received two envelopes, but there is only one party. If you act twice on the same invitation, you create a duplicate effect. The program must recognize the command identifier before acting. In our copy, OPEN-17 occurs more than once and OPEN-18 occurs once. The mission asks whether both useful commands exist and whether each produced exactly one effect in the simulation.

A producer writes messages into a topic, which is like a stream journal. A consumer reads messages and decides what to do with them. A topic may have partitions, here P0 and P1; each message has a position, or offset, within its own partition. A checkpoint records where the consumer will resume. These terms are introduced here, not assumed. You can understand the exercise by following two bookmarks across four written lines.

The course copy is fictional and local. It opens no door, contacts no production broker, and cannot identify the human behind service identity SUPPLIER-SVC. The urgency belongs to the story; there is no real exercise timer. To succeed, keep three counts separate: retained messages, messages reread after the stop, and distinct commands that actually have an effect. This distinction resolves the two contradictory claims without inventing more evidence.

Pause and think

Why do four messages not prove four openings?

See the explanation

A command can be repeated or replayed in several messages without needing another effect.

2

Lesson · explanation

Read partitions and checkpoints as two bookmarks

The four retained records are P0/40 E1/OPEN-17, P0/41 repeated E1/OPEN-17, P0/42 E2/OPEN-18, and P1/12 E3/OPEN-17. P0 and P1 are separate partitions. Within P0, positions run 40, then 41, then 42. P1 has its own position 12. Do not treat 12 and 42 as two points on one universal clock: offsets are local to their partitions, so each partition needs a separate bookmark.

Before the interruption, the consumer already applied OPEN-17 from P0/40. Its durable resume state says P0→41 and P1→12. Under this exercise's convention, it rereads P0/41, P0/42, and P1/12. Three messages are read after restart: two carry OPEN-17 and one carries OPEN-18. P0/40 remains among the four retained records, but it is before the P0 checkpoint and is not reread from this state.

Imagine two open books, a red P0 and a blue P1. Your red bookmark is at page 41; the blue bookmark is at page 12. Resuming gives red pages 41 and 42 plus blue page 12. Counting every archived page answers a different question from counting pages read after the pause. This picture explains how 'four retained' and 'three reread' can both be true. Neither number yet tells us how many actions were applied.

For the mission, list all four positions with partition names, then cross out only P0/40 when listing replayed positions. Do not cross out P1/12 merely because 12 is smaller than 41: the books are different. In a real Kafka lab, a group with an existing committed offset will not automatically reset because an audit command says --from-beginning. Use a new group in an authorized lab, never a production group, when exploring earliest retained records.

Pause and think

Which positions are reread from checkpoint P0→41 and P1→12?

See the explanation

P0/41, P0/42, and P1/12: three reread messages.

3

Lesson · explanation

Deduplicate effects using the command identifier

At the stop, the durable action log already contains OPEN-17. After restart, P0/41 carries OPEN-17 again; the consumer keeps the record as evidence but does not repeat the action. P0/42 carries OPEN-18, which is not yet in the durable log, so the simulation adds that command once. P1/12 again carries OPEN-17 and must cause no new action. The final distinct effects are OPEN-17 and OPEN-18.

Picture a ticket desk where every ticket has a reservation number. Showing OPEN-17 twice can create two observations at the desk but should not grant two seats. OPEN-18 is a different number and deserves a new seat. The command identifier is the key to that decision. Message identifiers E1 and E3 describe stream records, not necessarily different business actions. Do not mistake a message ID for the identity of the effect.

In the copy, the final action log is [OPEN-17, OPEN-18]: two entries and two distinct values. Duplicate effects equal 2 − 2 = 0. This does not mean the topic contains no repeated raw messages; it clearly does. It means this simulation has not applied the same command identifier twice. A real application needs to store the identifier durably together with the effect. A crash between separate writes can otherwise create a problem.

The short example script starts from a state in which OPEN-17 is already known. It demonstrates deduplication logic but does not itself guarantee end-to-end exactly-once action for a physical door. A producer setting that reduces duplicate writes cannot automatically protect every downstream consumer effect. To make a real guarantee, study how the consumer position, durable action, and stored command ID are coordinated. This lesson claims only the result of its supplied simulation.

Pause and think

What action log remains after rereading the three records?

See the explanation

[OPEN-17, OPEN-18]: OPEN-17 was already applied, and OPEN-18 is added only once.

4

Lesson · explanation

Check missing commands and repeated effects separately

The first check asks whether an expected command is missing. The expected set is {OPEN-17, OPEN-18}. After restart, the applied set contains both names. Expected minus applied is empty, so in this copy the second command OPEN-18 has not vanished. This answers Voss's claim, but it says nothing yet about whether one of the commands was applied more than once.

The second check asks whether a command produced repeated effects. Compare action-log length with the number of distinct command identifiers. There are two entries and two distinct identifiers, so repeated effects equal zero. This addresses the report of four openings, which likely counted raw messages as actions. Both checks are needed: an application could include every expected command and still apply OPEN-17 twice.

Imagine distributing two medicines on a list. Checking that both names appear prevents forgetting one medicine. Checking that each dose was given only once prevents a repeated dose. These are different risks. Door commands similarly require a missing-action check and a duplicate-effect check. Raw message counts still matter for audit, but they cannot replace either check of the actions the receiving system performed.

Write the mission arithmetic plainly: four retained messages, three reread messages, two expected commands, two distinct applied effects, zero missing commands, and zero duplicate effects. Add 'in the supplied simulation' to the conclusion. If a real system's action logs were incomplete or altered, this arithmetic alone would not certify physical door behavior. Imani can request the additional logs and physical observations needed to test that possibility.

Pause and think

Why calculate both missing commands and repeated effects?

See the explanation

Having both expected commands does not ensure either was applied only once; the risks are separate.

5

Lesson · explanation

Retention limits what a restarted consumer can reread

Retention is the rule governing how long, or under what conditions, a topic keeps its messages. In this copy, all four records are still available, so the consumer can verify positions after its checkpoint. But if a necessary record such as P0/40 left retention before a group that needed it could read it, moving that group's offset would not recreate the deleted record. A bookmark cannot restore a torn-out page.

Imagine a noticeboard whose sheets are removed after a week. Returning a month later, you cannot recover an old notice by changing the page number in your notebook. You need an approved archive, another source, or an honest note that reconstruction is incomplete. Kafka's exact retention period and policy depend on the topic configuration; there is no universal duration. Check those settings before promising any real replay.

The mission separates two situations. First, all four practice records remain retained: rereading P0/41, P0/42, and P1/12 is possible and checkable. Second, a record needed by some group has already expired: replay from the topic alone cannot promise a complete history. The team should use an approved archived copy or replacement source with known provenance, then describe whatever gap remains. Do not silently fabricate the missing message.

Retention also cannot reveal who sent a command. The stream shows SUPPLIER-SVC, a technical account or service identity used for publication. Depending on system access rules, more than one person or process might be able to use its credentials. To attribute a human action, Imani needs other access logs, permissions, times, and physical evidence. A service identity is a technical lead, not a face behind the screen.

Pause and think

What if a needed record has already left retention?

See the explanation

Changing an offset cannot recreate it; find an approved archive or other source and document the gap.

6

Lesson · explanation

A successful restart remains a conclusion with limits

Imani can now answer both conflicting reports. The copy holds four raw messages, including repeated OPEN-17 records. Three are reread after the checkpoint. The final action log contains OPEN-17 and OPEN-18 once each. Within this small model, no expected command is missing and no effect is duplicated. That answer is better than simply saying 'two' or 'four' because it names exactly what each number counts.

Imagine a film with two scenes, each screened twice. Counting screenings gives four; counting different scenes gives two. To know whether the audience saw every scene, you must still check which scenes played. To know whether an action happened twice, inspect effects rather than screenings. The same logic drives the mission. The mystery remains: OPEN-18 exists in retained data, while its true sending time and human author still require investigation.

A real end-to-end examination would follow messages from producer to retained topic, consumer checkpoint, durable record of applied commands, and any physical effect. It would describe the transaction or deduplication method and retention settings. The exercise script contains only a small copy of these elements and teaches which questions to ask. Its green result is not a universal Kafka guarantee or proof about the story's real door.

Conclude by giving four retained positions and three reread positions, then the set of two applied commands. Calculate zero missing and zero duplicate effects with the two checks. End with two limits: an expired message needs an archive, and SUPPLIER-SVC does not identify a human. Those limits guide the next investigation step, in which a late-arriving record may still change the apparent timeline.

Pause and think

What may Imani say after the lab, and what human question remains open?

See the explanation

In the simulation OPEN-17 and OPEN-18 each have one effect with no missing or duplicate action; the human behind SUPPLIER-SVC is unknown.

Visual guide

Controlled stop and restart

  1. 1Producer: 4 retained messages
  2. 2Before stop: OPEN-17 applied at P0/40
  3. 3Checkpoint: P0=41, P1=12; 3 messages to reread
  4. 4After restart: OPEN-17 and OPEN-18 applied once

Raw messages: 4; missing commands: 0; repeated effects: 0 in the simulation.

Code · read each line

Simulate restart and check two invariants

records = [
    (0, 40, "E1", "OPEN-17"),
    (0, 41, "E1", "OPEN-17"),
    (0, 42, "E2", "OPEN-18"),
    (1, 12, "E3", "OPEN-17"),
]
checkpoint = {0: 41, 1: 12}  # After applying position 0/40.
action_log = ["OPEN-17"]    # Durable practice copy of the effect.
applied = set(action_log)
remaining = [
    row for row in records if row[1] >= checkpoint[row[0]]
]
for partition, offset, event_id, command_id in remaining:
    if command_id not in applied:
        action_log.append(command_id)
        applied.add(command_id)
expected = {"OPEN-17", "OPEN-18"}
print("raw_messages", len(records))
print("read_after_restart", len(remaining))
print("applied_commands", sorted(applied))
print("missing_commands", sorted(expected - applied))
print("duplicate_effects", len(action_log) - len(set(action_log)))

Standalone Python keeps four messages, resumes at three positions after the stop, then prints OPEN-17 and OPEN-18 as applied commands. The missing-command list is empty and repeated effect count is zero. Checkpoint and action log are fictional copies.

Configuration · read the values

Local Kafka lab commands to read

# Read-only learning example; requires an approved local Kafka broker.
bin/kafka-topics.sh --bootstrap-server localhost:9092 --create \
  --topic gate_commands_practice --partitions 2 --replication-factor 1
bin/kafka-console-producer.sh --bootstrap-server localhost:9092 \
  --topic gate_commands_practice
# In the producer terminal, enter a JSON line such as:
# {"event_id":"E1","command_id":"OPEN-17","credential":"SUPPLIER-SVC"}
bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 \
  --topic gate_commands_practice --from-beginning --group audit_practice

The first command creates a two-partition practice topic, the producer accepts JSON lines, and the audit consumer reads them. A local broker and new group name are needed to start at retained records. The page runs nothing; identifiers are fictional and contain no secret.

PART 2 · WATCH IT WORK

A complete worked example

Follow each step, then the result

Worked example: check the restart

OPEN-17 was applied before the failure; the group rereads P0/41, P0/42, and P1/12.

  1. Count four retained raw messages: E1 occurs twice, E2 once, and E3 once.
  2. Count three messages after the checkpoint; two carry OPEN-17 and one OPEN-18.
  3. Compare with durable effects: ignore OPEN-17 for action and add OPEN-18 once.
  4. Verify expected minus applied is empty and the action log has no duplicate.
What this shows

A successful restart shows both that no expected action is missing and that no action is applied twice in the tested copy.

How this helps with your mission

The guided example separates four retained records from the three reread after checkpoint P0→41 and P1→12, then from two applied commands. In the mission, reproduce both checks: expected {OPEN-17, OPEN-18} minus applied is empty, and action log [OPEN-17, OPEN-18] contains zero duplicates. This answers Voss and the 'four openings' report without confusing messages and effects. State that replay depends on retention and that SUPPLIER-SVC cannot identify a human. The result belongs to the simulation, not to an unexamined physical door.

PART 3 · YOUR TURN

Use the lesson to solve the mission

Story scene · practical task

Mission: the stream after the outage

Screens return after an outage. Voss says the second opening vanished; another report claims four openings. Imani accepts neither until messages and effects are counted separately. Mara hands you the fictional topic and checkpoints. Prepare a verifiable answer before the story meeting, without touching a real broker or door. There is no exercise timer.

Your task

  1. Give the retained message count and the positions read after the stop.
  2. List commands actually applied after restart.
  3. Calculate missing commands and repeated effects in the simulation.
  4. Explain retention's limit and why SUPPLIER-SVC still does not identify a person.

How to know you have succeeded

  • 4 raw messages; 3 positions reread.
  • OPEN-17 and OPEN-18 once each.
  • No missing command and no repeated effect.
  • Replay only while records are retained; technical identity is insufficient for attribution.
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. How many raw messages are retained, and at which positions?
2. After checkpoint P0→41 and P1→12, which positions are reread?
3. Which action log results from the simulation after restart?
4. How many missing commands and duplicated effects does this model find?
5. What if a needed message has left topic retention?
See the worked answer
  1. The four records are P0/40, P0/41, P0/42, and P1/12. From checkpoint P0→41 and P1→12, the consumer rereads the last three.
  2. OPEN-17 is already in the durable action log; its rereads remain evidence but add no effect. OPEN-18 is added once.
  3. Expected {OPEN-17, OPEN-18} minus applied is empty. Action log [OPEN-17, OPEN-18] has two distinct items: zero repeated effects. These findings apply to the supplied simulation.
  4. If needed records are out of retention, an offset cannot recreate them; use an approved archive or other source. SUPPLIER-SVC is a service identity, so other records are needed to identify a human actor.

You confirmed the second command without multiplying the first. Next, a late-arriving message will change the apparent timeline; you must distinguish event time from arrival time.

Before you leave

Remember this

  • The producer writes to a topic; the consumer resumes from a checkpoint for each partition.
  • The copy retains four messages, while P0/41, P0/42, and P1/12 are reread after the stop.
  • OPEN-17 was already applied; OPEN-18 is added once, producing two distinct effects.
  • Check missing commands and duplicate effects separately.
  • Retention limits replay; an offset cannot recreate a record already deleted.
  • A service account such as SUPPLIER-SVC alone does not identify the person who sent a command.

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.

Producer
A program writing messages to a topic.
Consumer
A program reading messages from the topic to process them.
Broker
A Kafka server storing and serving messages.
Retention
A rule determining how long or how much message history stays available.
Checkpoint
Durable bookmark from which a reader resumes after stopping.
Business effect
The concrete result intended by a command, distinct from the message carrying it.
Restart
Returning to work after a stop and checking messages and effects.

Approfondissements de ce cours

Raisonner sur les délais et détecter une panne

Un modèle synchrone impose une borne connue à la latence et une vitesse d’exécution contrôlée. Dans un modèle asynchrone, messages et exécution peuvent être retardés arbitrairement, sans garantie temporelle. Le modèle partiellement synchrone admet des périodes asynchrones finies mais de durée inconnue, avec un comportement synchrone en dehors de ces périodes. Ces termes ne décrivent pas ici le fait qu’une API bloque ou retourne immédiatement : c’est un autre usage du même vocabulaire.

Une mesure habituelle de faible latence ne fournit pas une borne toujours vraie. Les pertes avec retransmission, la congestion, les files d’attente et les changements de route peuvent créer de longs délais. Un processus peut être préempté, subir une inversion de priorité, une pause de ramasse-miettes ou une faute de page avec échange disque. Les garanties d’un système d’exploitation temps réel ne sont pas celles d’un serveur généraliste. Une pause conserve normalement l’état mémoire, tandis qu’un crash avec redémarrage le perd ; les autres nœuds peuvent confondre les deux.

Un détecteur de défaillance utilise souvent des sondes et un timeout. Sans réponse, il ne distingue pas un crash d’une pause, d’une perte ou d’un retard. Un détecteur parfait ne suspecterait que les nœuds réellement arrêtés ; cette propriété par timeout demande un modèle synchrone crash-stop avec liens fiables. Dans un modèle partiellement synchrone, un détecteur éventuellement parfait peut se tromper temporairement dans les deux sens, puis finir par distinguer les nœuds corrects des nœuds arrêtés. Cela ne promet pas une détection instantanée ni un délai maximal de rétablissement.

Conçois donc une réaction qui reste sûre même si une suspicion est fausse. Réaffecter un lot à un autre travailleur alors que le premier est seulement lent peut produire deux travailleurs actifs. Les mécanismes d’identité, de version et d’enregistrement atomique protègent l’effet métier. Les nœuds byzantins ne sont pas toujours détectables ; certaines déviations laissent des preuves, d’autres non. Un détecteur de panne usuel ne constitue pas un mécanisme général de détection de fraude.

Pour transformer un lien fiable réordonnant en lien FIFO, numéroter les messages par émetteur, mettre en attente les numéros futurs, livrer seulement le prochain attendu et éliminer les anciens doublons. En crash-recovery, persister les numéros, l’époque et l’état nécessaire, avec une définition précise du point de livraison ; sinon un redémarrage peut réutiliser un numéro ou oublier une livraison. Si le récepteur attend un message jamais retransmis, l’ordre est préservé mais le progrès s’arrête : distinguer ces deux garanties.

Exemple appliqué aux données

attendu = {'A': 0, 'B': 0}
tampon, livré = {}, []
for émetteur, numéro in [('A', 1), ('B', 0), ('A', 0), ('A', 1)]:
    if numéro < attendu[émetteur]:
        continue
    tampon[émetteur, numéro] = (émetteur, numéro)
    while (émetteur, attendu[émetteur]) in tampon:
        livré.append(tampon.pop((émetteur, attendu[émetteur])))
        attendu[émetteur] += 1
assert livré == [('B', 0), ('A', 0), ('A', 1)]

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

Le récepteur attend le numéro 0 et reçoit 2, 0, 1, 1. Donne l’ordre livré, puis explique le danger d’une remise à zéro du compteur de l’émetteur après crash.

Voir la correction expliquée

Stocker 2, livrer 0 à son arrivée, puis 1 et enfin 2 ; le second 1 est un doublon. Après crash, réutiliser 0 peut faire prendre une nouvelle requête pour un doublon ancien, ou inversement. Une époque durable ou une identité neuve connue du protocole, avec un état de réception adapté, évite l’ambiguïté.

Références : Notes originales de Martin Kleppmann — Cambridge 2025/26.

Adapté de Distributed Systems — notes de cours 2025/26, Martin Kleppmann, University of Cambridge, pages 24–27. 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