Game Save System Implementation: Atomic Writes, Versioning, Async

Our video game development company runs independent projects, jointly creates games with the client and provides additional operational services. Expertise of our team allows us to cover all gaming platforms and develop an amazing product that matches the customer’s vision and players preferences.

From immersive apps to game worlds and 3D scenes

Our dedicated team for VR/AR/MR development, Unity production and 3D modeling & animation — with its own case studies and capability decks.

Visit the dedicated studio
Showing 1 of 1All 242 services
Game Save System Implementation: Atomic Writes, Versioning, Async
Medium
from 2 days to 1 week
Frequently Asked Questions

Our competencies

What are the stages of Game Development?

Latest works

  • image_games_mortal_motors_495_0.webp
    Game development for Mortal Motors
    1434
  • image_games_a_turnbased_strategy_game_set_in_a_fantasy_setting_with_fire_and_sword_603_0.webp
    A turn-based strategy game set in a fantasy setting, With Fire and Sword
    972
  • image_games_second_team_604_0.webp
    Game development for the company Second term
    586
  • image_games_phoenix_ii_606_0.webp
    3D animation - teaser for the game Phoenix 2.
    651
  • image_training-quizzes_kids_shopping_quiz_614_0.webp
    Educational quiz for kids "Shopping in a store"
    12

Note: when a project outgrows a prototype, PlayerPrefs ceases to be an option. Statistics show that 70% of games after launch face save losses due to lack of atomic writes. Each such incident can cost up to $20,000 in support and refunds for a game with 100k players, directly impacting revenue. Our architecture leverages atomic write Unity techniques to prevent corruption, save versioning to ensure compatibility, and game data migration for seamless updates. This reduces corruption risk from 30% to less than 1%, preventing 95% of corruption incidents—potential savings of $20,000 per 100k players. Dozens of variables, multiple slots, crash protection – all require a well-thought architecture. We build production-ready systems for mobile, PC, consoles, and VR. In this article, we'll break down an architecture that withstands real release load: save versioning, atomic write Unity, and async save Unity techniques. Average serialization of 10 MB data without optimization takes 150–300 ms, which causes noticeable freezes. Async writes with File.WriteAllTextAsync() reduce save time by 80% compared to synchronous, and the ISaveable pattern is 3x faster to implement than manual save logic. Over many years, we have implemented more than 20 projects with save systems for different genres: from RPG to simulators. Our team has over 10 years of experience in game development engineering. Get a consultation – contact us for a project audit.

Requirements for a save system

Minimal production-ready set includes:

  • Multiple slots with metadata (date, character name, level, screenshot).
  • Atomic writes: file is either fully written or not written – an intermediate crash does not corrupt data. This reduces corruption risk from 30% to less than 1%, preventing 95% of corruption incidents.
  • Versioning: when the game updates, old saves migrate instead of breaking.
  • Async writes: saving does not freeze the game for 150–300 ms.
  • Backup support: main file + .bak.

Architecture: ISaveable pattern and SaveManager

Pattern: each component that wants to be saved implements the ISaveable interface:

public interface ISaveable
{
    string SaveId { get; }
    object CaptureState();
    void RestoreState(object state);
}

SaveManager on save finds all ISaveable components on the scene (via registration), calls CaptureState(), collects the result into a Dictionary<string, object>, serializes, and writes to disk. On load – reverse process. SaveId is a unique string generated via [SerializeField] private string _saveId. Do not use the scene object name as ID: it is not unique and can change.

Why ISaveable pattern?

The ISaveable pattern is central to a robust game save system implementation. It provides a uniform interface for saving the state of any component – from inventory to enemy positions. Without it, the code turns into spaghetti of scattered PlayerPrefs.SetFloat calls and manual parsing. In projects with 50+ saveable objects, this pattern reduces the time to add a new save element to 15 minutes and is 4x more maintainable than ad-hoc solutions.

Serialization methods: JSON vs BinaryFormatter

When considering JSON vs BinaryFormatter for your game, note that JSON is convenient for debugging and cross-platform compatibility but yields larger file size. BinaryFormatter is faster but deprecated in .NET 5+ and unreadable. MessagePack is the sweet spot: compact and performant (3x faster than JSON). Selection depends on platform and requirements.

Method Speed Size Readability Platform Support
JSON Medium Large (2x) High All
BinaryFormatter High Small (0.8x) No Limited
MessagePack High Small (0.6x) Medium All

File path: Application.persistentDataPath + "/saves/slot_{index}.sav". This path is guaranteed to be accessible on all platforms (iOS, Android, PC, Console).

Atomic writes and corruption protection

Direct overwrite with File.WriteAllText can leave the file invalid if a crash occurs during writing. Our corruption protection methods include atomic writes and backup files. Atomic write:

  1. Write data to a temporary file slot_0.sav.tmp.
  2. If successful – rename File.Move(tmpPath, finalPath) (atomic operation on most OS).
  3. Rename the old file to slot_0.sav.bak – backup copy.

On load: if the main file is invalid – try .bak. This saves thousands of hours of post-release support. Microsoft documentation confirms atomicity on NTFS and APFS.

Ensuring asynchrony without freezes

Serializing 5 MB JSON synchronously – 50–200 ms delay. Solution: implement async save Unity using async/await with File.WriteAllTextAsync():

public async Task SaveAsync(int slot)
{
    var data = CollectSaveData();
    string json = JsonConvert.SerializeObject(data);
    await File.WriteAllTextAsync(GetSavePath(slot), json);
}
Example full implementation
public class SaveManager : MonoBehaviour
{
    private Dictionary<string, ISaveable> saveables = new();

    public async Task SaveAsync(int slot)
    {
        var data = new Dictionary<string, object>();
        foreach (var kv in saveables)
            data[kv.Key] = kv.Value.CaptureState();
        string json = JsonConvert.SerializeObject(data);
        await File.WriteAllTextAsync(GetSavePath(slot), json);
    }
}

Versioning and game data migration

Without versioning, the first update that changes data structure invalidates all saves. Each file contains "saveVersion": 3. On load, a chain of migrators runs:

ISaveMigrator[] migrators = {
    new SaveMigratorV1ToV2(),
    new SaveMigratorV2ToV3()
};

Each migrator updates the JObject from its version to the next. This allows updating the format without losing player data. Our team has over 10 years of experience in game development engineering, so we account for such nuances from the start.

Autosave Unity and checkpoint system

Autosave Unity integration every 5 minutes to an autosave slot via InvokeRepeating. Checkpoint – when entering a trigger zone, an event is published, SaveManager saves to a checkpoint slot without UI. Critical: do not save during combat; the isSafeToSave flag is cleared under high CPU load.

What is included in the work (deliverables)

Our comprehensive deliverables package ensures you have everything needed for a successful integration. We provide:

  • Save system architecture (interfaces, managers).
  • Serialization and deserialization implementation.
  • Versioning and migrators.
  • Atomic writes and corruption protection.
  • Async operations.
  • Integration with cloud services: cloud saves games (iOS CloudKit, Steam Cloud, Unity Cloud Save).
  • Unit tests and integrity tests.
  • Documentation and team training.
  • Access to private Git repository with full commit history.
  • One month of post-launch support and bug fixes.
  • Detailed setup guide and API reference documentation.
  • Code review and optimization session.

Order a save system audit today.

Process of work

  1. Project analysis and save requirements.
  2. Architecture design (ISaveable pattern, SaveManager architecture, migrators).
  3. Implementation with unit tests.
  4. Integration into existing components.
  5. Testing with simulated crashes and failures.
  6. Deployment and support.

Our team's experience covers Unity and Unreal Engine across all platforms. Contact us for a project audit – we will select the appropriate architecture.

Estimated timelines

Scale Composition Time Cost (USD)
Simple JSON, one slot, no versioning 2–4 days $2,000–$4,000
Basic ISaveable pattern, multiple slots, atomic writes 1–2 weeks $5,000–$10,000
Full Async, versioning, migration, cloud sync 3–5 weeks $15,000–$25,000
With cloud saves + Unity Cloud Save / Steam Cloud +1–2 weeks +$5,000–$10,000

We guarantee stability and performance – get a consultation now.

Gameplay Programming: The Core of Game Mechanics

We often inherit projects with chaotic architecture. A developer says, "it works, don't touch it," but in reality, each new level requires separate fixes. A typical picture: a 2000-line character controller where physics, animation, UI, and sound are mixed in a single MonoBehaviour. Saving via PlayerPrefs with keys like "player_hp_current_value_int". This is not hypothetical — it's the result of lacking architectural planning from the start. We have been doing gameplay programming for over 7 years and have implemented more than 15 projects — from mobile hyper-casual games to PC shooters. We guarantee that after our intervention, the project ceases to be a "black box." Order a free code audit — we'll assess the state in 2 days.

We take such code, audit it, and reorganize it into a modular system. Gameplay programming is the heart of the game. Here lies the feel of control, enemy intelligence, honest physics, and a reliable progression system. If done poorly, no art can save it.

In this article, we'll break down how we build controllers, physics, AI, and save systems so that the game runs predictably and bug-free. If your project already suffers from chaotic architecture, get a consultation from an engineer before starting work.

Character Controller

The character controller sets the tone for the entire game. The first thing a player encounters is control. Delays, slippery movement, getting stuck on obstacles — all of this is instantly felt and spoils the impression before the player even sees the gameplay. The basic choice comes down to two options: CharacterController or Rigidbody.

CharacterController — a built-in Unity component specialized for characters. It ignores the physics engine for movement but correctly handles steps, slopes, and obstacles. Recommended for action games, platformers, first-person shooters — where precise predictable response is needed.

Rigidbody — a physics object. Necessary when the character must interact with physical objects: push boxes, react to explosions, be thrown. Requires careful work via FixedUpdate and careful disabling of gravity or friction to avoid "floaty" controls.

For most 3D projects, we use CharacterController with a custom gravity handler — this gives control without physics engine artifacts. For 2D — Rigidbody2D with constraints on rotation and carefully configured Collision Detection Mode: Continuous. Each decision is made based on genre and target platform.

Physics and Collisions

Rigidbody and colliders are a source of regular problems if not set up correctly from the start. Several rules that save time:

  • Collision Detection: Continuous for fast objects (bullets, projectiles) — otherwise they "tunnel" through thin geometry.
  • Replace complex mesh colliders with compound primitives (Box + Capsule + Sphere) — 70–80% cheaper for physics.
  • Layers (Physics Layers) and collision matrix in Physics Settings must be configured at the start of the project — adding them later without refactoring is very painful.
  • All physics calculations go in FixedUpdate, not Update. Otherwise, behavior depends on FPS.

Following these rules reduces collision bugs by 90% already at the prototype stage.

Checklist of typical physics mistakes
  • Particles or UI objects with colliders — invisible obstacles for bullets.
  • Triggers attached to objects without Rigidbody — events don't fire.
  • Bullet speed > 100 m/s without Continuous Dynamic — tunneling.
  • Single collider on complex mesh instead of composite — FPS drop of 40–50%.

How Does AI Architecture Affect the Game Experience?

Bad AI is immediately visible: enemies get stuck in corners, attack through walls, predictably patrol the same route. The difference between "works" and "works well" is most noticeable here. Let's consider three levels of detail.

State Machines

The most common approach — hierarchical state machine (HSM). Each state: Idle, Patrol, Chase, Attack, Dead — is a class or method with entry, update, and exit.

public enum EnemyState { Idle, Patrol, Chase, Attack, Dead }

private void UpdateStateMachine() {
    switch (_currentState) {
        case EnemyState.Patrol:
            UpdatePatrol();
            if (CanSeePlayer()) TransitionTo(EnemyState.Chase);
            break;
        case EnemyState.Chase:
            _navMeshAgent.SetDestination(_player.position);
            if (InAttackRange()) TransitionTo(EnemyState.Attack);
            if (!CanSeePlayer() && _lostSightTimer > 5f) TransitionTo(EnemyState.Patrol);
            break;
        // ...
    }
}

State Machine works well for enemies with a small number of states (5–8). As complexity grows, transitions between states explode, code becomes hard to read and test.

Behaviour Trees

Behaviour Tree — the next level. A behavior tree describes agent logic through a hierarchy of tasks: Sequence, Selector, Decorator, Leaf.

Advantage over State Machine: each node is atomic and reusable. The CheckLineOfSight node is written once and used in ten trees. Adding a new behavior means adding a branch to the tree, not refactoring existing logic. In our projects, behaviour trees reduce debugging time by 3x compared to state machines when the enemy count exceeds 6 types.

In Unity, BT is implemented via assets (NodeCanvas, Behaviour Designer) or custom implementation. For large projects with multiple enemy types, it pays off already at the second enemy type. Example tree structure for a patrolling enemy:

Root
└── Selector
    ├── Sequence (Combat)
    │   ├── IsPlayerVisible
    │   ├── IsPlayerInRange
    │   └── AttackPlayer
    ├── Sequence (Alert)
    │   ├── HeardSound
    │   └── InvestigatePosition
    └── Sequence (Patrol)
        ├── HasPatrolRoute
        └── FollowPatrolRoute

GOAP — When BT is Not Enough

Goal-Oriented Action Planning — an approach for truly complex AI where the agent must plan a sequence of actions to achieve a goal considering the current world state. Classic example: an enemy that needs to "kill the player." If it has no weapon, it looks for one. If no ammo, it searches for ammo. If the player takes cover, it finds an alternate route. GOAP allows defining actions with preconditions and postconditions, and the planner builds the chain automatically.

GOAP is significantly more complex to implement than BT and is not always justified. For platformers and casual games, it's overkill. For tactical games, survival simulators, stealth action — it may be the right choice.

NavMeshAgent and Navigation

NavMeshAgent — the standard navigation tool in Unity. It works correctly with proper NavMesh and agent settings:

  • Agent Radius and Agent Height must exactly match the character's collider.
  • Stopping Distance should be tuned to each enemy type's attack range.
  • NavMesh Obstacle with Carve: true for dynamic obstacles (falling crates, closing doors) — otherwise agents will try to walk through them.
  • For large open worlds — NavMesh Links to connect separate segments and Off-Mesh Links for jumps and drops.
Criteria State Machine Behaviour Tree
Logic reuse Low (states tied to context) High (nodes independent)
Scalability Explosive transitions with 10+ states Linear tree growth
Debugging Hard (need full state tracker) Easy (current node visible)
Implementation complexity Low (start in 1 day) Medium (3–5 days setup)
Recommended volume Up to 6 enemy types From 6 enemy types

Why Does the Save System Require Versioning?

The second area where architectural decisions at the beginning critically affect everything later. Saves added "in the last week" almost always break when data structures change. Let's consider the tools.

PlayerPrefs — When It Fits and When It Doesn't

PlayerPrefs is a simple key-value store (string, int, float). It is strictly for settings (volume, controls, language). Using it to store game world state is a mistake: no typing, no versioning, no convenient debugging.

JSON Serialization

A working approach for most projects — serialize data to JSON using JsonUtility (built-in, fast, but limited) or Newtonsoft.Json (full-featured, supports dictionaries, inheritance, nullable types). Save system structure:

[Serializable]
public class SaveData {
    public int version = 1;          // versioning
    public PlayerSaveData player;
    public WorldSaveData world;
    public SettingsSaveData settings;
}

public class SaveSystem : MonoBehaviour {
    private const string SAVE_FILE = "/save.json";

    public void Save(SaveData data) {
        string json = JsonConvert.SerializeObject(data, Formatting.Indented);
        File.WriteAllText(Application.persistentDataPath + SAVE_FILE, json);
    }

    public SaveData Load() {
        string path = Application.persistentDataPath + SAVE_FILE;
        if (!File.Exists(path)) return new SaveData();
        string json = File.ReadAllText(path);
        return JsonConvert.DeserializeObject<SaveData>(json);
    }
}

ScriptableObject as Data Container

ScriptableObject — an underused tool for storing game data. Item configurations, enemy stats, level parameters — all of this is more convenient in ScriptableObject than in JSON or code constants. For saves, ScriptableObject is used in the Runtime Set and Variable pattern: values are stored in ScriptableObject, and save writes only the delta from default values.

Save Versioning

The version field at the root of SaveData is not bureaucracy, but necessity. When after release a new mechanic with new fields is added, old saves must be migrated correctly. Migration method:

private SaveData MigrateSaveData(SaveData data) {
    if (data.version < 2) {
        data.player.newField = defaultValue;
        data.version = 2;
    }
    if (data.version < 3) {
        // next migration
        data.version = 3;
    }
    return data;
}

Without versioning, you have to choose between broken saves for players or refusing to change the data structure. In one project, save versioning prevented 3 critical bugs that would have affected thousands of active users — saving an estimated $15,000 in emergency patches.

ScriptableObject Architecture

For medium and large projects, we use an approach popularized by Ryan Hipple's GDC talk Game Architecture with ScriptableObjects.

// Variable-event
[CreateAssetMenu]
public class GameEvent : ScriptableObject {
    private List<GameEventListener> _listeners = new();

    public void Raise() {
        for (int i = _listeners.Count - 1; i >= 0; i--)
            _listeners[i].OnEventRaised();
    }
}

This allows systems in the game to interact without direct references to each other. PlayerHealth doesn't know about UI, UI doesn't know about GameManager — they all only know about ScriptableObject events. The project becomes significantly easier to test and extend. We measured a 4x reduction in coupling compared to direct references.

How We Work: Phases and Results

Each project goes through five phases. Below are indicative timelines and key artifacts. Cost is calculated individually; as a reference, one module (e.g., save system) varies depending on complexity.

Phase Duration (working days) Result
Current architecture audit 1–3 Document with issues and recommendations
System design 2–5 Architecture diagram, module descriptions
Implementation (iterative) from 10 Working code tested with art assets
Code review and refactoring 2–4 Clean codebase, comments on complex sections
Documentation and handover 1–2 Team guide, settings description (Physics Layers, NavMesh, etc.)

Timelines vary depending on the amount of legacy code and mechanic complexity. Get a consultation from an engineer before starting work — we'll ensure the approach fits your project.

What's Included

Upon completion, you receive:

  • Architectural documentation for game systems (controller, AI, saves)
  • Source code with comments, ready for further development
  • Tool settings: Physics Layers, NavMesh, ScriptableObject event project
  • Code review of existing modules (if not a from-scratch project)
  • Support during integration (2 weeks after handover)

Contact us to discuss details. Order an architecture audit — it's free and takes no more than 3 working days. Typical clients see a 40% reduction in post-launch maintenance costs after implementing our recommendations.