How to Build a Game Save System That Never Loses Progress
A practical game save system design, with versioned JSON, migrations, compressed base64 strings, atomic writes and Steam Cloud, plus a C# example.

How do you build a game save system that survives updates, crashes and cloud sync? In our experience the reliable recipe is short: store your save data as JSON, put a schema version number inside it, upgrade old saves with small migration steps, write every file atomically so a crash can never leave half a save, and let Steam Cloud (or your platform's equivalent) sync the result. We add one more trick borrowed from Factorio's blueprint strings: compress the JSON and encode it as a base64 string with a format prefix. The files get tiny, the version travels with the data, and a save becomes a piece of text you can paste anywhere.
This guide explains each part, the trade-offs, and ends with a complete C# example you can drop into a Unity project.
What a Game Save System Has to Do
A save system looks like a single "write the state to disk" call, and that is why it breaks in production. A good save system does five jobs:
- Capture the right state. Only the data you cannot rebuild: progress, inventory, unlocks, world changes. Not meshes, not textures, not anything the game can recompute on load.
- Load saves from older versions of the game. Your 1.0 players will install 1.4, and their saves must still open.
- Survive a crash or power loss in the middle of a write. The old save must stay intact until the new one is complete.
- Detect corruption and recover, ideally from a backup, instead of crashing on load.
- Sync between machines without the player thinking about it.
Pick a Format: JSON First
You have three realistic choices for the data itself:
- JSON: human-readable, supported everywhere, easy to debug and to migrate, because you can read an old save as a generic tree and fix its shape before you map it to your classes. Larger and slower than binary, which compression mostly fixes.
- A custom binary format: smallest and fastest, but every change to the layout needs careful versioning code, and a bug turns a save into unreadable bytes. Worth it for huge worlds with millions of entities, rarely for anything else.
- Engine-specific serialization (for example Unity's JsonUtility or PlayerPrefs for small settings, Godot resources, Unreal's SaveGame objects): convenient at first, but it ties the save to engine class layouts and makes migrations harder to control.
Our recommendation: start with JSON. It is the format you can open in a text editor when a player sends you a broken save at 2 a.m., and the format an AI agent can read and fix too. Move to binary only when a profiler shows that save size or load time is a real problem.
Two rules make JSON saves much easier to live with:
- Keep a plain data class (a DTO) for the save, separate from your game objects. The game copies its state into the DTO on save and reads it back on load. Never serialize live MonoBehaviours, actors or nodes directly.
- Store stable IDs, not references. An item is "sword-iron", a level is "forest-02", not a pointer or a scene index that changes when you reorder a list.
Version Every Save and Write Migrations
The single most valuable field in a save file is a version number. Without it, the first time you rename a field, every old save either fails to load or silently loses data.
The pattern we use:
- Every save has an integer version field at the top level.
- The game has one constant, the current version. Bump it every time the save's shape changes.
- On load, read the JSON into a generic tree first (not straight into your classes).
- Run migration steps in order: from 1 to 2, from 2 to 3, and so on, until the tree is at the current version. Each step is a few lines that rename a field, split one value into two, or add a default.
- Only then map the tree to your save class.
Some practical rules:
- Never edit an old migration step after release. Add a new one.
- Never reuse a field name with a different meaning. Rename it and migrate.
- Refuse to load a save with a version newer than the game knows, with a clear message ("This save was made with a newer version of the game"), instead of loading it and dropping fields you do not understand.
- Keep a folder of real saves from every released version and load them all in an automated test. It is the cheapest insurance you will ever buy.
The Factorio Trick: Compressed JSON as a Base64 String
Factorio is famous for its blueprint strings: a whole factory layout that players paste into forums and chat as one line of text. Its format is documented on the official Factorio wiki: the blueprint is a JSON object, compressed with zlib deflate at compression level 9, encoded as base64, with a single version byte in front of the string. The version byte is 0 for every Factorio version through 2.0. To decode it, you skip the first character, decode the base64 and inflate the result back to JSON.
To be accurate: that is how Factorio stores blueprints, not its save games. Factorio's saves are zip archives (the official wiki lists "save games (as zip files)" in the game folder) with a binary game state inside. What we recommend here is the blueprint-string approach applied to save files, because it combines the strengths of JSON with most of the size benefit of a binary format:
- Tiny files. JSON is very repetitive (the same field names over and over), so deflate typically shrinks it to a fraction of its size.
- The version is built in, twice: the prefix character tells you how the string itself is encoded, and the version field inside the JSON tells you the shape of the data. You can change compression later by changing the prefix, without touching the data.
- It is plain text. A save string fits in any place that only accepts text: a web storage key, a cloud key-value store, a support ticket, a "share your build" feature or a clipboard.
The honest trade-offs:
- Base64 makes the compressed bytes about a third larger. If the save only ever lives in a file, writing the compressed bytes directly is smaller. We keep the string because the portability is worth more than those bytes.
- You lose "open the file and read it". Add a debug menu item or a small command-line tool that decodes a save back to pretty JSON, and you get the readability back when you need it.
- Compression costs CPU time. For saves of a few megabytes it is negligible; for very large worlds, compress on a background thread.
Atomic Writes: Never Leave Half a Save
The classic save bug: the game opens the save file, truncates it, starts writing, and the player's laptop runs out of battery. The old save is gone and the new one is half written. The fix is an atomic write, and it costs about five lines:
- Write the new save to a temporary file next to the real one (save.dat.tmp).
- Flush it all the way to disk.
- Replace the real file with the temporary one in a single operation. Keep the previous version as a backup (save.dat.bak).
- On load, if the main file is missing or fails to decode, try the backup.
Because the replace happens only after the new file is complete, the player always has either the old save or the new one, never a broken mix.
A few more habits that prevent most save disasters:
- Save from one place in the code, through one function. Multiple systems writing the same file at the same time is a common source of corruption.
- Do not save during scene loading or on application quit if you can avoid it. Quitting can be cut short, especially on mobile. Save at checkpoints and when the game is paused or sent to the background.
- Use the platform's user data folder (Application.persistentDataPath in Unity, user:// in Godot, the Saved folder in Unreal), never the install folder, which may be read-only.
A Complete Save System Example in C#
Here is the whole pipeline for Unity: versioned JSON, migrations, compression, a base64 string with a format prefix, and an atomic write with a backup. It uses Newtonsoft Json.NET (Unity's com.unity.nuget.newtonsoft-json package) because its JObject tree makes migrations easy, and GZipStream, which uses the same deflate algorithm as zlib and is available in Unity's .NET profile.
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
public class SaveData
{
public int version;
public string playerName;
public int level;
public float[] position = new float[3];
public List<string> inventory = new List<string>();
}
public static class SaveSystem
{
// Shape of the data inside the JSON. Bump it and add a migration step on every change.
public const int CurrentVersion = 3;
// Format of the string itself (like Factorio's version byte): "1" = gzip + base64.
const char FormatPrefix = '1';
public static string Encode(SaveData data)
{
data.version = CurrentVersion;
byte[] json = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(data));
using var packed = new MemoryStream();
using (var gzip = new GZipStream(packed, CompressionLevel.Optimal))
gzip.Write(json, 0, json.Length);
return FormatPrefix + Convert.ToBase64String(packed.ToArray());
}
public static SaveData Decode(string text)
{
if (string.IsNullOrEmpty(text) || text[0] != FormatPrefix)
throw new InvalidDataException("Unknown save format");
byte[] packed = Convert.FromBase64String(text.Substring(1));
using var gzip = new GZipStream(new MemoryStream(packed), CompressionMode.Decompress);
using var reader = new StreamReader(gzip, Encoding.UTF8);
JObject root = JObject.Parse(reader.ReadToEnd());
Migrate(root);
return root.ToObject<SaveData>();
}
static void Migrate(JObject root)
{
int version = (int?)root["version"] ?? 1;
if (version > CurrentVersion)
throw new NotSupportedException($"Save version {version} is newer than this game");
if (version < 2) // v2 renamed "name" to "playerName"
{
root["playerName"] = root["name"];
root.Remove("name");
}
if (version < 3) // v3 added the inventory
{
if (root["inventory"] == null)
root["inventory"] = new JArray();
}
root["version"] = CurrentVersion;
}
public static void Save(string path, SaveData data)
{
string tmp = path + ".tmp";
using (var file = new FileStream(tmp, FileMode.Create, FileAccess.Write, FileShare.None))
using (var writer = new StreamWriter(file, new UTF8Encoding(false)))
{
writer.Write(Encode(data));
writer.Flush();
file.Flush(true); // force the bytes to disk before the swap
}
if (File.Exists(path))
File.Replace(tmp, path, path + ".bak"); // swap in one step, keep a backup
else
File.Move(tmp, path);
}
public static SaveData Load(string path)
{
foreach (string candidate in new[] { path, path + ".bak" })
{
if (!File.Exists(candidate))
continue;
try
{
return Decode(File.ReadAllText(candidate));
}
catch (Exception e) when (!(e is NotSupportedException))
{
UnityEngine.Debug.LogWarning($"Save {candidate} is unreadable: {e.Message}");
}
}
return null; // no usable save: start a new game
}
}Call it with a path in the user data folder, for example Path.Combine(Application.persistentDataPath, "slot1.sav"). A few notes on the choices:
- A save from a newer game version is not treated as corrupt: Load lets that exception through, so you can show the player a message instead of quietly falling back to an older backup.
- The prefix and the version field are separate on purpose. If you later switch to Brotli or add encryption, you add prefix "2" and keep every data migration as it is.
- The same Encode and Decode pair works for a "copy save to clipboard" button or for sending a save to your support inbox.
- On platforms with their own storage APIs (consoles, the web), keep Encode and Decode and replace only Save and Load.
Steam Cloud and Other Cloud Saves
Once the files are safe on disk, cloud sync is mostly configuration. As of November 2026, Steamworks (partner.steamgames.com/doc/features/cloud) offers two ways to do it:
- Steam Auto-Cloud: no code. In the Steamworks settings you list the folders and file patterns to sync. Steam downloads them before the game launches and uploads them after it exits.
- The Cloud API (ISteamRemoteStorage): code you write, with more control over which files sync and when.
For most indie games Auto-Cloud is enough. The setup steps we follow:
- In the Steam Cloud settings, set the byte quota per user and the number of files allowed per user. Both must be non-zero, and the settings must be published.
- Add a root path for your save folder, for example WinAppDataLocalLow for a Unity game on Windows, plus the matching macOS and Linux roots if you ship there.
- Put the player's Steam ID in the subfolder ({64BitSteamID} or {Steam3AccountID}), so two Steam accounts on one PC never share saves.
- Test with the developers-only option before turning the feature on for everyone.
Valve's guidance matches what the save design above gives you: smaller files work better, splitting state into files by how often it changes avoids re-uploading unchanged data, and machine-specific settings such as video settings should not be synced at all. Keep graphics options in a separate, local-only file. Compressed save strings help here directly: a smaller save is a faster sync at exit and a faster game launch on the next machine.
Remember that whatever you claim on your store page must be in the build: if the page says Steam Cloud, test it on two machines before release. Our Steam release checklist covers the rest: ai-game.dev/blog/how-to-release-a-game-on-steam.
Save System Checklist
- JSON data class separate from game objects, with stable string IDs.
- An integer version field in every save, and one current-version constant in code.
- Ordered migration steps, never edited after release, and a refusal for newer versions.
- Compressed JSON as a base64 string with a format prefix.
- Atomic write: temporary file, flush, replace, keep a backup.
- Load falls back to the backup and never crashes the game.
- Saves live in the user data folder, synced by Steam Auto-Cloud, with local-only graphics settings.
- An automated test that loads real saves from every released version.
Building It with an AI Agent
A save system is a good job for an AI agent, because it is well specified and easy to test. Give the agent this checklist as the plan and ask it to write the save class, the migrations and a test that round-trips old saves. With AI Game Developer connected to your editor, the agent does not only write the files: it runs short C# snippets inside the live Unity editor, so it can save the current game state, decode the string back to JSON and show you exactly what was stored, or load an old save and check that the migration produced the right values. It works the same way with Unreal (Python) and Godot. If you are new to this workflow, start with ai-game.dev/blog/claude-code-unity-tutorial, and commit your save tests along with the code (our version control guide: ai-game.dev/blog/version-control-game-development).
You can download the app at ai-game.dev/download and read about the Unity integration at ai-game.dev/engines/unity.

