# One live version per game, until two transactions overlap

> A PostgreSQL READ COMMITTED reproduction leaves two live game versions when go-live transactions overlap. A partial unique index with reordered updates enforces at most one.

Source: https://sheng.page/en/posts/game-version-gating/ · Published: 2026-11-24 · Author: Sheng

In a project I worked on, game versions follow a state machine: draft, sandbox, live, retired. The design calls for one live version per game and a second person's approval; tests cover sequential promotions. Reading the source again, I found that "one live" relied on two ordered UPDATE statements in one transaction, with no matching uniqueness constraint.

In a minimal PostgreSQL 16.15 reproduction under READ COMMITTED, overlapping promotions left two live versions in three runs out of three. Adding a partial unique index and reordering the statements makes the second transaction fail when the timing matches, leaving one live version. This is a finding; the project code hasn't been fixed. The project hasn't been deployed to production either, so there's no data to check whether it ever happened.

## The rule itself

Versions have four states. Promotion accepts draft or sandbox; retired cannot return to live, and the editing API rejects changes to live or retired profiles. Manual retirement reads the state first and, if that state is live, checks the operations role; approved promotion retires the previous version automatically. Versions are global per game across operators.

Games with versions but none live are hidden from operator lists, so anything not ready stays out of sight and operators decide once it is live; games with no version profiles at all are exempt. Daily reports exclude sandboxes unless one is requested by name, while RTP statistics exclude them entirely.

One place, one version: the new one arrives and the old one makes way. That is the core of the design.

## What the second person guards against

Going live is an approval kind. Approval moves the request from pending to executing, provided it is still pending and the approver isn't the requester. If execution fails, the handler tries to return it to pending so the approver can retry once the cause is fixed. This compare-and-swap-style update allows one executor while the request is executing.

What it can't stop is two requests: one person asks to put v2 of a game live, someone else asks for v3, each is approved, and those are two legitimate executions. Another layer of approval wouldn't close that gap, so the database has to stop it.

## Where the guarantee actually sat

The table has UNIQUE(game, version) and an ordinary index, with no restriction on live versions per game. The approved go-live action is one transaction: set this version live, then retire every other live version of the same game. A successful run on its own leaves exactly one live version.

READ COMMITTED is PostgreSQL's default isolation level; the project's go-live transaction inherits the connection setting. At that level, UPDATE searches using its statement snapshot and also sees earlier writes in its own transaction. When transaction B runs "retire the other live versions", A's new live state is uncommitted, so B cannot see that state and does not retire the version. The PostgreSQL documentation describes this as a possible inconsistent snapshot: waiting can reveal updates to the same row while other rows retain their snapshot visibility.

## Reproducing it

The minimal reproduction keeps only the relevant columns. A starts first and holds its transaction for two seconds; B starts half a second later and promotes a different version:

```sql
-- setup.sql
DROP TABLE IF EXISTS game_versions;
CREATE TABLE game_versions (
  game text NOT NULL, version text NOT NULL,
  state text NOT NULL CHECK (state IN ('draft','sandbox','live','retired')),
  UNIQUE (game, version));
INSERT INTO game_versions VALUES ('slot-a','v1','live'),('slot-a','v2','sandbox'),('slot-a','v3','sandbox');
```

```sql
-- a.sql (b.sql is the same with v3 for v2, plus SELECT pg_sleep(0.5); first)
BEGIN;
UPDATE game_versions SET state='live' WHERE game='slot-a' AND version='v2' AND state IN ('draft','sandbox');
UPDATE game_versions SET state='retired' WHERE game='slot-a' AND state='live' AND version<>'v2';
SELECT pg_sleep(2);
COMMIT;
```

```sh
#!/bin/sh
# Two approved go-live transactions for different versions of one game, overlapping in time.
# $1: setup file, $2/$3: the two sessions. B starts 0.5 s after A; A holds its transaction for 2 s.
psql -X -q -f "$1"
psql -X -q -f "$2" > /dev/null &
psql -X -q -f "$3" > /dev/null &
wait
psql -X -q -c "SELECT version, state FROM game_versions ORDER BY version"
```

```text
$ sh run.sh setup.sql a.sql b.sql
 version |  state  
---------+---------
 v1      | retired
 v2      | live
 v3      | live
(3 rows)
```

Three runs gave the same result. B's retire statement runs into v1, which A has locked, waits for A to commit and rechecks that row: v1 is retired by then, so B skips it. v2 is still sandbox in B's statement snapshot and does not match; waiting does not restart the whole scan. Both transactions succeed, and v2 and v3 are both live.

A rerun in PostgreSQL 16.15 under OrbStack on the Mac applied all 14 project migrations and called the sqlc-generated queries in the go-live function's order. Five runs out of five left v2 and v3 both live.

## Hand the rule to the database

A partial unique index on rows where state = 'live' allows at most one per game. This index checks uniqueness immediately on writes, so the go-live transaction has to retire the old version first, then set the new one live.

```sql
-- setup2.sql adds this line after the CREATE TABLE in setup.sql
CREATE UNIQUE INDEX one_live_per_game ON game_versions (game) WHERE state = 'live';

-- a2.sql (b2.sql likewise)
BEGIN;
UPDATE game_versions SET state='retired' WHERE game='slot-a' AND state='live' AND version<>'v2';
UPDATE game_versions SET state='live' WHERE game='slot-a' AND version='v2' AND state IN ('draft','sandbox');
SELECT pg_sleep(2);
COMMIT;
```

```text
$ sh run.sh setup2.sql a2.sql b2.sql
psql:b2.sql:4: ERROR:  duplicate key value violates unique constraint "one_live_per_game"
DETAIL:  Key (game)=(slot-a) already exists.
 version |  state  
---------+---------
 v1      | retired
 v2      | live
 v3      | sandbox
(3 rows)
```

While retiring the old version, B waits for A, then skips the retired row. Promoting v3 conflicts with v2 in the unique index; B's transaction fails, leaving one live version in three runs out of three.

On the project schema the same change gave SQLSTATE 23505 for B in five runs out of five, with v2 the only live version. The reordering isn't optional. Adding the index while keeping the original order makes even a single promotion fail, because the new version goes live while the old one still is. If the data already holds two live versions, the index can't be created until they are cleaned up.

All promotions could first lock the same game record with SELECT ... FOR UPDATE or share an advisory lock; SERIALIZABLE needs retry handling. I'd pick the index. With the rule in the schema, code that forgets it can't write the bad state.

Whether the failed transaction can follow the existing back-to-pending retry path still needs checking in the project.

The Rails guide warns that uniqueness validation creates no database constraint: two connections can still write the same value, so a unique index is needed. Bailis and colleagues' 2015 paper "Feral Concurrency Control" studied open-source Rails applications and found that some application-level checks without database support still permit integrity violations under concurrency.

## What I couldn't find

Bets supplying a maths version and hash check the model registration; the recorded fields are immutable, and RTP groups by version and hash (see "[The first RTP alert was replaced in six days](/en/posts/rtp-monitoring-threshold/)"). The legacy interface can omit them. I found no comparison with the live version's hash on the betting path. I also can't estimate how likely two go-live transactions are to collide in practice.

An unset amount or approval threshold is covered in "[Treat unset as zero: hard caps, approval thresholds and which way a kill switch fails](/en/posts/default-hard-caps-and-kill-switches/)".

## Notes

- States are draft, sandbox, live and retired; draft can go live, retired cannot return, and manual retirement checks the operations role when it reads live. Versions are global per game.
- The approval's compare-and-swap prevents another claim while a request is executing; it cannot stop separate requests promoting different versions of one game.
- The project promotes before retiring others; the minimal READ COMMITTED reproduction left two live versions three times out of three, and the project schema and queries did the same five times out of five under OrbStack.
- A partial unique index with retire-before-promote makes the second transaction fail on a duplicate key under the example's timing, leaving one live version; adding the index without reordering makes even a single promotion fail.
- The checked code remains unfixed. Bets check supplied model identities, but I found no comparison with the live version's hash on the betting path.

## Further reading

- PostgreSQL, "[Transaction isolation](https://www.postgresql.org/docs/16/transaction-iso.html)": official documentation on how an UPDATE under READ COMMITTED re-evaluates a row after waiting.
- PostgreSQL, "[Partial indexes](https://www.postgresql.org/docs/16/indexes-partial.html)": official documentation for indexes limited by a WHERE clause.
- PostgreSQL, "[Explicit locking](https://www.postgresql.org/docs/16/explicit-locking.html)": official documentation for SELECT ... FOR UPDATE and advisory locks.
- Rails Guides, "[Active Record validations](https://guides.rubyonrails.org/active_record_validations.html)": the framework's official guide; its uniqueness section says a validation is not a database constraint and a unique index is needed.
- Bailis et al., "[Feral concurrency control](https://www.bailis.org/papers/feral-sigmod2015.pdf)" (SIGMOD 2015): an academic paper measuring how application-level integrity checks in Rails applications fail under concurrency.
- Wikipedia, "[Race condition](https://en.wikipedia.org/wiki/Race_condition)": encyclopaedia entry on faults that depend on timing.
- Wikipedia, "[Compare-and-swap](https://en.wikipedia.org/wiki/Compare-and-swap)": encyclopaedia entry on the atomic write that applies only if the current value matches.
- Wikipedia, "[Separation of duties](https://en.wikipedia.org/wiki/Separation_of_duties)": encyclopaedia entry on splitting critical actions between people.

> Ideas and technical judgement by Sheng; drafted with Claude · Example run on PostgreSQL 16.15 (cloud Linux and an OrbStack container), project-schema reproduction run with Go 1.27.3; tools: Claude Code (Opus 5.5, Fable 5.1), Codex (gpt-6-astra), Grok CLI.