TExcelTAD
Home › Multiplayer Game Networking › Persistence & Player Data

Persistence & Player Data

A match lasts minutes; a player's account lasts years. Whatever must survive the match (level, inventory, currency, unlocked skins, rank, match history) goes into a persistent store owned by your backend. Getting it wrong has painful results: lost progress, duplicated items that wreck the economy, double rewards after a server crash.

What to persist, and who writes it

Data Changes Written by
Profile, settings, cosmetics rarely backend API (player request, validated)
Inventory, currency often, valuable backend only, in transactions
Progression (XP, levels, unlocks) after matches backend, from the server's match result
Rank / MMR after ranked matches matchmaking service
Match history, stats after matches backend, append-only
Live match state (positions, health) every tick not persisted; it lives in the game server's memory

The game client never writes persistent data directly; it asks the backend, which validates (Never Trust the Client). The dedicated game server reports results ("player u_7f3a won, 12 kills, earned 340 XP") once, at the end of the match or at checkpoints, through an authenticated server-to-server API. Writing to the database every tick would cost far more than it saves.

Save at checkpoints, not every tick

  • Session games (shooters, MOBAs): write once at match end, plus important mid-match events (a purchase, a rare drop).
  • Persistent worlds (survival, MMO): keep state in memory, mark changed objects dirty, and flush them periodically (every 30–60 s) and on important events. This is write-behind caching. A crash loses at most one interval, so anything valuable (trades, purchases) is written immediately instead.
  • Cache vs database: a fast in-memory store such as Redis holds hot, rebuildable data (online presence, lobby membership, leaderboards via sorted sets, session tickets). The durable source of truth (a relational database such as PostgreSQL, or a document store) holds anything you can't afford to lose. If the cache is wiped, the game should recover from the database.

Optimistic concurrency: version numbers

Two writers can update the same record: the game server finishing a match and the player buying something in the store at the same moment. If both read "gold: 500", add or subtract, and write back, one update is lost. Optimistic concurrency fixes this: every record carries a version; a write says "only if the version is still N" and fails if someone else wrote first. The loser re-reads and retries.

ts · try it yourself
type Profile = { gold: number; xp: number; version: number };

class Store {
  private rows = new Map<string, Profile>();
  constructor() { this.rows.set('u_7f3a', { gold: 500, xp: 1200, version: 7 }); }
  read(id: string): Profile { return { ...this.rows.get(id)! }; }
  // UPDATE profiles SET ... , version = version + 1 WHERE id = $1 AND version = $2
  write(id: string, next: Profile, expectedVersion: number): boolean {
    const cur = this.rows.get(id)!;
    if (cur.version !== expectedVersion) return false;
    this.rows.set(id, { ...next, version: expectedVersion + 1 });
    return true;
  }
}

const db = new Store();
const matchServer = db.read('u_7f3a');   // both read version 7
const shop = db.read('u_7f3a');

shop.gold -= 300;                          // buys a skin
console.log('shop write   ', db.write('u_7f3a', shop, shop.version) ? 'ok' : 'CONFLICT', db.read('u_7f3a'));

matchServer.gold += 120; matchServer.xp += 340;          // match reward computed from the stale copy
console.log('match write  ', db.write('u_7f3a', matchServer, matchServer.version) ? 'ok' : 'CONFLICT', db.read('u_7f3a'));

// The loser re-reads and applies its change again.
const fresh = db.read('u_7f3a');
fresh.gold += 120; fresh.xp += 340;
console.log('match retry  ', db.write('u_7f3a', fresh, fresh.version) ? 'ok' : 'CONFLICT', db.read('u_7f3a'));
shop write    ok { gold: 200, xp: 1200, version: 8 }
match write   CONFLICT { gold: 200, xp: 1200, version: 8 }
match retry   ok { gold: 320, xp: 1540, version: 9 }

Without the version check, the match write would have set gold back to 620 and the skin would have been free. (In SQL you can also write SET gold = gold + 120, which is atomic for a single row; versions matter when the new value is computed in application code or spans several fields.)

Idempotent match results

Networks fail after the work is done: the game server sends "grant 340 XP", the database commits, but the reply is lost, so the server retries. Without protection the player gets 680 XP. The fix is an idempotency key: each result carries a unique id (here the match id plus the player), and the backend records which keys it has applied in the same transaction as the grant.

ts · try it yourself
const applied = new Set<string>();
const xp = new Map<string, number>([['u_7f3a', 1540], ['u_91bc', 800]]);

function grantXp(matchId: string, player: string, amount: number): string {
  const key = `${matchId}:${player}`;
  // BEGIN; INSERT INTO applied_results(key) ... ; UPDATE players SET xp = xp + amount ...; COMMIT;
  if (applied.has(key)) return `duplicate ${key} ignored (xp ${xp.get(player)})`;
  applied.add(key);
  xp.set(player, xp.get(player)! + amount);
  return `applied   ${key} +${amount} (xp ${xp.get(player)})`;
}

console.log(grantXp('m-118', 'u_7f3a', 340));
console.log(grantXp('m-118', 'u_91bc', 210));
console.log(grantXp('m-118', 'u_7f3a', 340));   // retry after a lost reply
console.log(grantXp('m-119', 'u_7f3a', 290));   // next match: a new key
applied   m-118:u_7f3a +340 (xp 1880)
applied   m-118:u_91bc +210 (xp 1010)
duplicate m-118:u_7f3a ignored (xp 1880)
applied   m-119:u_7f3a +290 (xp 2170)

In SQL the "applied" set is a table with a unique constraint on the key, so even two retries racing each other can't both insert.

Duping: why trades need transactions

Item duplication bugs come from operations that touch two records without making them atomic. A trade has two steps: remove the sword from A, add it to B. If the server crashes between them, the sword vanishes; if a retry or a second request runs the "add" twice, or two trades of the same sword run at once, it is duplicated.

ts · try it yourself
type Inv = Map<string, string[]>;
const inv = (): Inv => new Map([['alice', ['sword#77']], ['bob', []], ['cara', []]]);

// Unsafe: check, then (later) move, with no lock or transaction around it.
function unsafeTradeStart(i: Inv, from: string, item: string) { return i.get(from)!.includes(item); }
function unsafeTradeFinish(i: Inv, from: string, to: string, item: string) {
  i.set(from, i.get(from)!.filter((x) => x !== item));
  i.get(to)!.push(item);
}

const a = inv();
const okBob = unsafeTradeStart(a, 'alice', 'sword#77');    // two trade windows checked at the same time
const okCara = unsafeTradeStart(a, 'alice', 'sword#77');
if (okBob) unsafeTradeFinish(a, 'alice', 'bob', 'sword#77');
if (okCara) unsafeTradeFinish(a, 'alice', 'cara', 'sword#77');
console.log('unsafe:', JSON.stringify(Object.fromEntries(a)));

// Safe: check and move in one atomic step (a database transaction with row locks).
function trade(i: Inv, from: string, to: string, item: string): string {
  if (!i.get(from)!.includes(item)) return `refused ${from} -> ${to}: ${from} no longer has ${item}`;
  i.set(from, i.get(from)!.filter((x) => x !== item));
  i.get(to)!.push(item);
  return `traded  ${from} -> ${to}: ${item}`;
}
const b = inv();
console.log(trade(b, 'alice', 'bob', 'sword#77'));
console.log(trade(b, 'alice', 'cara', 'sword#77'));
console.log('safe:  ', JSON.stringify(Object.fromEntries(b)));
unsafe: {"alice":[],"bob":["sword#77"],"cara":["sword#77"]}
traded  alice -> bob: sword#77
refused alice -> cara: alice no longer has sword#77
safe:   {"alice":[],"bob":["sword#77"],"cara":[]}

Give valuable items unique ids (sword#77, not "1 sword") so audits can find duplicates, and keep an append-only ledger of currency and item movements; balances can then be recomputed and exploits traced.

Schema and data hygiene

  • Key everything by the identity provider's stable user id (sub with TAD, see Accounts & Sign-In), never by email or display name.
  • Version your save formats and migrate old records when you read them.
  • Keep personal data separate from game data, and delete it when the account is deleted (a legal requirement in many regions).
  • Back up the database and test restoring it; read the System Design course for replication, sharding and caching patterns.

Test yourself

A game server retries a 'grant 340 XP' request because the reply was lost, but the first request had already committed. What prevents a double grant?

  1. A faster network
  2. An idempotency key recorded in the same transaction as the grant
  3. Writing the XP every tick
  4. A bigger cache

With optimistic concurrency, what happens when a write's expected version no longer matches the stored version?

  1. The write overwrites the record anyway
  2. The write fails; the writer re-reads the record and applies its change again
  3. The database crashes
  4. Both versions are kept

Which data is usually NOT written to the persistent database?

  1. Inventory changes
  2. Match results
  3. Each player's position on every server tick
  4. Purchases