← Back to Tug of War

How Tug of War works

A real-time clicker running on Elixir, Phoenix LiveView, PostgreSQL, and a Raspberry Pi at home.

What this is

I built Tug of War as a small experiment: one shared number between 0 and 100,000,000, starting right in the middle at 50,000,000. Team Red pulls it down by one. Team Blue pushes it up by one. There are no accounts or login walls. You open the page, pick a side, and push against whoever else happens to be online.

Most of the fun for me was seeing how simple and cheap a real-time multiplayer backend can be when you let the BEAM do the heavy lifting.

How a click moves through the system

Browser (optimistic UI, 500ms click batch)
  -> SliderLive (WebSocket + silent rate-limit check)
    -> GameCore GenServer (in-memory score + player count)
      -> 200ms tick: Phoenix.PubSub broadcast to all clients
      -> 5s tick: async Postgres upsert (score + hour/day/month buckets)

Instant clicks without flooding the server

If every click sent a WebSocket frame to the server, a few hundred people mashing buttons would turn into thousands of tiny packets per second. Instead, a small JavaScript hook (BatchClicks) handles clicks right in the browser first. The score, percentage, red/blue split, and your session impact counter all update immediately in the DOM.

In the background, the hook keeps a running count of your red and blue clicks and flushes one batch_clicks message to the server every 500ms. If you aren't clicking, nothing gets sent. When the next server broadcast arrives, the client reconciles the authoritative score with any clicks still waiting in the local buffer.

State in BEAM memory, broadcasts on a fixed tick

On the server, a single GenServer (GameCore) holds the current score and online player count in RAM. Incoming batches from SliderLive hit GameCore as non-blocking GenServer.cast/2 calls. Nothing touches PostgreSQL on the click hot path.

Rather than broadcasting on every click, GameCore runs a 200ms timer and pushes the latest score and player count over Phoenix.PubSub to every connected LiveView. That caps broadcast frequency at 5 updates per second per client, whether ten people are playing or ten thousand.

Online player counts come from Phoenix.Presence. Each connected LiveView tracks its session on mount, and GameCore subscribes to presence_diff events to keep the count and peak-player numbers current without polling anything.

Quietly dealing with autoclickers

Put a public button on the internet and someone will point a script at it within five minutes. I didn't want CAPTCHAs ruining the page, and showing a "slow down" toast just tells a bot author where the rate limit sits so they can tune their script right under it.

So SliderLive checks each incoming batch against a human click-rate ceiling. Go over it and the server flips a shadowbanned flag on that socket without saying a word. From that point on, your clicks stop reaching GameCore, while your browser keeps seeing the bar move via a local offset layered on top of the real global score. From the bot's point of view, everything looks like it's working.

Analytics without a write bottleneck

The /stats page shows historical clicks, score swings, and peak players across hourly, daily, and monthly windows. Writing a row per click would bury a small database, so GameCore buffers analytics in memory and flushes once every 5 seconds (plus once more on graceful shutdown via terminate/2).

Each flush runs inside an async task and executes a single PostgreSQL INSERT ... ON CONFLICT DO UPDATE statement that updates the current hour, day, and month rows in analytics_buckets at the same time. Counters are summed atomically, while min score, max score, and peak players are merged with SQL LEAST and GREATEST.

If Postgres ever fails to accept a flush, the task sends the failed snapshot back to GameCore, which folds it back into the pending buffer for the next 5-second tick. And when the app starts up after downtime, Analytics.Recorder.backfill_gaps/3 inserts zero-click rows for any missed buckets so the charts on /stats stay continuous.

Running on a Raspberry Pi

The whole thing runs on a Raspberry Pi sitting at home, alongside a local PostgreSQL instance. Public traffic comes in through a Cloudflare Tunnel (cloudflared) to Caddy on localhost, which reverse-proxies to the Phoenix release running on Bandit.

Provisioning is handled with Ansible (system user, Postgres role, Caddy config, and a systemd unit). Deploys are just a shell script: rsync the source over SSH, compile the Mix release directly on the Pi, run migrations, restart systemd, and wait for /health to return 200 OK.

This /about page itself is a plain Phoenix controller route with no LiveView socket attached, so reading it costs the Pi almost nothing and doesn't count you as an active player in the arena.

Want to see it in action? Jump back into the Arena or watch the live numbers roll in on the Stats page.