← Complete program

Chapter 17 · Course 1 c17-m01

How do we recognize a repeated event?

Your goal Identify stream repetitions and process commands idempotently without discarding a genuine second command.

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 real prototype is missing and Voss is trying to blame you. Mara Sol and investigator Imani traced the test shell to a discreet depot. A new batch of command messages now arrives in the case copy. Each carries the technical label SUPPLIER-SVC. Voss says four messages mean four door openings, but Imani sees possible repeats and a distinct second command.

This lesson stands alone. An event is a message saying something was requested or observed. In a stream, a message may be reread after a failure or sent again. You will distinguish its event_id from the business command_id, then apply each command once in a simulation. SUPPLIER-SVC is a technical identity; it cannot by itself name the human who used it.

02

Before the lesson

Purpose of this course

Identify stream repetitions and process commands idempotently without discarding a genuine second command.

Topics covered

Distinguish a message, event identifier, and business command identifier.; Count raw messages, distinct events, and distinct commands.; Explain idempotence as 'repeating the input does not repeat the effect.'; Avoid inferring a person from one service key.

What you will learn

  • Distinguish a message, event identifier, and business command identifier.
  • Count raw messages, distinct events, and distinct commands.
  • Explain idempotence as 'repeating the input does not repeat the effect.'
  • Avoid inferring a person from one service key.

PART 1 · THE LESSON

Understand step by step

1

Lesson · explanation

Four lines on the screen, but how many actions?

You are Aster Motors' new data recruit. Luca was hurt in a crash involving a car resembling Noctis 01, the real prototype is missing, and Voss is trying to blame you. Mara and Imani traced a test shell to a discreet depot. A new batch of command messages appears in the case copy, all labeled SUPPLIER-SVC. Voss sees four lines and announces four door openings.

An event is a message saying something was requested or observed. A stream is a sequence of such messages arriving over time. Like a letter, a message has an envelope and contents. Here the envelope has an event_id; the contents have a command_id, the identifier for an opening request. Counting envelopes and counting requests are different operations.

The same message may be reread after a stop or resent when the sender did not receive confirmation. Picture printing another copy of a letter to make sure it arrives. Receiving two copies does not mean the recipient requested the same thing twice. Conversely, a new command may need a new effect even when it comes from the same service.

Your goal is to identify repeats without discarding a genuine second command, then simulate applying each request once. You control no real lock, and the exercise has no timer. The pressure belongs to the story. A good answer separates observed counts, simulated effects, and what SUPPLIER-SVC cannot prove about a person.

Pause and think

Why do four received messages not automatically prove four openings?

See the explanation

A message may be replayed or resent for the same command; examine identifiers before counting effects.

2

Lesson · explanation

Read each envelope and each command

The copy contains, in displayed order, E1/OPEN-17, E1/OPEN-17, E3/OPEN-17, and E2/OPEN-18. Each pair shows event_id first and command_id second. There are four raw message lines. The distinct event IDs are E1, E3, and E2: three. The distinct command IDs are OPEN-17 and OPEN-18: two. These three counts answer three different questions.

The second line repeats E1/OPEN-17 exactly and may be a replay of the same event. The third has a new event_id, E3, while its command remains OPEN-17. It is a new envelope for the same business request. The fourth line carries OPEN-18, different from OPEN-17. Do not delete it merely because it also uses SUPPLIER-SVC.

Imagine ordering a cake with order number 17. The shop receives the original order slip, an identical photocopy, and another paper still bearing order number 17. That is one cake order. A slip numbered 18 is a second order. The paper number tracks envelopes; the order number decides how many cakes to make.

For this rule to work, each genuinely new action needs its own command_id. If a system reused OPEN-17 for another opening, deduplication would wrongly suppress a legitimate action. That is a design flaw to investigate, not a reason to treat every envelope as a new request. In this scenario, OPEN-17 and OPEN-18 are the two distinct requests to inspect.

Pause and think

How many messages, distinct event_id values, and distinct command_id values are there?

See the explanation

Four messages, three distinct event IDs, and two distinct command IDs.

3

Lesson · explanation

An exact replay differs from a new delivery

An exact replay repeats a retained message without changing its event identifier. The second line repeats E1/OPEN-17, including the envelope label. Comparing event_id values exposes that exact repeat. Keep both lines in the archive to understand how the stream behaved, while avoiding counting them as two commands.

The third line is different: E3 has not appeared before. A check removing only repeated event IDs would therefore let E3 pass as 'new.' Yet E3 contains OPEN-17, which was already requested. If every new event ID caused an action, the same command could act again. This is why the business check uses command_id.

Imagine an original parcel and its resend in a new box. The new box has another tracking number, but the note inside still asks for the same object to reach the same person. The box number answers 'which delivery?' The order number answers 'which action should occur?' Confusing them overcounts openings.

Do not say E3 is unimportant. It may reveal a resend, a lost confirmation, or a system stage that creates new envelopes. The investigation should retain raw messages and identifiers. It separates the event archive from the applied effect. Deleting E3 from evidence would hide part of the stream's behavior.

Pause and think

E3 is new. Why should OPEN-17 not be applied again?

See the explanation

Its envelope is new, but command_id=OPEN-17 is a command already applied.

4

Lesson · explanation

Idempotence: a repeated request keeps one effect

A process is idempotent when repeating the same operation does not multiply its result. In our simulation, applying OPEN-17 once and then receiving OPEN-17 again leaves one application of that command. This does not mean every later command is ignored. OPEN-18 is another request and needs separate treatment. The business identifier makes the distinction.

The practice script holds a set called applied_commands. At the first OPEN-17, the ID is absent, so the script adds it and prints apply OPEN-17. On the second and third lines, OPEN-17 is already present, so no new application is printed. At OPEN-18, the ID is absent, so it prints apply OPEN-18. The simulation has two applications in total.

Picture a stamp on a library order slip. Once slip 17 is fulfilled, a photocopy should not send out another book. Slip 18 is new and does need fulfillment. One bad program acts once for every paper received and acts four times. Another bad program processes only the first line and loses OPEN-18. Idempotence avoids both mistakes.

This demonstration opens no actual door. apply is only text printed by a local program. It teaches a decision rule, not the proven history of building locks. Voss may be wrong to infer four openings from messages, but these counts alone also cannot establish how many physical movements a lock made. Door records would be needed.

Pause and think

Which commands does the practice program print with apply?

See the explanation

apply OPEN-17 and then apply OPEN-18, once each.

5

Lesson · explanation

Local memory does not survive a crash

In the small script, applied_commands is an in-memory set. It is excellent for teaching the rule, but it disappears when the program stops. After restart, OPEN-17 may look new and its effect may repeat. A real service must retain processed command IDs durably. This matters precisely because messages may be reread after a failure.

The record and effect must also be coordinated. Suppose the program marks OPEN-17 as applied and crashes before performing the action. After restart it may ignore a request whose effect never happened. Conversely, if it performs the action and crashes before recording it, it may repeat the action. Two separate steps create this risky gap.

A database uniqueness constraint or a transactional write can help, depending on how the effect is performed. A transaction is like a group of changes confirmed together or canceled together. This lesson does not build a complete real-world solution or promise 'exactly once' for a physical lock. It explains why command memory must endure and align with the outcome.

A poor claim would be 'our Python set permanently prevents double openings.' It survives neither a crash nor two programs racing at once. The honest conclusion is narrower: with this fictional list in one local run, the script prints two applications. Production would need durable design, failure tests, and records from the real system.

Pause and think

Why does an in-memory applied_commands set not protect a restarted program by itself?

See the explanation

The set is lost when the program stops, so old commands may appear new.

6

Lesson · explanation

Preserve four messages while limiting effects

An investigation needs raw messages even when some cause no new effect. The four lines show E1 was seen again and OPEN-17 was also delivered as E3. If you erase repeats from the source file, Imani cannot study how the stream retried. Preserve originals and calculate the once-only applied command list separately.

This resembles a mail ledger and a task list. The ledger records every envelope received, including copies. The task list says to make cake 17 once and cake 18 once. Erasing ledger lines to shorten the task list destroys history. Performing a task for every ledger line multiplies effects.

In your answer to Mara, put three numbers side by side: four received messages, three distinct event identifiers, and two distinct business commands. Describe the second line as an exact E1 replay and the third as a new E3 envelope for OPEN-17. Someone opening only this lesson can then understand why Voss's table is misleading.

Do not confuse message arrival order with the certain order of physical actions. A message can be sent late, delayed, or reread after the action it describes. The copy gives row order, not a full building timeline. Preserve available timestamps and later compare authentication and lock logs before stating what physically occurred.

Pause and think

Why keep repeated E1 and E3 in the raw archive?

See the explanation

They show replays and new deliveries in the stream even though OPEN-17 should produce only one effect.

7

Lesson · explanation

SUPPLIER-SVC is a technical label, not a face

All four messages carry SUPPLIER-SVC. That value is the technical identity declared in the copy, like a label on a key used by a program. It helps guide a search into possible access. It does not automatically identify the person who pressed a button or even the exact process using the key at each moment.

A key may be shared between services, copied, stolen, or used by several processes. Picture an access card labeled 'workshop': the label names a group, not the hand holding it at 21:00. To attribute an action, Imani needs authentication logs, machines, times, permissions, and independent evidence. Even these must be linked carefully.

The investigation already found that a supplier account had excessive permissions. That is a serious lead, not proof that the permissions were used here or that Voss sent the commands. It would be equally wrong to blame you merely because another authorization bore your name. Labels open questions; they do not end the investigation.

A careful conclusion says, 'The observed messages carry SUPPLIER-SVC; check who or what controlled that identity at the relevant times.' A bad conclusion says, 'SUPPLIER-SVC proves Voss opened the door twice.' The counts and identifiers here do not yet tie any command to a particular person or a confirmed lock movement.

Pause and think

Can SUPPLIER-SVC alone name the person who requested OPEN-18?

See the explanation

No. It is a technical identity; access records and independent evidence are needed to attribute a person.

8

Lesson · explanation

Explain the mission without inventing the ending

The control room displays four lines, and Voss calls them four openings. Your first answer is arithmetic: E1/OPEN-17, E1/OPEN-17, E3/OPEN-17, and E2/OPEN-18 give four envelopes, three distinct event_id values, and two distinct command_id values. The second line is an exact replay; the third redelivers OPEN-17 in a new envelope. These are different repeat mechanisms.

Your second answer concerns the effect in an idempotent simulation: OPEN-17 once and OPEN-18 once. OPEN-18 is not a duplicate because its business ID differs. Keeping all four messages as evidence does not require four effects. Likewise, limiting effects does not authorize deleting two messages from the archive. These rules protect both the investigation and the system.

Your third answer states the limits. The copy proves neither four physical movements, the true order of all actions, nor the human behind SUPPLIER-SVC. It shows two distinct business commands to inspect. Imani can continue with authentication logs, lock records, and times. The next lesson explains how a stream can retain and reread messages after a stop.

To succeed, write short sentences Mara could read without knowing Python: 'four messages, three events, two commands; OPEN-17 repeats, OPEN-18 is distinct; the local program applies each once; the service identity does not name a person.' This answers Voss without inventing a culprit or controlling any real door.

Pause and think

Which command must not be erased as a duplicate of OPEN-17?

See the explanation

OPEN-18: it is a distinct second business command to inspect and apply once in the simulation.

Visual guide

Four envelopes, two commands

  1. 1E1 → OPEN-17: apply
  2. 2E1 → OPEN-17: replay
  3. 3E3 → OPEN-17: new envelope, same command
  4. 4E2 → OPEN-18: second command

Keep all 4 messages, but the simulation applies only 2 business effects.

Code · read each line

Apply each command only once

messages = [
    {"event_id": "E1", "command_id": "OPEN-17", "credential": "SUPPLIER-SVC"},
    {"event_id": "E1", "command_id": "OPEN-17", "credential": "SUPPLIER-SVC"},
    {"event_id": "E3", "command_id": "OPEN-17", "credential": "SUPPLIER-SVC"},
    {"event_id": "E2", "command_id": "OPEN-18", "credential": "SUPPLIER-SVC"},
]
seen_events, applied_commands = set(), set()
for message in messages:
    seen_events.add(message["event_id"])
    if message["command_id"] not in applied_commands:
        applied_commands.add(message["command_id"])
        print("apply", message["command_id"])
print("messages", len(messages))
print("unique_events", len(seen_events))
print("unique_commands", len(applied_commands))

The local script prints apply OPEN-17 and apply OPEN-18, then 4 messages, 3 event IDs, and 2 distinct commands. It uses no Kafka broker or real lock; applied_commands is only practice memory.

PART 2 · WATCH IT WORK

A complete worked example

Follow each step, then the result

Worked example: is E3 new?

E3 has never been seen, but its command_id is OPEN-17, already applied with E1.

  1. Compare event_id: E3 is new, so it is not the exact replay of E1.
  2. Compare command_id: OPEN-17 is already present; the business effect is the same.
  3. Keep E3 in raw messages to explain the second delivery but do not open the door again.
  4. When E2/OPEN-18 arrives, recognize a different command and apply it once.
What this shows

A new envelope and a new action are two different questions.

How this helps with your mission

For the mission, list E1/OPEN-17, E1/OPEN-17, E3/OPEN-17, and E2/OPEN-18. Count four raw messages, three distinct event_id values, and two distinct command_id values. Explain the exact E1 replay and E3's new envelope for OPEN-17, then simulate one application each of OPEN-17 and OPEN-18. Preserve all four messages as evidence, and say SUPPLIER-SVC names neither a person nor four confirmed physical openings.

PART 3 · YOUR TURN

Use the lesson to solve the mission

Story scene · practical task

Mission: four door messages

The control room shows four lines under SUPPLIER-SVC. Voss points to the screen and declares four openings. Imani gives you event IDs E1, E1, E3, E2; Mara adds command IDs OPEN-17, OPEN-17, OPEN-17, OPEN-18. Prepare an answer before the fictional meeting without deleting messages or activating a door. There is no exercise timer.

Your task

  1. Count messages, distinct event IDs, and distinct command IDs.
  2. Identify the exact replay and the new delivery of an old action.
  3. Name the commands to apply once each.
  4. Explain why SUPPLIER-SVC cannot identify a person.

How to know you have succeeded

  • 4 messages, 3 event IDs, 2 command IDs.
  • Second line repeats E1; third has new E3 but OPEN-17 was already requested.
  • OPEN-17 then OPEN-18, once each.
  • A technical identity alone is insufficient to attribute human action.
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. The copy shows E1/OPEN-17, E1/OPEN-17, E3/OPEN-17, and E2/OPEN-18. How many messages, distinct `event_id` values, and distinct `command_id` values are there?
2. How do the second line E1/OPEN-17 and third line E3/OPEN-17 differ?
3. In the idempotent simulation, which commands should print `apply`?
4. What should the investigation do with repeated E1 and E3/OPEN-17 messages?
5. What can we conclude from SUPPLIER-SVC appearing on all four messages?
See the worked answer
  1. The lines are E1/OPEN-17, E1/OPEN-17, E3/OPEN-17, E2/OPEN-18: four envelopes, three event IDs, and two business commands.
  2. The second replays E1. The third has a new E3 envelope but repeats OPEN-17; keeping it as evidence does not require repeating the effect.
  3. An idempotent processor records OPEN-17 as applied and ignores its repeats for the effect. OPEN-18 remains a real second command to investigate separately.
  4. SUPPLIER-SVC tells which technical identity appears in messages. Without access records and other evidence we do not know which person or process controlled it.

You can tell a replay from a second action. Next you will see where Kafka puts messages and how reading resumes after a stop without mixing offsets from different partitions.

Before you leave

Remember this

  • A message has an event_id envelope and a business command_id; whether each is new is a separate question.
  • The copy contains four messages, three distinct event IDs, and two distinct commands.
  • The second line replays E1; E3 is a new envelope for the already requested OPEN-17 command.
  • An idempotent simulation applies OPEN-17 once and OPEN-18 once while preserving all four raw messages.
  • A Python set in memory guarantees nothing after a crash; effect records must be durable and coordinated with the effect.
  • SUPPLIER-SVC is a technical identity; the messages alone identify no person or certain number of physical openings.

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.

Event
A message reporting a request or fact to process.
event_id
Identifier of an event envelope; repeating it may reveal an exact replay.
Business key
Stable identifier of the real action, here command_id.
Duplicate
An already received message or action whose repeat must not create a new effect.
Idempotent
Producing the same result even when an operation is requested several times.
Service identity
Identity used by a program or technical key, distinct from a proven person.
Replay
Reading retained events again, for example after a stop.

Comprendre les garanties et le format d’UDP

UDP transmet des datagrammes en préservant les limites de message, sans assurer de lui-même leur livraison, leur ordre ni la suppression des doublons. Il n’établit pas la connexion TCP préalable. L’absence de certaines opérations de transport réduit le mécanisme de base mais ne garantit pas qu’une application UDP soit toujours plus rapide. Le récepteur ou le réseau peut être saturé ; l’application doit avoir une politique sur pertes, répétitions et congestion.

L’en-tête UDP contient port source, port destination, longueur et checksum, chacun sur deux octets, soit huit octets. La longueur comprend en-tête et données. Le champ seize bits va au plus à65 535, pas65 536. Pour IPv4 avec en-têtes minimaux, la charge UDP maximale théorique usuelle est65 507 octets ; la MTU du chemin impose généralement des messages bien plus petits pour éviter une fragmentation défavorable. Des mécanismes IPv6 particuliers existent mais ne sont pas la base de cet atelier.

Le checksum UDP est une somme de contrôle incluant une pseudo-en-tête IP, l’en-tête UDP et les données ; ce n’est pas le CRC Ethernet. Il sert à détecter des erreurs, sans authentifier l’émetteur ni prouver absolument l’identité du message. Les règles de présence du checksum diffèrent entre IPv4 et IPv6. Les contrôles de liaison et de transport ne sont pas redondants par définition : ils couvrent des périmètres différents, et un chemin peut employer plusieurs liaisons ou produire une erreur ailleurs que sur le câble local.

Le livre cite radio, télévision et téléphonie sur IP comme exemples sensibles à la latence, ainsi que DNS et SNMP. Il ne faut pas transformer ces exemples en classement exclusif : la vidéo peut utiliser HTTP sur TCP ou QUIC, et DNS utilise aussi TCP et des transports chiffrés. La limite de512 octets évoquée dans cette édition n’est pas une limite générale d’UDP. Choisir le transport en fonction du protocole applicatif et des exigences mesurées, pas d’une association figée entre type de média et protocole.

Pour un événement data, noter un identifiant, une version de schéma et une heure utile ; décider comment détecter ou tolérer les pertes et doublons au niveau applicatif. Une réception UDP réussie ne signifie pas que tous les événements précédents sont arrivés. Un acquittement applicatif peut confirmer davantage, mais il faut alors définir ce qu’il confirme : octets reçus, validation, écriture durable ou traitement métier.

À toi de jouer

Un collecteur UDP reçoit les identifiants100,102,102. Que sait-on et que manque-t-il pour conclure ?

Voir la correction expliquée

On observe un saut et une répétition, mais le mécanisme d’identifiants, l’ordre attendu et les autres points d’observation sont nécessaires pour conclure à une perte ou un doublon. UDP seul n’assure pas la séquence complète.

Références : RFC 768 — UDP · RFC 9000 — QUIC.

Adapté de Apprenez le fonctionnement des réseaux TCP/IP, Romain Guichard (Caelifer), elalitte, pages 149–151. Consulter le PDF source et ses illustrations · Provenance. Licence Creative Commons 6 2.0 (mention extraite de la couverture ; variante non identifiée)

Comprendre l’incertitude et les compensations

Le problème des deux généraux décrit deux acteurs qui doivent agir ensemble mais communiquent par messages pouvant se perdre. Dans la version non militaire des notes, deux personnes veulent se retrouver : si une seule vient, le résultat est mauvais. Un message de proposition suivi d’un accusé de réception ne produit pas une certitude partagée, car l’émetteur de l’accusé ignore si celui-ci est arrivé.

Agir sans confirmation risque de laisser un acteur seul. Attendre une confirmation transfère ce risque à son partenaire, qui pourrait alors attendre une confirmation de la confirmation. Pour tout échange fini, la perte du dernier message laisse une ambiguïté. Envoyer davantage de messages peut augmenter la confiance sous certaines hypothèses probabilistes, sans créer de connaissance commune certaine sur un canal qui peut les perdre tous.

Deux scénarios peuvent être indiscernables pour un nœud : la requête est reçue mais sa réponse disparaît, ou la requête elle-même n’arrive jamais. Les messages sont notre moyen d’apprendre l’état distant ; une observation reçue peut déjà être ancienne. Cette limite explique pourquoi un timeout ne constitue pas une preuve d’échec métier et pourquoi les procédures de rapprochement sont nécessaires.

Une boutique veut expédier si et seulement si le paiement a lieu. Ce cas ressemble au problème précédent, mais possède une différence décisive : un paiement peut souvent être remboursé. Le protocole pratique tente le paiement, puis l’expédition, et rembourse si celle-ci devient impossible. Après une coupure, le service peut interroger l’état des transactions et réconcilier les résultats. Une expédition physique ou une action irréversible ne s’annule pas avec la même facilité.

Pour un pipeline, réserve une ressource, prépare un résultat, puis publie un pointeur de catalogue ; si la publication échoue, une procédure de nettoyage peut compenser les ressources préparées. Une compensation est une nouvelle action métier avec ses propres échecs possibles : elle n’efface pas magiquement l’histoire. Choisis explicitement les actions réversibles, les états intermédiaires, le journal et les tentatives de rapprochement.

À toi de jouer

Un service réserve un espace de stockage, puis une autre opération refuse la livraison du lot. Propose un protocole de compensation et indique l’incertitude qui reste si l’accusé du nettoyage se perd.

Voir la correction expliquée

Enregistrer un identifiant stable, tenter de libérer la réservation et consulter ensuite son état jusqu’à confirmation durable. La perte de l’accusé peut signifier que la libération a réussi ; il faut donc pouvoir la répéter sans supprimer une nouvelle réservation sans rapport. Une réservation/version identifiée évite cette confusion.

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 16–18. 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