Chapter 15 · Course 2 c15-m02
Can a backup really take us back?
Your goal Plan an isolated restore, verify the recovered data, and calculate RPO and RTO from a simple timeline.
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 the new data recruit at Aster Motors. Luca was hurt when a car resembling the Noctis 01 crashed; the prototype is missing, and Voss is trying to blame you with an authorization bearing your name. Data lead Mara Sol and investigator Imani found an older backup of the log. It may contain a delivery absent from the report published after the crash. A file labeled 'backup' is not yet usable evidence: the team must open it without changing originals and check what is inside.
This lesson stands on its own. PostgreSQL is a program that organizes data in tables. pg_dump exports a PostgreSQL database; with its custom -Fc format, pg_restore can inspect and rebuild the archive. You will read a procedure for restoring to a separate practice database, verify row identifiers, and calculate RPO, the data loss period a team can tolerate, and RTO, the time it aims to take to restore service. Commands are examples; no real database is changed.
Before the lesson
Purpose of this course
Plan an isolated restore, verify the recovered data, and calculate RPO and RTO from a simple timeline.
Topics covered
Explain the difference between creating an archive, listing it, and restoring it.; Restore into a separate database and verify particular rows.; Calculate RPO and RTO in minutes with stated start and end times.; Say what a backup can show and what it cannot prove yet.
What you will learn
- Explain the difference between creating an archive, listing it, and restoring it.
- Restore into a separate database and verify particular rows.
- Calculate RPO and RTO in minutes with stated start and end times.
- Say what a backup can show and what it cannot prove yet.
PART 1 · THE LESSON
Understand step by step
Lesson · explanation
Why an older copy matters to 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 uses an authorization under your name to blame you. Imani and Mara find a log backup from before the post-crash report. It might hold a row that the published report no longer shows. Check it before making a claim.
A database resembles a well organized set of tables. PostgreSQL is software that keeps those tables and answers SQL questions. A backup is a copy meant to recover data after failure or compare versions. Owning a file called backup does not guarantee it opens or contains the right rows. A name on a file is a starting claim, not a completed check.
Imagine finding a photocopy of a notebook in a box. Its label says yesterday, but you must check that it is the right notebook, every needed page is readable and it was not mixed with another copy. For our archive, that means knowing its origin, restoring it elsewhere and checking specific row identifiers.
This mission uses a fictional copy; the PostgreSQL commands are examples to read. Do not alter an original database or reveal any secret. The story's meeting creates urgency, not a real timer. Your goal is to show what the backup allows the team to compare and calculate how much data and time an incident might cost.
Pause and think
Why is a file named backup not enough as evidence?
See the explanation
Check its origin, restore it and inspect actual rows without changing originals.
Lesson · explanation
Create an archive with pg_dump
pg_dump exports a PostgreSQL database. In the example, pg_dump -Fc -f practice.dump practice_db reads the practice database practice_db and writes practice.dump. -Fc selects custom archive format; -f names the output file. This file is not an ordinary document that you understand by opening it as plain text.
Think of a labeled moving box. Packing the box is one step; knowing what is inside and returning each item to its place are other steps. Likewise, a successful pg_dump does not prove that a restore will contain the expected table. A backup becomes useful when people can inspect, rebuild and verify it.
Custom format lets pg_restore select objects to restore. But pg_dump exports one database, not automatically every role and setting in a whole PostgreSQL installation. An occasional logical archive is not a complete continuous recovery plan. Saying we have a file differs from saying the entire service can return exactly as it was.
Origin matters. An untrusted archive can contain objects that execute code during restoration. The team uses an approved copy in an isolated environment with appropriate access. In this lesson you read the procedure; you do not run it on a real database. An investigative backup should remain protected because it may contain sensitive data.
Pause and think
Which tool creates practice.dump, and what does -Fc mean?
See the explanation
pg_dump creates it; -Fc selects PostgreSQL's custom archive format.
Lesson · explanation
Inspect the archive before restoring it
pg_restore --list practice.dump displays objects described by the custom archive: tables and other items PostgreSQL could rebuild. It is like reading a box inventory before unpacking. You can check whether the archive appears to match the expected database. Listing does not load those objects into a destination.
An object list does not prove that every row is usable. An inventory may mention a folder without guaranteeing all its pages can be read. You still need to restore into a separate space, run queries and inspect results. Treating --list as a complete restore would give Imani more confidence than the evidence warrants.
Next the example creates practice_restore with createdb. This is a disposable destination distinct from practice_db and the investigation's originals. A visible destination name in the commands lets you verify where objects will be loaded. The wrong destination could mix an archive into a database under study or overwrite important information.
In a real lab, the team would also check permissions, available space and compatibility with the approved destination. This exercise focuses on the logical order: make a practice archive, list it, prepare a separate database, restore and verify. Each stage answers a different question and leaves a trace that can be explained to another person.
Pause and think
What does pg_restore --list show, and what does it not yet establish?
See the explanation
It lists announced archive objects; it does not prove restored rows are readable and consistent.
Lesson · explanation
Restore separately and inspect specific rows
pg_restore --exit-on-error --dbname=practice_restore practice.dump loads the approved archive into a separate practice database. --dbname names the destination; --exit-on-error asks the tool to stop on an error rather than continue silently. It must not target the original database. Picture opening a photocopy on a worktable instead of pasting it over the original notebook.
When the command finishes, checking is not over. psql --dbname=practice_restore -c can run a reading query such as SELECT event_id FROM events ORDER BY event_id;. That returns identifiers in the events table. Inspect expected tables, row counts and important values too. A command ending without an error does not replace these concrete checks.
The fictional copy should have R1 and TRANSFER-7. If the query shows only R1, the demonstration has not recovered the announced clue; inspect the archive, schema or restore before proceeding. If it shows both, the team has a repeatable observation. Identifiers may not be enough on their own; other columns and timestamps can explain what the rows mean.
Keep archive origin and time, a checksum if the team uses one, destination, commands and verification results. Another person can rerun the test and check your observation. If a table is missing or the schema changed, report that limitation. A partly successful restoration must not be presented as a perfect copy.
Pause and think
Which IDs should appear in this exercise's practice_restore database?
See the explanation
R1 and TRANSFER-7 should be readable in the restored copy.
Lesson · explanation
Compare the copy with the report without changing either
The checked restored backup contains R1 and TRANSFER-7. The post-crash published report contains only R1. Compare sets of identifiers: IDs in the copy minus IDs in the report give TRANSFER-7. That is a precise discrepancy, more useful than saying the documents differ. Imani can investigate where the data path diverged.
Imagine two package lists. An older warehouse list mentions A and B, while today's public list mentions only A. You can establish that B appears in the old list but not the new one. You cannot yet tell whether B was delivered, canceled, copied badly or removed deliberately. The list difference is an observation; explaining it requires more traces.
In the case, TRANSFER-7's presence in an earlier version does not automatically prove who removed it from the report. It could reflect a correction, load failure, report filter or fraud. Do not secretly replace the published report with your copy. Preserve both versions, their times and the report-production rules for comparison.
The result still gives Mara a sharper question: why does the report supporting Voss's story omit an identifier present in an approved older archive? The next lesson will seek logs, metrics and traces around the divergence. For now, state the discrepancy and the method that exposed it without assigning intent.
Pause and think
Which ID appears in the restored copy but not the published report?
See the explanation
TRANSFER-7. The difference alone does not explain why the report lacks it or who caused the gap.
Lesson · explanation
Calculate the possible data-loss window
RPO means recovery point objective. It states the maximum span of data a team is willing to lose under its plan. In our scenario, the last known backup is at 20:50 and failure starts at 21:20. If that backup is the only return point, the gap between them is 30 minutes. Changes made during that window might be missing after restoration.
Use a timeline: 20:50 to 21:00 is ten minutes, then 21:00 to 21:20 is twenty more, totaling thirty. This is a potential window, not proof that exactly thirty minutes of useful changes vanished. Perhaps there were no changes, or some survived elsewhere. State the result with the assumption that this backup is the only return point.
The exercise's RPO target is at most 60 minutes. A 30-minute window meets it: 30 ≤ 60. A target says what the team accepts; the scenario times let us check this case. More frequent usable backups could shorten the window if they are part of the recovery plan. The archive alone does not decide what the objective should be.
Do not mix RPO with the time needed to make the service work again. RPO concerns data that might be missing between backup and failure. A backup at 21:19 would make that window shorter even if restoration still took a long time. These are different questions and need different measurements. We next measure service return with RTO.
Pause and think
What is the possible data-loss window from 20:50 to 21:20, and does it meet a 60-minute target?
See the explanation
30 minutes; it meets the scenario's 60-minute RPO target.
Lesson · explanation
Measure full return from the moment of failure
RTO means recovery time objective: how long the team aims to take before service is usable again after failure. Here failure starts at 21:20. The isolated restore begins at 21:30, and data is verified at 22:10. The full observed return runs from 21:20 to 22:10, or 50 minutes.
Break that into parts. From 21:20 to 21:30, ten minutes pass before restoration begins. From 21:30 to 22:10, the restoration and verification phase lasts forty minutes. Ten plus forty equals fifty. Reporting only forty minutes as observed RTO would omit the delay before work began. Always declare the starting point.
The exercise's RTO target is at most 45 minutes. An observed 50-minute return exceeds it by five minutes. That does not cancel the RPO result: the 30-minute potential data gap met its separate 60-minute target. One data-loss measure can pass while the service-return measure fails. The two scores cannot substitute for each other.
A team can reduce RTO with restore drills, prepared environments and faster failure detection. This lesson does not claim one file automatically makes a service available. Verification at 22:10 is part of return: a database technically loaded but not checked for important rows is not yet a reliable result for this mission.
Pause and think
Why is observed RTO 50 minutes rather than the 40-minute restore phase?
See the explanation
It starts at failure at 21:20 and ends at verified return at 22:10; the ten minutes before 21:30 count too.
Lesson · explanation
Give Imani a reproducible result
Before the fictional meeting, Mara asks for a clear demonstration. State the order: make the practice archive with pg_dump -Fc, inspect it with pg_restore --list, create practice_restore, restore with pg_restore --dbname=practice_restore, and run a checking SELECT. Each command has a different purpose. None should target an original case database in this demonstration.
Then give the checked facts: R1 and TRANSFER-7 are in the restored copy, while the report shows only R1. Preserve both versions and their times. If restoration was incomplete, report that before comparing. The discrepancy becomes strong only after the archive was inspected, restoration succeeded and expected rows were verified. A backup label alone is insufficient.
State time spans with boundaries: 20:50 → 21:20 gives a potential 30-minute gap, under the 60-minute RPO target. 21:20 → 22:10 gives a 50-minute observed return, over the 45-minute RTO target. The phase beginning at 21:30 lasts only 40 minutes. Naming the exact times subtracted prevents a plausible but wrong answer.
Finish with the evidence limit. TRANSFER-7 exists in this earlier version but is absent from the report under study. The team must still find where and why the row left the path to the report and whether a person acted. The next lesson examines traces of that path. Here you made an old file into a checkable comparison without altering originals.
Pause and think
Which conclusion fits both the checked restore and uncertainty about cause?
See the explanation
TRANSFER-7 is in this older copy and absent from the report; the cause and any responsible person still require investigation.
Visual guide
One copy and two time spans
- 120:50: known backup
- 221:20: failure / latest state unavailable
- 321:30: isolated restore begins
- 422:10: restored data verified
Scenario RPO = 30 min; restore phase = 40 min; full return from failure = 50 min.
Code · read each line
Calculate time spans and compare identifiers
from datetime import datetime
def clock(value):
return datetime.strptime(value, "%H:%M")
backup_at = clock("20:50")
failure_at = clock("21:20")
restore_started = clock("21:30")
restore_verified = clock("22:10")
rpo_minutes = int((failure_at - backup_at).total_seconds() / 60)
restore_phase_minutes = int((restore_verified - restore_started).total_seconds() / 60)
rto_minutes = int((restore_verified - failure_at).total_seconds() / 60)
backup_events = {"R1", "TRANSFER-7"}
restored_events = {"R1", "TRANSFER-7"}
published_report = {"R1"}
print("RPO", rpo_minutes, "minutes")
print("restore_phase", restore_phase_minutes, "minutes")
print("RTO", rto_minutes, "minutes")
print("restored_matches_backup", restored_events == backup_events)
print("missing_from_report", sorted(restored_events - published_report))The local Python script prints 30 minutes from backup to failure, 40 minutes for the restore phase, and 50 minutes from failure to verified return (observed RTO). It confirms both backup identifiers were recovered and flags TRANSFER-7 missing from the report.
Configuration · read the values
Read a PostgreSQL practice procedure
# Illustration only: a separate, disposable practice database is required.
pg_dump -Fc -f practice.dump practice_db
pg_restore --list practice.dump
createdb practice_restore
pg_restore --exit-on-error --dbname=practice_restore practice.dump
psql --dbname=practice_restore -c "SELECT event_id FROM events ORDER BY event_id;"pg_dump -Fc creates a custom archive; pg_restore --list describes it; createdb prepares a separate destination; pg_restore loads it there; psql checks identifiers. These are examples to read. They assume PostgreSQL, an authorized practice database, and an approved archive. This course does not run them.
PART 2 · WATCH IT WORK
A complete worked example
Follow each step, then the result
Worked example: the recovered row
Backup at 20:50; failure at 21:20; restore starts at 21:30; verification ends at 22:10. The copy has R1 and TRANSFER-7; the report has R1 only.
- Restore the approved archive into practice_restore, never over the original, and check that R1 and TRANSFER-7 are readable.
- Calculate 21:20 − 20:50 = 30 minutes of potentially missing changes.
- Calculate 22:10 − 21:20 = 50 minutes to full recovery; the restore phase itself lasts 40 minutes.
- Compare sets: TRANSFER-7 is present in the copy and absent from the report. Record the difference and preserve both versions.
A backup is useful when its restoration and contents are checked; recovery times need a precise starting point.
How this helps with your missionFor Imani, inspect the approved archive, restore it into practice_restore and verify R1 and TRANSFER-7 without touching originals. The report contains only R1: record the difference without assigning a cause. From backup 20:50 to failure 21:20, the scenario's RPO window is 30 minutes and meets target 60. From failure 21:20 to verified data at 22:10, observed return is 50 minutes and misses RTO target 45; the phase begun at 21:30 takes 40 minutes.
PART 3 · YOUR TURN
Use the lesson to solve the mission
Story scene · practical task
Mission: the forgotten log copy
Imani puts a post-crash report and an older archive in front of you. Voss claims the report never omitted a transfer. Mara asks for a repeatable demonstration in a separate practice lab before the fictional meeting. Do not change original databases or expose secrets. The urgency is part of the story; the exercise has no timer.
Your task
- Put pg_dump, pg_restore --list, a separate database, pg_restore, and SQL verification in order.
- Name the two identifiers expected in the backup and the one absent from the report.
- Calculate scenario RPO and complete return from failure; compare them with 60- and 45-minute targets.
- Write a careful conclusion about what the difference between copy and report shows.
How to know you have succeeded
- Archive inspected and restored only to a practice destination.
- R1 and TRANSFER-7 recovered; TRANSFER-7 missing from report.
- RPO 30 min ≤ 60; full return 50 min > 45.
- The discrepancy is confirmed, but its cause and author remain unknown.
Try code or SQL and keep a local draft. The mission questions are checked separately below.
See the worked answer
- pg_dump -Fc exports the archive; pg_restore --list inspects it; create practice_restore; pg_restore --dbname=practice_restore loads it; SELECT verifies rows.
- The practice copy contains R1 and TRANSFER-7. The published report has R1 only. Keep both versions and their timestamps.
- 21:20 − 20:50 = 30 minutes of potential data loss, meeting a 60-minute target. 22:10 − 21:20 = 50 minutes to full return, missing a 45-minute target. The code's 40 minutes is only the phase begun at 21:30.
- A verified restore shows that TRANSFER-7 existed in this earlier version. It does not show who removed it from the report or whether the difference came from a correction, loading error, or fraud.
You now have a checked earlier version and a precise discrepancy. Next you will inspect logs, metrics, and traces to find where the data pipeline diverged.
Before you leave
Remember this
pg_dump -Fccreates a custom archive of one database;pg_restore --listlists announced objects.- Restore an approved archive into a separate practice database, then check tables, rows and IDs.
- The fictional copy contains R1 and TRANSFER-7; the report contains only R1.
- The possible gap from backup 20:50 to failure 21:20 is 30 minutes, within RPO target 60.
- From failure 21:20 to verification 22:10, return takes 50 minutes, exceeding RTO target 45.
- The copy-report discrepancy is a checked lead; it does not alone establish its cause or 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.
- PostgreSQL
- A database system that stores data in tables and answers SQL queries.
- Backup
- A copy used to recover data if the original becomes unavailable or wrong.
- pg_dump
- A PostgreSQL tool that exports one database as a script or archive.
- pg_restore
- A tool for inspecting or rebuilding a database from a pg_dump archive.
- Restore
- Rebuilding data from a backup.
- RPO
- The maximum period of data a team is willing to lose under its backup strategy.
- RTO
- The target time for making a service usable again after failure.
- Verification
- A concrete check that expected tables and rows are present and consistent.
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.
Produire une sauvegarde logique et vérifier la restauration
mysqldump est un programme client lancé depuis le terminal, pas une instruction SQL à envoyer dans l’invite mysql>. Il peut produire un script de définition et de rechargement des données. Le fichier est un artefact sensible : il peut contenir toutes les données lisibles par le compte de sauvegarde. Son emplacement, ses accès, sa conservation et son transfert doivent être prévus.
Une commande comme mysqldump -u sauvegarde -p atelier_data > atelier_data.sql redirige la sortie vers un fichier local. Le shell peut écraser le fichier existant ; nomme les versions et contrôle le code de sortie. Sous PowerShell, vérifie aussi l’encodage et le mécanisme de redirection de la version utilisée, ou l’option --result-file du client. Le répertoire courant est celui du terminal au lancement, pas une propriété du serveur.
L’option historique --opt regroupe plusieurs réglages et est activée par défaut dans les versions documentées ; elle n’est pas une garantie universelle de sauvegarde rapide et cohérente. Pour des tables InnoDB, --single-transaction peut servir à une vue cohérente, sous les conditions documentées et avec précautions concernant les DDL concurrents. Vérifie aussi la couverture des vues, routines, déclencheurs, événements, droits et autres objets nécessaires à la reprise.
Un dump d’une base nommée sans options supplémentaires ne contient pas forcément CREATE DATABASE. Une restauration exige une base cible préparée et un compte autorisé : mysql -u restauration -p base_cible < fichier.sql dans un shell compatible, ou SOURCE depuis le client après USE base_cible. Restaurer peut modifier ou remplacer des objets ; fais l’essai sur une cible isolée.
Une sauvegarde n’est prouvée utilisable qu’après restauration et contrôles : nombre de lignes, contraintes, quelques requêtes métier et paramètres nécessaires. Distingue intégrité du fichier, cohérence logique et capacité de reprise au moment voulu. Les exemples de sauvegarde du livre enseignent la mécanique ; une politique opérationnelle comprend aussi fréquence, rétention, séparation des accès et objectifs de perte et délai acceptables.
Exemple appliqué aux données
# Terminal autorisé, fichier de destination nouveau :
mysqldump -u sauvegarde -p --single-transaction --result-file=atelier_data.sql atelier_data
Export mysqldump --single-transaction puis restauration et égalité des lignes vérifiés sur MySQL 8.4.13 isolé. Essai avec root local de laboratoire ; le compte sauvegarde et sa politique de droits restent à configurer dans votre environnement.
À toi de jouer
Un fichier dump existe et a une taille non nulle. Est-ce une preuve suffisante de restauration ?
Voir la correction expliquée
Non. Il faut contrôler la réussite de la sauvegarde, restaurer sur une cible isolée et vérifier les données, objets et requêtes nécessaires. Une taille seule n’établit ni couverture ni cohérence.
Références : Sauvegarde logique.
Adapté de Administrez vos bases de données avec MySQL, Chantal Gribaumont (Taguan), pages 66–67. 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)