Back to articles
October 30, 2026React NativeFastAPIPostgreSQLReal-TimeSystem Design

Building a Live Two-Player Game in a Social App: Let the Server Own the Clock

Lessons from building Two Truths & a Lie for a React Native social app with FastAPI and Postgres: server-side timers, row locks, hidden answers, one game per pair, and games that survive a closed app.

A game with two players and a countdown looks simple. Show a timer, wait for both answers, move on.

Then real phones get involved. One player locks their screen mid-round. The other closes the app to answer a message. Both tap "invite" at the same second. Someone's phone clock is two minutes off. Every one of these breaks a game that trusts the phone.

I recently built a "Play Together" feature for a social app I'm working on for a client. Two people who have already had a call can invite each other to a live game of Two Truths & a Lie. Each round, both write three statements about themselves (two true, one lie), then both guess which of the other's statements is the lie. Five rounds, points for every right guess, and a winner at the end.

The game is fun. The backend behind it taught me more than I expected. Here is what I learned.


The Setup in One Picture

 Invite ──► PENDING ──accept──► LOBBY ──both tap Start──► PLAYING ──5 rounds──► FINISHED
              │                    │                         │
           5 min                 120 s                each round:
              ▼                    ▼                  WRITING  (90 s)
           EXPIRED              EXPIRED               GUESSING (30 s)
                                                      REVEAL   (5 s)
 
 Exit Game, or nobody writes in a round ──► ABANDONED

React Native on the phones, FastAPI and Postgres on the server, and a live events subscription that tells each phone when something changed. Every number above lives in config, so changing the rounds or timers is a settings change, not a code change.


Lesson 1: The Phone Can't Own the Timer

The obvious way is a countdown on each phone. When it hits zero, the phone tells the server "time's up".

That fails the moment a phone goes to the background. iOS pauses your JavaScript. The countdown stops. If both players lock their screens, nobody ever says "time's up", and the game is stuck in round 2 forever.

So the server owns the clock. Every open game has one column, deadline_at: the moment the server moves it on by itself. A PENDING invite expires at its deadline. In a round, the deadline ends the current phase.

class Game(Base):
    status: Mapped[GameStatus]          # pending, lobby, playing, finished...
    phase: Mapped[GamePhase | None]     # writing, guessing, reveal
    round_number: Mapped[int]
    # When the server moves the game on by itself. Null once the game is over.
    deadline_at: Mapped[datetime | None]

The phone just draws a countdown to phaseEndsAt. If the phone is asleep, nothing is lost. When it wakes up, it asks the server what state the game is in now.


Lesson 2: One Function Moves the Game On

All the rules for "time ran out" live in one function. It runs in a loop, because one late check might need to catch up more than one step (the guessing ended and the reveal ended).

def _advance(game: Game, now: datetime) -> bool:
    changed = False
    while game.status in OPEN_STATUSES and game.deadline_at and game.deadline_at <= now:
        changed = True
        if game.status != GameStatus.PLAYING:   # unanswered invite, or never started
            game.status = GameStatus.EXPIRED
            _end(game, now)
        elif game.phase == GamePhase.WRITING:
            round_ = game.current_round
            if round_.sender_statements is None and round_.receiver_statements is None:
                game.status = GameStatus.ABANDONED   # neither is playing any more
                _end(game, now)
            else:
                _start_guessing(game, now)
        elif game.phase == GamePhase.GUESSING:
            _reveal(game, now)
        elif game.round_number >= settings.game_rounds:
            game.status = GameStatus.FINISHED
            _end(game, now)
        else:
            _new_round(game, now)
    return changed

Having one place for these rules made the odd cases easy to decide:

  • Only one player wrote? The game goes on. The other one still gets to guess, and the one who didn't write just has nothing to be guessed.
  • Nobody wrote? Both players are gone. The game is abandoned instead of running five empty rounds.
  • Both finished early? The phase ends right away. Nobody waits 90 seconds for a timer when both answers are already in.

Lesson 3: Every Server Runs the Clock, Row Locks Keep It Fair

A background task checks every second for games whose deadline has passed:

async def advance_due_games() -> int:
    now = datetime.now(UTC)
    async with SessionLocal() as session:
        games = list(await session.scalars(
            select(Game)
            .where(Game.status.in_(OPEN_STATUSES), Game.deadline_at <= now)
            .order_by(Game.deadline_at)
            .limit(100)
            .with_for_update(of=Game, skip_locked=True)
        ))
        moved = [game for game in games if _advance(game, now)]
        await session.commit()
    for game in moved:
        await _announce(game)   # tell both players
    return len(moved)

When the backend runs on more than one server process, every process runs this loop. That sounds like a race, but FOR UPDATE SKIP LOCKED makes it safe. The first process to lock a game moves it on. The others skip that row and move to the next one. No game jumps two rounds because two servers saw it at once.

A partial index on deadline_at (only for open games) keeps this query cheap, even when finished games pile up.


Lesson 4: Catch Up Before Every Action

The timer loop runs every second, but a player's tap can land in the gap. A guess can arrive 200 ms after the guessing phase should have ended.

So every action loads the game with a lock and applies any countdown that already ran out first:

async def _lock(session, game_id, user_id) -> Game:
    game = await _load(session, game_id, user_id, lock=True)
    if _advance(game, datetime.now(UTC)):
        await session.commit()
        await _announce(game)
        game = await _load(session, game_id, user_id, lock=True)
    return game

Now a late guess gets a clear "It's not time to guess" error. It never quietly counts toward a round that is already over. The game is correct even if the timer loop is a little behind.


Lesson 5: Don't Send the Lie to the Phone

The easy way is to send the full round to both phones and let the UI hide the answer until the reveal.

But anything you send to a phone, a curious user can read. Open the network inspector, and you can see which statement is the lie before you guess.

So the server builds a different view of the same round for each player:

writing = is_current and game.phase == GamePhase.WRITING
revealed = not is_current or game.phase == GamePhase.REVEAL or game.status == GameStatus.FINISHED
 
return RoundView(
    my_statements=my_statements,
    my_lie_index=my_lie,
    partner_submitted=their_statements is not None,
    partner_statements=None if writing else their_statements,
    partner_lie_index=their_lie if revealed else None,
    partner_guess=their_guess if revealed else None,
)

While both are writing, you only learn that your partner has submitted, not what. During guessing, you see their statements but not the lie. Only after the reveal does the lie leave the server. You can't cheat with data you never received.


Lesson 6: One Open Game per Pair, Enforced by the Database

Two people who just had a fun call will often invite each other at the same moment. Both checks ("is there already a game between us?") run at the same time, both see nothing, and both insert. Now there are two games.

A check in Python can't fix this. A unique index can:

Index(
    "uq_games_open_pair",
    func.least(text("sender_id"), text("receiver_id")),
    func.greatest(text("sender_id"), text("receiver_id")),
    unique=True,
    postgresql_where=text("status IN ('pending', 'lobby', 'playing')"),
)

least and greatest make the pair the same no matter who invited whom. The WHERE makes the rule apply only to open games, so the same two people can play again tomorrow. The second insert fails, and the API turns that into a friendly message: "There is already an open game between you."

Each player can also only be in one game at a time, so nobody gets pulled into a second game while they are in the middle of one.


Lesson 7: Events Are Hints, Queries Are the Truth

Every change reaches the other player as a live event: invited, accepted, updated, finished. But events get missed. The app was closed, the network dropped, the phone was in a tunnel.

So the app never trusts events alone. Two queries rebuild the picture from scratch:

  • gameInvites: invites still waiting for my answer, so the "invited you to play" popup shows up even if the app was closed when the invite came in.
  • myCurrentGame: the game I'm in right now, so reopening the app drops the player back into the round they left.

An event just says "something changed, go and look". The query says what actually is. That one rule removed a whole class of "my screen is stuck" bugs.


Lesson 8: Decide How Every Game Ends

Most of the work wasn't the happy path. It was writing down every way a game can stop, and making sure the other player is always told:

  • The invite isn't answered in 5 minutes: expired, and both are told.
  • Accepted, but both don't tap Start within 2 minutes: expired.
  • The sender takes the invite back: cancelled.
  • Someone taps Exit Game: abandoned, and the other player sees who left.
  • One of them unmatches mid-game: the game ends right away.
  • All five rounds played: finished, with a "Play Again" that simply sends a new invite.

Writing these as explicit statuses made the mobile side much simpler. The app doesn't guess why a game ended. The server tells it.


What I'd Add Next

Shipping honestly means naming the gaps:

  • Server time for the countdown. The phone counts down to phaseEndsAt using its own clock. If a phone's clock is off, its timer is off too. The fix is to send the server's current time with each game, so the app can correct for the difference.
  • A smarter scheduler. Checking every second is simple and works well at today's scale. With many thousands of live games, a queue that wakes up exactly at each deadline would do less work.
  • Prompts from the admin panel. The round ideas ("Your childhood", "A hidden talent") are a fixed list in code for now. The next step is letting the client manage them from the admin dashboard.
  • The second game. Sketch & Guess shows as "coming soon". The same state machine should carry it, with a drawing phase instead of a writing phase.

Key Takeaways

  • On mobile, the server owns the clock. Phones sleep, and their timers stop with them.
  • Keep every "time ran out" rule in one function that can catch up more than one step.
  • Use FOR UPDATE SKIP LOCKED so every server can run the timer safely.
  • Apply overdue deadlines before every action, so late taps never count.
  • Never send hidden answers to the phone. Build a separate view for each player.
  • Enforce "one open game per pair" with a partial unique index, not an if in your code.
  • Events are hints, queries are the truth. Let the app rebuild its state after it was closed.

Building a social or real-time app where two people have to see the same thing at the same time? Let's connect and we can talk it through.

Building a mobile app or web platform?

I take products from concept to a production release in 4–6 weeks. Let's talk through your goals.

Start a conversation

Have a project in mind?

Tell me what you're building and where you're stuck. I'll come back with a plan, a timeline and an honest estimate.

muizz@themoiz.com
Replies within 24 hours
Hire me on Upwork