Game Save Systems & Serialization

Game Save Systems & Serialization

A save system turns selected runtime game state into durable data and restores it later. Serialization is the conversion between in-memory values and a stored representation; persistence is making that representation survive process exit, crashes, and updates.

A save file is not a memory dump. It is a deliberate data contract between game versions.

1. What Belongs in a Save?

Start by deciding what the player expects to persist:

Do not blindly serialize every runtime object. Usually exclude transient or derived state such as frame timers, cached pointers, render handles, temporary effects, physics solver internals, and values that can be recomputed.

For ECS games, serialize selected component values through an explicit save representation. Do not write raw archetype chunks, sparse-set arrays, entity indices, or allocator memory directly to disk.

2. Save and Load Pipeline

A reliable pipeline separates live game state from the file format:

flowchart TD
    A[Live world and gameplay state] --> B[Select persistent state]
    B --> C[Build save snapshot]
    C --> D[Validate and serialize]
    D --> E[Write temporary file]
    E --> F[Flush and close]
    F --> G[Replace previous save]
    G --> H[Durable save]

Loading reverses the process, but should not mutate the live world until the file has been read and validated:

flowchart TD
    A[Choose save slot] --> B[Read file]
    B --> C[Check header and format version]
    C --> D{Valid and supported?}
    D -->|No| E[Report error or recover backup]
    D -->|Yes| F[Deserialize data]
    F --> G[Run migrations]
    G --> H[Validate references and values]
    H --> I[Build staged world state]
    I --> J[Apply state at safe load boundary]

Staging matters: a truncated or incompatible file should not leave half the world restored.

3. Design a Stable Save Format

Use a format that is easy to inspect and version. JSON is convenient for debugging and tools; a compact binary format can reduce size and parse cost. The choice is secondary to having an explicit, documented schema.

Example shape:

{
  "format_version": 3,
  "slot_id": "slot_01",
  "saved_at": "2026-10-30T18:30:00Z",
  "player": {
    "health": 85,
    "inventory": [{"item_id": "iron_sword", "count": 1}]
  },
  "world": {
    "level_id": "forest_ruins",
    "opened_doors": ["north_gate"],
    "defeated_bosses": ["root_guardian"]
  }
}

The example is illustrative; use the identifiers and timestamp conventions your project defines.

Good format rules:

4. ECS Serialization: Save Meaning, Not Memory Layout

An entity handle used inside one running process is often an index plus a generation counter. That handle may be recycled after destruction and is not automatically a permanent identity across sessions.

For persistent objects, assign a stable save ID (or another deliberate persistent identity). At save time, map runtime entities to save records. At load time, create entities and rebuild the mapping before resolving cross-entity references.

flowchart LR
    A[Runtime entity handle] --> B[Persistent ID lookup]
    B --> C[Save record with component values]
    D[Load record] --> E[Create runtime entity]
    E --> F[Build Persistent ID to runtime handle map]
    F --> G[Resolve entity references]

Example record concept:

SavedEntity:
  persistent_id
  components:
    Transform: position, rotation
    Health: current, maximum
    Inventory: item IDs and counts

Do not persist component storage indices or archetype/chunk positions. Storage layout is an implementation detail and may change when components are added, removed, or reordered. Save only the components that define persistent gameplay state; reconstruct transient components and runtime services during load.

5. Versioning and Migrations

Save formats evolve. A later game version may rename fields, split a component, change units, or replace an item ID. Put a format version in every save and migrate older data through explicit steps.

flowchart TD
    A[Read saved version] --> B{Current version?}
    B -->|Yes| E[Validate current schema]
    B -->|Older| C[Migration for N to N+1]
    C --> D{More versions to migrate?}
    D -->|Yes| C
    D -->|No| E
    E --> F[Load game state]

Keep migrations sequential and test them against real fixtures from previous releases. For example, a migration might rename old_weapon_name to weapon_id, supply a default difficulty field, or convert a stored value from one unit to another.

Do not silently reinterpret unknown data. Decide whether an unsupported future version should be rejected, opened read-only, or handled by a documented compatibility policy.

6. File Safety and Reliability

A save can be interrupted by a crash, power loss, full disk, or process termination. Avoid overwriting the only good copy in place.

A practical local-file strategy:

  1. Serialize to a temporary file in the same directory as the target.
  2. Check every write result and flush/close successfully.
  3. Replace the previous save with the completed temporary file using the platform's safe replacement operation.
  4. Keep a rotating backup or previous generation if the game needs recovery.
  5. On startup, validate the newest save and fall back to a known-good backup when appropriate.

Atomic replacement behavior and durability guarantees vary by operating system and filesystem. For important saves, understand the platform APIs you target rather than assuming a rename alone guarantees power-loss safety.

Also consider:

7. Snapshot vs Event Log

Most games should begin with a straightforward snapshot: a complete representation of the persistent state at a point in time.

An event log stores changes such as DoorOpened(north_gate) or ItemCollected(iron_sword). It can support replays, history, or specialized simulation workflows, but requires event ordering, replay rules, log compaction, and compatibility across event versions.

Approach Strength Cost
Snapshot Simple load path; easy to inspect and validate Rewrites the selected persistent state
Event log Captures history and incremental changes Replay, ordering, compaction, and migration are harder
Snapshot + event tail Faster recovery with recent history More moving parts; add only when justified

For a typical single-player game, a versioned snapshot plus backups is a strong starting point.

8. Testing Save Systems

Treat saves as a compatibility surface, not just a button that appears to work.