Data Persistence: Making State Outlive a Program

Every variable you create lives in memory only while your program runs. Close the program, restart the computer or let the program crash, and those values vanish. Data persistence is the practice of storing the state a program needs so that a later run, or a different program, can pick up where the last one left off. You need it the first time you want a game to remember a high score or a to-do app to remember tomorrow's list.

Transient state versus persistent state

While a program runs, its variables, lists and objects sit in RAM. Data held only there is transient data: it exists for the lifetime of one run. Persistent data survives after the program ends because it has been copied to non-volatile storage such as an SSD, a hard disk, a database or a cloud service.


Property

Transient data

Persistent data

Where it lives

Memory (RAM)

Disk, database or cloud storage

Lifetime

One run of the program

Until it is deleted or overwritten

Access speed

Very fast

Slower; it must be read back in

Survives a crash or power loss

No

Recoverable if an intact, durably stored snapshot remains

Typical examples

Loop counters, cursor position, running totals

User settings, high scores, saved documents


Not everything should persist. A loop counter, or a value you can compute from saved data, can simply be rebuilt on the next run. Persist the state that cannot be recreated and that the user expects to find again.



The save–load cycle

Saving converts in-memory values into a storable form, a step called serialization, and then writes that form to storage. Loading reverses the process: the program reads the stored form and rebuilds its variables, a step called deserialization. Common storage forms include plain text, CSV, JSON and database tables.


These Python snippets represent two separate runs. The mechanics of opening and writing files are covered with file input and output.


Run 1: save the current game state.


Python
import json

state = {"score": 42, "level": 3}

with open("save.json", "w") as f:
    json.dump(state, f)


Run 2: load the existing save at startup.


Python
import json

with open("save.json") as f:
    state = json.load(f)


Three boxes show run 1 memory, disk storage and run 2 memory, with a save arrow and a load arrow between them.


The loading snippet assumes a valid save exists. The saving snippet illustrates the cycle, but overwriting an existing file can damage the previous save if writing is interrupted. Reliable recovery requires an intact, durably stored snapshot: a saved copy of the state that remains available after the failure. Protect the previous version until its replacement is safely stored.



How much is saved, and how much can be lost

For a file of fixed-size records,


file size=n×(bytes per record)+header bytes\text{file size} = n \times (\text{bytes per record}) + \text{header bytes}


Assuming instantaneous, successful saves and an intact, durably stored latest snapshot, the worst-case loss of play or editing time is


maximum lost play or editing time=save interval\text{maximum lost play or editing time} = \text{save interval}


Example: An address-book app holds 500 contacts at 120 bytes each, plus a 40-byte header. Each save writes 500 × 120 + 40 = 60,040 bytes. With instantaneous, successful autosaves every 10 minutes, a crash just before a save can lose up to 10 minutes of edits. Six full saves per hour write 360,240 bytes.


Real writes take time. Suppose snapshots capture state when each save starts, starts are spaced one interval apart, and writing takes a fixed duration shorter than that interval. If the previous durable snapshot stays protected, a crash just before the next save finishes can lose an interval plus the write duration of ongoing edits. For a 10-minute interval and a 1-minute write, that is up to 11 minutes. Repeated failed saves can extend the loss further.


Saving more often reduces the loss window but writes more data. Recovery restores the state captured in the latest intact, durably stored snapshot; later changes remain at risk.

What to remember

  • Transient data disappears when the run ends; persistent data can be loaded by a later run.
  • Persistence is explicit: serialize, write, then read and deserialize.
  • Save state users expect to keep, and protect an intact, durable snapshot.
  • Save at checkpoints because crashes skip exit code.
  • File size is records times bytes per record plus header. The save-interval loss bound assumes instantaneous, successful saves; snapshot-at-start writes can add their duration when previous versions remain protected.

Example: Autosave in a note-taking app

A note-taking app keeps all of its state in memory while it runs and autosaves every 5 minutes, with the first autosave 5 minutes after launch. Its state includes the text of every note, the user's chosen font size, the on-off phase of the blinking cursor, and a count of how many notes currently fit on screen. Each note is saved as a 180-byte record, and the save file adds a 64-byte header. The user has 250 notes and types continuously at about 40 words per minute. Assume each save completes instantly and 1 kB = 1000 bytes.


a) Which pieces of state must be persisted, and which can stay transient?


For each value, ask two questions: can it be rebuilt on the next run, and does the user expect to find it again?

  • Note text: it cannot be recreated and the user expects it back, so it must be persisted.
  • Font size: a preference the user expects to survive a restart, so it should be persisted.
  • Cursor blink phase: it flips every fraction of a second and means nothing to the next run, so it stays transient.
  • Count of notes on screen: it can be recomputed from the loaded notes and the window size, so it stays transient.

The app should persist the note text and the font size only.


b) The app crashes 23 minutes after launch. How many words of typing are lost?


Autosaves happen at 5, 10, 15 and 20 minutes, so the last completed save before the crash was at ________. Everything typed after that point existed only in memory and disappears with the crash.


The unsaved time is 23 − 20 = ________, so the lost typing is


words lost=3 min×40 wordsmin=120 words\text{words lost} = 3\ \text{min} \times 40\ \frac{\text{words}}{\text{min}} = 120\ \text{words}


The crash loses about 120 words; everything before minute 20 is restored from the save file on the next launch.


c) How many bytes does one save file occupy?


The records take 250 × 180 = ________. Adding the header gives


file size=250×180+64=45 064 bytes≈45.1 kB\text{file size} = 250 \times 180 + 64 = 45\,064\ \text{bytes} \approx 45.1\ \text{kB}


Each save writes 45,064 bytes, about 45.1 kB.


d) How much data does autosave write in one hour, and what changes if the interval is halved to 2.5 minutes?


At one save every 5 minutes there are 60 ÷ 5 = ________ saves per hour, so


12×45 064=540 768 bytes≈0.541 MB per hour12 \times 45\,064 = 540\,768\ \text{bytes} \approx 0.541\ \text{MB per hour}


Halving the interval doubles the number of saves to 60 ÷ 2.5 = ________ per hour, which writes 24 × 45,064 = 1,081,536 bytes, about 1.08 MB per hour. In exchange, the worst-case loss in a crash drops from 5 minutes of typing to 2.5 minutes. The shorter interval protects more work at the cost of twice the write volume.

Match each term about keeping program state between runs with the description that fits it. Each description is used exactly once.

Match each term
A.

Rebuilding in-memory values from stored text or bytes

B.

Working memory such as RAM that loses its contents when power is removed

C.

Values that exist only in memory during a single run of a program

D.

Converting in-memory values into text or bytes that can be stored

E.

Values kept in storage so they are still available after the program ends

F.

A device such as an SSD or hard disk that keeps data without power

Non-volatile storage

Deserialization

Persistent data

Volatile memory

Transient data

Serialization

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A bicycle-rental display tracks counts for a fixed fleet of 72 bicycles. Every bicycle is either rented or available. The program maintains rentedCount and calculates availableCount using:


availableCount=72−rentedCount\text{availableCount}=72-\text{rentedCount}


The fleet size is built into the program and never changes. No rentals or returns occur while the display is shut down. The display needs to restore both counts after restarting.


Complete each blank using either rentedCount or availableCount. For this design, save the value used as the input to the calculation and recalculate its output.


The changing value to save persistently is . After loading that value on restart, the program can recalculate .

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A game keeps a player's progress in memory, saves it, closes, and restores it the next day. Put these steps in the order they occur.

  1. 1.

    The next run reads the stored data back from storage.

  2. 2.

    The program serializes the state into a storable format such as JSON text.

  3. 3.

    The program deserializes the data and rebuilds the in-memory state.

  4. 4.

    The program exits and its memory is released.

  5. 5.

    The program builds and updates the player's state in memory during the first run.

  6. 6.

    The serialized data is written to non-volatile storage.

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Extra Practice