Chapter 19 · Course 3 c19-m03
How can we trace a deletion?
Your goal Reconstruct a row's creation, update, and deletion from CDC events without confusing current absence with never having existed.
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.
Story · optional context
The story so far
You are Aster Motors' new data recruit. Luca was hurt in a crash involving a car resembling the missing Noctis 01 prototype, and Voss accuses you. Mara Sol and Imani found two register versions: S100 does not authorize the departure in your name, while S101 displays an authorization and OPEN-18. A technical field was added without erasing S100. Imani looks for row AUTH-9 linking these facts, but it is missing from the current register. Voss says that an absent row never existed.
This lesson stands alone. PostgreSQL records write information in its write-ahead log, or WAL. Change data capture, called CDC, turns committed writes into readable events. Debezium can follow PostgreSQL and send creates, updates, and deletes to Kafka. You will reconstruct a deleted row's history and distinguish a delete event from a Kafka tombstone used in topic compaction.
Before the lesson
Purpose of this course
Reconstruct a row's creation, update, and deletion from CDC events without confusing current absence with never having existed.
Topics covered
Describe WAL, logical decoding, and the purpose of a CDC connector in simple terms.; Read c, u, and d operations with their key and LSN positions.; Explain why a delete event and Kafka tombstone carry different information.; Preserve change evidence without attributing an action to a person from one metadata field.
What you will learn
- Describe WAL, logical decoding, and the purpose of a CDC connector in simple terms.
- Read c, u, and d operations with their key and LSN positions.
- Explain why a delete event and Kafka tombstone carry different information.
- Preserve change evidence without attributing an action to a person from one metadata field.
PART 1 · THE LESSON
Understand step by step
Lesson · explanation
The missing row and the question we must answer
You are the new data recruit at Aster Motors. Luca was injured in a crash involving a car resembling the missing Noctis 01 prototype. Voss accuses you of authorizing its departure. Mara and Imani already found two register versions: S100 does not show your authorization, while S101 shows an authorization and the OPEN-18 command. A row called AUTH-9 could connect those clues, but it is missing from the current register.
Imagine an authorization notebook. If a page has been torn out today, opening the notebook now does not prove the page was blank yesterday. We need a dated copy, a change history, or other trustworthy evidence. In our case, a copy of CDC events contains a creation, an update, and a deletion. This lesson shows how to read those traces without treating current absence as proof that the row never existed.
Our precise goal is to explain what happened to AUTH-9, in what order, and what the evidence can truly establish. You will see four messages with the same key. Three describe database changes; the fourth is a signal used by Kafka. There is no need to connect to Aster's real database. The supplied Python code only replays fictional messages in a small local state.
Do not confuse a plausible story with a proven accusation. S100 and S101 show different states if their sources and clocks check out. Authentic and sufficiently complete CDC messages can explain why a row disappeared. They do not automatically reveal the human who caused the write. Keeping this distinction clear will protect both the investigation and anyone who might be blamed unfairly.
Pause and think
If AUTH-9 is absent today, what do you immediately know about its past?
See the explanation
Only that it is absent from the current state; retained traces are needed to describe its past.
Lesson · explanation
The WAL records database writes
PostgreSQL is software that stores tables, rather like notebooks with rows and columns. When an operation changes a table, PostgreSQL first records information needed for that write in its WAL. WAL stands for write-ahead log. Among other jobs, it helps the database recover after a failure. It is not a video of the screen or a diary naming every person who touched the keyboard.
Imagine a kitchen writing confirmed orders in a notebook before changing its list of meals to prepare. If the lights go out, the notebook helps staff resume. The WAL has a comparable role for database writes. We still have to distinguish a committed change from an abandoned attempt. The CDC feed we discuss represents committed changes made readable through logical decoding, rather than every command somebody considered.
Logical decoding turns information in the log into changes another program can understand: a row was created, updated, or deleted. Change data capture, called CDC, carries that history as events. Debezium can read PostgreSQL changes and publish them to Kafka. Kafka is a messaging system; in this lesson it carries records to read later. It does not send driving commands to the Noctis car.
In our example, op=c means create, op=u means update, and op=d means delete. The after field shows a new state when available; before may show an old state depending on configuration. A wrong reading would treat d as a missing value without action. In this copy, it is a deletion operation. Yet a copied event still needs a verified source before it becomes strong evidence.
Pause and think
What does logical decoding do here?
See the explanation
It makes committed WAL changes readable as create, update, or delete events.
Lesson · explanation
A key and an LSN keep the clues together
Every message in our copy has the key AUTH-9. A key is a stable label that helps us follow the same row through several messages. Think of printing the same number on different versions of a card. Its content can change, but the number tells us which card we are following. The key does not name a culprit; services, automated tasks, and people may all affect one row.
Each database change also has an LSN, short for Log Sequence Number, a position in this PostgreSQL source's WAL. The markers 0/100, 0/120, and 0/140 put the three example writes in that order. Think of page positions in a technical notebook. They help order changes from that source. They are not times displayed by a clock, nor minutes elapsed between events.
A garage gate log may show a time while our CDC event shows an LSN. It would be wrong to compare 0/120 directly with 09:20 or infer the crash time from it. To connect the sources, check clocks, corresponding events, and provenance. A larger LSN in this example supports source order; it does not tell us how far the car traveled or who was at the gate.
CDC begins at a configured point. If the connector was not listening before 0/100, older changes might be missing. Even a feed with no visible gap cannot prove the row had never existed before that point. Record the originating database, captured table, capture period, continuity of positions, and how the copy was preserved. The scope of a conclusion depends on those checks.
Pause and think
Does LSN 0/140 give the exact time of deletion?
See the explanation
No. It is a PostgreSQL log position useful for ordering changes from that source.
Lesson · explanation
Create AUTH-9 and then change its approval
The first message has op=c, the key AUTH-9, and LSN 0/100. Its after field contains approved=False. Start with an empty local state; after that event, put AUTH-9 in it with approval false. If the event truly comes from the verified source, it shows the row existed during the period covered by the copy. It does not say why anyone created it.
The second message has op=u at 0/120. Its before field says approved=False, while after says approved=True. An update replaces the current value for the same key. Replaying the messages in order gives false first and true second. Imagine one card whose approval box starts unchecked and is later checked. It is still the same card labeled AUTH-9.
It would be wrong to say False means the row was absent. After creation, the row exists; only its approval value is false. It would also be wrong to say True was already present when the row was created. The first message says otherwise. Both states matter to the investigation: Voss displays a recent authorization, while the sequence shows an observable change.
The before field can be absent or limited under other connector settings. Our copy supplies it for this update, so we can compare old and new values clearly. In a real system, first inspect the event schema before relying on a field. Neither before nor after identifies the person who pressed a key. They describe data states, not a human author.
Pause and think
After op=u at LSN 0/120, what is the current approved value?
See the explanation
approved=True; immediately before the update the copy showed False.
Lesson · explanation
Deleting a row does not erase a preserved history
The third change has op=d and LSN 0/140. In this copy, before contains approved=True and after is None. The script removes AUTH-9 from its small dictionary of current rows. Querying that dictionary after the third event finds no row. Deletion answers the question about current state, but current state alone cannot answer the whole question about history.
Imagine a classroom board where a name is erased after someone photographed three stages. The board no longer shows the name, yet retained photos show it was there. Here, the c, u, and d events are a comparable trace, provided their origin is verified. The delete event matters because it explains how the state moved from row present to row absent.
Our delete event includes the previous value. That detail depends on connector configuration and should not be promised for every database. Even without it, reliable earlier events might show the former value; check what was actually captured. A counterexample would be to invent the row's old contents after seeing a delete event that carries no previous state and no earlier record.
Mara can accurately say this: in the verified copy, AUTH-9 was created with False, updated to True, and deleted at 0/140; it is absent from the final reconstructed state. Saying it never existed conflicts with that sequence. Saying Voss deleted it goes beyond those messages. Evidence of a data change and evidence of the human responsible are different things.
Pause and think
Why does an empty final state not prove AUTH-9 never existed?
See the explanation
Because preserved events show its creation, update, and deletion.
Lesson · explanation
The Kafka tombstone has a different job
A fourth message arrives with the same AUTH-9 key, but its entire value is null. It is a Kafka tombstone. It follows the op=d event and does not, by itself, describe the row's former value. In a compacted topic, that marker allows Kafka to remove the last stored value for the key during compaction. It helps manage retained messages rather than narrate every detail of the deletion.
Imagine a box of cards that mainly keeps the latest card for each number. A blank card labeled AUTH-9 can signal that even the last card for that number should leave the organized box. This is different from the story of the delete operation, with its LSN and possibly its prior content. In our copy, that story is the third message, op=d at 0/140.
The script first checks whether the message's entire value is None. If it is, the script records tombstone in history and goes on without applying a second delete. Otherwise it reads op from the value. This distinction avoids a programming mistake: reading value['op'] from a null value would fail, while counting the tombstone as another d would distort the timeline.
Compaction and retention rules can remove older messages from a topic. Therefore the current Kafka topic is not necessarily a complete investigation archive. Before needed traces disappear, an authorized team must preserve a copy with source information and integrity checks. The wrong decision would be to discard all previous events because a tombstone exists. A tombstone alone cannot reconstruct the previous approval value.
Pause and think
Which message describes deletion, op=d or the null tombstone?
See the explanation
The op=d event describes deletion; the null tombstone is used for Kafka compaction.
Lesson · explanation
The connector has a defined scope and limits
Debezium can read PostgreSQL changes through a logical replication slot. The slot keeps a reading position, like a bookmark. The connector turns suitable changes into messages and publishes them to Kafka here. The chain is database, WAL, logical decoding, connector, messages. Misconfiguring any link can leave gaps or mix sources, even if our small local Python script runs perfectly.
If the reader stops, a slot can retain WAL longer than expected and use more disk space. Access to logs and messages also needs control because data can be sensitive. In this lesson you create no real slot and connect to no service. You study a supplied simulation and note what would need checking in a properly authorized environment.
For a defensible trace, ask which server and table were captured, from which starting position, with which event schema and retention rule. Check that AUTH-9 identifies the same row across the three changes. A pasted list without source details may contain copying errors. LSN order is helpful, but the provenance and integrity of the copy matter as well.
S100 and S101 give another angle: they show preserved register states. They may support the conclusion that a change occurred, once their table, provenance, and clocks are checked. Do not automatically assume each snapshot matches a particular LSN in our copy. Connecting the two sources requires a verified timeline and preservation chain. An apparent agreement is a reason to inspect, not a shortcut to certainty.
Pause and think
Why must we check the CDC connector's start point?
See the explanation
The feed may omit changes older than that point, so its silence cannot prove they never happened.
Lesson · explanation
Write a conclusion the team can defend
Imani puts the four messages on the table while Voss displays the empty register. Give your answer in a simple order. First name the AUTH-9 key and three positions: create at 0/100, update at 0/120, and delete at 0/140. Next give the successive states: False, then True, then no current row. Finally explain that the same-key null message is a Kafka tombstone, separate from the described deletion.
In the story, Mara must prepare a report quickly so an incomplete screen does not settle an accusation. The exercise itself has no real timer. A good report says the preserved events contradict Voss's claim that an absent row never existed. It does not claim every event from all time is known. The capture has a scope and a starting point that must be checked.
To find who caused the change, the team needs more than AUTH-9 and LSN values. It can examine independent access logs, service accounts, an approved change request, and permissions at that time. Even those clues need comparison: a technical identity can be shared or automated. Do not turn Voss's role in the story into a result supposedly calculated by the script.
Your result helps the mission in two ways. It preserves a lead hidden by the current register, and it points to the next checks without accusing someone at random. The next lesson considers retention and expiration of versions: a team must decide what to preserve before compaction or retention removes useful traces. Here you learned to separate present state, change history, and human attribution.
Pause and think
What can the four messages alone prove about Voss personally?
See the explanation
They cannot attribute the change to Voss; they show AUTH-9's history in the copy, not the human writer.
Visual guide
AUTH-9's lifecycle
- 1LSN 0/100: c → approved=false
- 2LSN 0/120: u → approved=true
- 3LSN 0/140: d → row deleted
- 4Kafka: same-key tombstone with null value
A row absent from the current register may have a history preserved in CDC events.
Code · read each line
Replay four fictional change messages
events=[
{"key":"AUTH-9","value":{"op":"c","lsn":"0/100","after":{"approved":False}}},
{"key":"AUTH-9","value":{"op":"u","lsn":"0/120","before":{"approved":False},"after":{"approved":True}}},
{"key":"AUTH-9","value":{"op":"d","lsn":"0/140","before":{"approved":True},"after":None}},
{"key":"AUTH-9","value":None},
]
current={}
history=[]
for event in events:
value=event["value"]
if value is None:
history.append("tombstone")
continue
op=value["op"]
if op=="d":
current.pop(event["key"],None)
else:
current[event["key"]]=value["after"]
history.append(op+" "+value["lsn"])
print("events",history)
print("final_row",current.get("AUTH-9"))
print("delete_lsn",events[2]["value"]["lsn"])
print("tombstone_value",events[3]["value"])The script applies c, u, and d to local state, then recognizes a tombstone without treating it as a second delete. Final state has no row but history remains.
PART 2 · WATCH IT WORK
A complete worked example
Follow each step, then the result
Worked example: the vanished row
AUTH-9 exists at 0/100, changes at 0/120, is deleted at 0/140, and then receives a Kafka tombstone.
- Start empty and apply c: AUTH-9 has false.
- Apply u: AUTH-9 has true; keep old and new values if the event provides them.
- Apply d: remove AUTH-9 from current state but record LSN 0/140 in history.
- Read the null tombstone as a compaction signal, not a detailed account of the deleted row.
Deletion changes present state; a retained change event can still tell what happened.
How this helps with your missionMara can answer Voss with a checkable timeline: AUTH-9 appears at 0/100 with approved=False, changes to True at 0/120, disappears after op=d at 0/140, then receives a same-key null tombstone. This contradicts the claim that the row never existed during the copied period. The team should preserve the trace, check the feed's provenance, continuity, and scope, then compare snapshots, access logs, and change requests before attributing the action to a person.
PART 3 · YOUR TURN
Use the lesson to solve the mission
Story scene · practical task
Mission: show that the erased row existed
Voss opens the current register: AUTH-9 is gone. Imani brings four messages from the CDC copy, and Mara asks you to explain the disappearance before the team drops the lead. In the fiction the case must move quickly; the exercise has no timer.
Your task
- Order c, u, d, and tombstone for the same key.
- Reconstruct
approvedat each stage and final state. - Explain the difference between operation d and the tombstone's null value.
- Give a check and a limit before attributing the change to a person.
How to know you have succeeded
- 0/100, 0/120, 0/140, then tombstone.
- False, true, absent; past existence shown in the copy.
- Operation d documents deletion; tombstone supports compaction.
- Source/LSN/access checked; human author not inferred.
Try code or SQL and keep a local draft. The mission questions are checked separately below.
See the worked answer
- At 0/100 c creates AUTH-9; at 0/120 u changes it; at 0/140 d deletes it; a same-key null tombstone follows.
- The row first says false, then true, then is absent from current state. Retained events and snapshots contradict the claim that it never existed.
- The d event states the operation and may carry the previous state. A tombstone has null value for Kafka compaction and does not replace d in analysis.
- Verify connector origin, LSN continuity, feed completeness, and access logs. None of these lines automatically names the human writer.
You can follow a row through deletion. The next lesson decides how to compact and expire versions without destroying evidence that must still be kept.
Before you leave
Remember this
- The current register shows a state; preserved CDC events may tell the story of earlier changes.
- PostgreSQL writes to its WAL; logical decoding and Debezium make committed changes readable as messages.
- A common key links one row's events; LSNs order source writes but are not a universal clock.
- In the copy,
c 0/100yieldsFalse,u 0/120yieldsTrue, andd 0/140removes AUTH-9. - The Kafka
nulltombstone helps compaction and does not replace thedevent's account. - Check a CDC copy's source, start point, and retention; it does not automatically 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.
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.
- WAL
- PostgreSQL's write-ahead log, which also helps recover writes after failure.
- CDC
- Change data capture: committed database changes represented as events.
- Logical decoding
- Reading WAL changes in a form consumers can understand.
- Debezium
- A connector able to publish PostgreSQL changes as messages.
- LSN
- A PostgreSQL log position useful for ordering changes from that source.
- Operation d
- A CDC event stating that a row was deleted.
- Kafka tombstone
- A message with the same key and a null value, used by Kafka log compaction.
- Topic compaction
- A Kafka policy that may keep the latest value per key while removing older values.
Approfondissements de ce cours
Télécharger le jeu de données de cet atelier. Sa préparation sur une base de test isolée est confiée à la personne qui administre l’atelier ; les lectures utilisent ensuite le compte et les paramètres qu’elle fournit.
Conserver les versions et identifier l’acteur réel
Un audit minimal ajoute date_creation, acteur_creation, date_modification et acteur_modification à la ligne courante. Un BEFORE INSERT remplit les quatre champs ; un BEFORE UPDATE actualise les deux derniers. On peut empêcher la modification des champs de création en les recopiant depuis OLD. L’historique fourni artificiellement pour tester n’est pas une vraie date de création : si l’audit est ajouté tard, distinguer valeur inconnue, date de reprise et événement réellement observé.
CURRENT_USER() dans un trigger retourne son définisseur, dont les privilèges sont utilisés à l’exécution, et non forcément la personne qui a déclenché la modification. USER() ou SESSION_USER() décrit la connexion, avec ses propres limites. Dans un pool Python utilisant un compte technique partagé, aucune de ces fonctions n’identifie à elle seule l’utilisateur métier. Prévoir un identifiant d’acteur fiable transmis par un mécanisme contrôlé ; une variable de session librement modifiable n’est pas une preuve d’identité.
Un historique complet stocke les versions antérieures dans une table séparée, tandis que la table de base conserve la dernière version. Un AFTER UPDATE copie les colonnes OLD et un AFTER DELETE conserve la dernière image avant disparition, avec type d’événement, horodatage et informations d’acteur. Les colonnes historisées doivent couvrir les attributs nécessaires à la reconstruction ; oublier un champ critique limite ce qu’on pourra prouver plus tard.
La clé historique (id,date_histo) de l’ancien exemple peut entrer en collision si plusieurs versions du même objet ont le même horodatage. NOW() peut être identique pour plusieurs lignes d’une instruction ; même DATETIME(6) ne constitue pas une preuve d’unicité. Une clé technique AUTO_INCREMENT d’événement, complétée par un index sur (objet_id,date_histo), évite de confondre date et identité. Définir le fuseau, la précision et le sens de la date reste indispensable.
Choisir BEFORE ou AFTER dépend de ce qu’on veut conserver et du traitement de l’échec. Une table d’historique InnoDB mise à jour dans le même contexte s’annule avec la transaction ; elle conserve les modifications validées, pas toutes les tentatives. Une trace des échecs ou un audit inviolable exige un autre mécanisme et des droits adaptés. Un utilisateur capable de modifier librement les tables d’audit ou leurs triggers peut aussi altérer la preuve.
Le modèle peut combiner audit minimal, versions antérieures et archivage logique, ou séparer les suppressions dans une archive. Définir durée de conservation, accès, purge et utilité de chaque champ. Conserver indéfiniment toutes les données personnelles sans objectif ne découle pas du besoin d’historisation. L’atelier modifie puis supprime un lot et vérifie que les anciennes valeurs et les deux événements sont retrouvés dans l’ordre de leurs identifiants.
Exemple appliqué aux données
DELIMITER //
CREATE TRIGGER au_tail_histo AFTER UPDATE ON lot FOR EACH ROW
INSERT INTO lot_histo(lot_id,image_ancienne,evenement,date_histo,compte_session,definisseur)
VALUES(OLD.id,JSON_OBJECT('id',OLD.id,'jeu_id',OLD.jeu_id,'libelle',OLD.libelle,'format',OLD.format,'nb_lignes',OLD.nb_lignes,'montant',OLD.montant,'date_reception',OLD.date_reception,'date_publication',OLD.date_publication,'publie',OLD.publie,'disponible',OLD.disponible,'commentaire',OLD.commentaire,'cree_le',OLD.cree_le,'modifie_le',OLD.modifie_le),'UPDATE',NOW(6),USER(),CURRENT_USER())//
CREATE TRIGGER ad_tail_histo AFTER DELETE ON lot FOR EACH ROW
INSERT INTO lot_histo(lot_id,image_ancienne,evenement,date_histo,compte_session,definisseur)
VALUES(OLD.id,JSON_OBJECT('id',OLD.id,'jeu_id',OLD.jeu_id,'libelle',OLD.libelle,'format',OLD.format,'nb_lignes',OLD.nb_lignes,'montant',OLD.montant,'date_reception',OLD.date_reception,'date_publication',OLD.date_publication,'publie',OLD.publie,'disponible',OLD.disponible,'commentaire',OLD.commentaire,'cree_le',OLD.cree_le,'modifie_le',OLD.modifie_le),'DELETE',NOW(6),USER(),CURRENT_USER())//
DELIMITER ;
UPDATE lot SET commentaire='Révision1' WHERE id=4;
UPDATE lot SET commentaire='Révision2' WHERE id=4;
DELETE FROM lot WHERE id=4;
SELECT COUNT(*)=3 AS ok FROM lot_histo WHERE lot_id=4;
Atelier MySQL8.4 isolé : initialiser d’abord la fixture de « Préparer un état de test reproductible » dans atelier_sql_tail, puis suivre les dépendances et les résultats du guide. Les commandes client/configuration ne sont pas du Python et les redémarrages de serveur ne sont pas exécutés.
À toi de jouer
Deux UPDATE du même objet ont lieu dans une seule seconde. Pourquoi une clé(id,date_seconde) est-elle fragile, et quelle information manque si les deux actions utilisent le même compte Python ?
Voir la correction expliquée
Les deux versions peuvent partager la même date et violer l’unicité ; une identité d’événement distincte résout ce problème technique. Le compte de connexion ne révèle pas l’acteur métier : il faut un contexte d’acteur authentifié et une politique de preuve correspondant au besoin.
Références : Administrez vos bases de données avec MySQL — source2012 · MySQL8.4 — create-trigger · MySQL8.4 — account-activity-auditing · Préparer le schéma avancé (SQL) · Guide et dépendances de chaque démonstration.
Adapté de Administrez vos bases de données avec MySQL, Chantal Gribaumont (Taguan), pages 320–324. Consulter le PDF source et ses illustrations · Provenance. Licence Creative Commons 6 2.0 (libellé exact de la couverture ; modalités précises non résolues)
Rendre les reprises compatibles avec les suppressions
La réplication conserve des copies sur plusieurs nœuds pour supporter certaines fautes et répartir des lectures. Copier des données immuables est simple ; les mises à jour rendent les copies divergentes. À la différence d’un ensemble de disques RAID piloté par un contrôleur, les réplicas distribués prennent des décisions séparées et peuvent être éloignés géographiquement. Une réplication ne remplace pas à elle seule une sauvegarde historique contre une suppression ou une corruption propagée.
Une opération d’incrément n’est pas idempotente : f(x)=x+1 ne satisfait pas f(f(x))=f(x). Ajouter un identifiant à un ensemble l’est ; on peut alors déduire le compteur de la taille de l’ensemble. Une livraison au plus une fois peut perdre l’effet ; une livraison au moins une fois peut le répéter ; un effet « exactement une fois » nécessite un contrat de déduplication ou d’idempotence correctement lié à l’état durable. La capture de compteur négatif dans les notes illustre un symptôme possible, mais sa cause interne n’est qu’une hypothèse de l’auteur, pas un diagnostic établi.
L’idempotence isolée ne résout pas toutes les interactions : A ajoute x, B observe puis retire x, et une tentative tardive de A ajoute x à nouveau. L’addition répétée seule est idempotente, mais f(g(f(x))) peut différer de g(f(x)). Une autre ambiguïté apparaît lorsque x est présent sur un réplica et absent sur l’autre : cela peut venir d’un ajout incomplet ou d’une suppression incomplète. Les états sans métadonnées ne permettent pas de distinguer les intentions.
Associer une date logique à chaque mise à jour et représenter une suppression par un tombstone, une marque de suppression, conserve cette information. Un enregistrement (t,false) indique que la clé a été retirée, tandis qu’une absence peut signifier qu’elle n’a jamais été vue. Les réplicas échangent leur état par anti-entropie ; pour une clé, ils propagent la version de timestamp supérieur. Une reprise conserve le timestamp de la demande initiale, ce qui l’empêche d’écraser une modification causale plus récente. La collecte des tombstones demande un protocole séparé ; les supprimer trop tôt peut ressusciter des valeurs anciennes.
Pour un registre clé→valeur, Last Writer Wins utilise un ordre total, par exemple couple Lamport/identité, et conserve seulement la version maximale. Deux mises à jour concurrentes reçoivent alors un gagnant arbitraire : une donnée est perdue. Un registre multivaleur avec vecteurs remplace une version causalement ancienne mais conserve les versions concurrentes, appelées conflits ou siblings, pour fusion ultérieure. Les vecteurs peuvent grossir avec les clients ; des variantes réduisent ce coût sans supprimer le besoin de métadonnées.
Exemple appliqué aux données
état = {}
def appliquer(clé, version, présent):
if clé not in état or état[clé][0] < version:
état[clé] = (version, présent)
appliquer('lot', (5,'A'), True)
appliquer('lot', (8,'B'), False)
appliquer('lot', (5,'A'), True)
assert état['lot'] == ((8,'B'), False)
# Garder la marque de suppression pour ne pas ressusciter le lot.
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
Une version (5,A,true) est suivie d’une suppression (8,B,false), puis d’un nouvel essai de la première demande. Quel état conserver ? Compare ensuite horodatage physique et logique pour une base à résolution LWW, comme dans la question critique sur Cassandra des notes.
Voir la correction expliquée
Conserver la suppression de version (8,B) ; la reprise garde (5,A) et ne doit pas l’emporter. Un horodatage physique facilite certains échanges mais dépend de la synchronisation et peut ordonner une action récente avant une ancienne. Un ordre logique préserve les dépendances correctement propagées mais départage aussi arbitrairement des actions concurrentes. Évaluer le contrat exact de la base et le risque de perte plutôt que conclure qu’une horloge physique rend les conflits impossibles.
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 50–54. 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