Architecture
A deep-dive into how the World Cup Pool is built, from the request path down to the database, plus the CI/CD topology and the domain model. Written for engineers extending or operating the system.
The World Cup Pool is a self-serve bracket competition for the 2026 FIFA World Cup. Friends create a pool, share a 6-character code, and each enters their predictions; a live leaderboard scores everyone as real results come in — no accounts, no passwords. It runs on fully managed infrastructure (Next.js on Vercel, Postgres on Neon), with privacy-friendly analytics, a daily automated database backup, and an end-to-end test suite that gates every deploy. An admin enters tournament results in a few clicks — or pulls them automatically from a live football-results API and confirms each change before it is applied.
- Framework
- Next.js 16 (App Router)
- Runtime
- React 19 · Node
- Data
- Prisma 6 · Neon Postgres
- Host
- Vercel — CI · CDN · Analytics
Operations
Vercel Web Analytics records page views via <Analytics /> in the root layout — privacy-friendly, no cookies.
A scheduled GitHub Action runs pg_dump every day, encrypting each snapshot (gpg, AES-256) before storing it as a 90-day artifact.
Vercel's git auto-deploy is off for main. GitHub Actions runs lint, the unit suite, the production build and Playwright's full create → pick → leaderboard flow against a real Postgres; main deploys only when all of them pass. Pull requests still get Vercel previews.
1 · Runtime request path
Every page is a React Server Component that reads through a single Prisma client into Neon. Interactive surfaces hydrate as client components and mutate state through /api route handlers.
2 · CI/CD & deployment topology
main is branch-protected; all work lands via PRs. Every PR and push to main runs ci.yml: lint → unit tests → build (with a placeholder DATABASE_URL), and Playwright against an ephemeral Postgres service. On main, a deploy job runs only after both pass: vercel pull → build → deploy --prebuilt --prod. Vercel's own git deploys are disabled for main(vercel.json) but still build previews for pull requests. The workflow runs with a read-only GITHUB_TOKEN and pins every action to a commit SHA rather than a movable tag; Dependabot checks the pins monthly and opens one grouped PR, which lands through the same checks as any other change.
3 · Data model
Four entities. Team is reference data seeded from data/worldcup2026.ts; the admin mutates only its result columns. A Pick is the join between a player and a team for a given round.
| id | cuid, PK |
| name | string |
| joinCode | string, unique (6-char) |
| locked | boolean — freezes picks |
| createdAt | datetime |
| id | cuid, PK — signed into the session cookie; never sent to other players |
| displayName | string |
| poolId | FK → Pool (cascade) |
| joinedAt | datetime |
| @@unique | (poolId, displayName) |
| id | cuid, PK |
| playerId | FK → Player (cascade) |
| teamCode | FK → Team |
| round | GROUP|FINAL4|SEMIFINAL|WINNER |
| groupId | string, nullable — only for GROUP |
| @@unique | (playerId, round, groupId, teamCode) |
| code | string, PK (e.g. BRA) |
| name | string |
| group | "A".."L" |
| reachedRound | string, nullable — set by admin |
| wonGroup | boolean — set by admin |
| isChampion | boolean — set by admin |
4 · Key flows
Create / join a pool
- HomeClient POSTs to apiUrl("/api/pools") or apiUrl("/api/pools/[code]/join").
- Route handler creates the Pool/Player and calls setPlayerIdCookie().
- Signed wcpool_session (httpOnly, 90-day, path /worldcup) is written; client routes to /pools/[code].
Make / edit picks
- PicksClient builds the full pick set client-side with progressive reveal.
- Save POSTs the entire set to /api/pools/[code]/picks.
- Handler validates round counts, then $transaction([deleteMany, createMany]) — an atomic replace.
- Reset = POST an empty array → deletes all picks.
Admin enters results
- AdminClient submits to /api/admin/results with the ADMIN_TOKEN.
- Handler verifies the token server-side, then updates Team result columns.
- Locking a pool flips Pool.locked; the picks API then rejects writes.
Auto-fetch results (optional)
- Admin clicks Fetch latest results; AdminClient POSTs to /api/admin/fetch-results (token-gated, needs FOOTBALL_API_KEY).
- Server pulls standings + matches from football-data.org; lib/results.ts maps teams and derives flags — group winners only once a group is finished, plus Final-4, finalists, champion.
- The endpoint returns PROPOSED changes and writes nothing.
- Admin reviews the diff and confirms; changes save via /api/admin/results.
Leaderboard
- Server component loads players + picks + teams in one pass.
- scoreAllPicks() computes per-round and total points purely in memory; getWinPercents() adds Win %.
- The page hands serializable rows to LeaderboardClient, which sorts them: Total desc by default, name as tie-break.
- Clicking Total or Win % re-sorts (click again to flip direction); rows without a Win % sort last.
5 · Scoring engine
lib/scoring.ts is pure and deterministic — no I/O — which makes it trivial to unit test. Knockout rounds are cumulative: a team that advances further also satisfies the earlier rounds (a finalist still earns its Final-4 points; the champion earns all three). Correctness is round-specific:
| Round | Correct when… | Pts | × | Max |
|---|---|---|---|---|
| GROUP | team.wonGroup && team.group === pick.groupId | 1 | 12 | 12 |
| FINAL4 | team reached ≥ Final 4 (cumulative) | 4 | 4 | 16 |
| SEMIFINAL | team reached ≥ Semi-Final (cumulative) | 8 | 2 | 16 |
| WINNER | team.isChampion | 16 | 1 | 16 |
| Maximum achievable | 60 | |||
6 · Win probability (leaderboard)
The leaderboard's Win % column is each player's estimated chance of finishing 1st, from a Monte-Carlo simulation of the rest of the tournament. It appears only once a live knockout bracket is available.
- Bracket —
lib/tournament-bracket.tspulls the knockout matches from football-data.org (FOOTBALL_API_KEY), resolves each team to our codes, and builds the current bracket: the earliest undecided round is the frontier; winners of adjacent matches meet in the next round up to the final. Finished semifinals / final lock in milestones for already-eliminated teams. The provider back-fills a round's teams only once the previous round is official, so a half-empty frontier (e.g. “ESP vs TBD”) is rebuilt from the previous round's winners; if a side is still unknown the bracket is treated as unavailable — it never simulates against a TBD opponent. - Match model —
data/ratings.tsholds a FIFA/Elo rating per team;eloWinProbconverts a rating gap into a single-match win probability (logistic on the difference — a ~100-point edge ≈ 64%). - Simulate —
lib/win-probability.tsplays the undecided matches ~20,000 times. Each trial yields a full set of team results, fed through the samescoreAllPicksthe leaderboard uses, then the players are ranked (a tie for 1st splits the credit). - Win % — the share of trials each player finished 1st. Computed server-side and cached (~10 min result, ~15 min bracket fetch) so a page view never re-runs the simulation or re-hits the API. An already-decided bracket skips the randomness — one deterministic pass.
Pure and unit-tested: the engine and bracket parser are covered by fixtures, including a frozen real-API snapshot. With no FOOTBALL_API_KEYor no knockout data, the column simply hides.
7 · Security & sessions
- No passwords. Identity = the
wcpool_sessioncookie:playerId.hmac(editing) orplayerId.view.hmac(view-only), HMAC-SHA256 signed over the id and the mode and checked withtimingSafeEqualinlib/session.ts(httpOnly, SameSite=Lax,Securein production, scoped to/worldcup). An unsigned or tampered cookie is treated as no session. - Signing key:
SESSION_SECRETonly — deliberately independent ofADMIN_TOKEN, so the admin token can be rotated without signing players out and a leaked one can't forge sessions. Production refuses to sign without it; dev/test use a fixed key. Changing it signs everyone out. - Re-joining a pool with an existing display name signs you in as that player view-only: there are no passwords, so the pool code plus a name must not unlock someone's picks. Only the session issued when the player first joined can edit (a device that already holds it keeps editing on re-join), and the picks API returns 403 to a view-only session.
- Other players' ids never reach the browser: the leaderboard and player list link to
picks?player=<display name>. - The cookie alone grants nothing: every API route verifies the player belongs to the pool named in the URL. The picks API validates JSON shape, rounds, groups and team codes before writing.
- Every
/api/admin/*route — reads included — is gated by a server-checkedADMIN_TOKEN(sent asx-admin-token, compared in constant time bylib/admin-auth.ts);/api/admin/resultswrites only whitelisted result columns. The/adminHTML renders nothing sensitive until the token is verified. - Public routes return generic 500 messages; the detail is logged server-side only.
- Pool creation (5/min) and joining (15/min) are rate-limited per client IP by
lib/rate-limit.ts— in-memory and per-instance, so best-effort only. - Viewing another player's picks reuses
PicksClientin alocked(read-only) mode. - Picks close when the admin locks the pool or the global deadline in
lib/lock.tspasses (end of Jun 10, 2026) — enforced in both the picks API and UI.
8 · Connection & build notes
DATABASE_URLis the pooled (PgBouncer) Neon URL for app queries.DATABASE_URL_UNPOOLED(directUrl) is used for migrations.- Prisma is a global singleton to survive serverless function reuse and avoid connection storms.
- Pages use
export const dynamic = "force-dynamic"so picks/leaderboards are never statically cached. - Build:
prisma generate → vitest run → next build— a failing test blocks the deploy. - Mounted at
/worldcup, not a domain root:BASE_PATHinlib/site.tsfeedsnext.config.ts'sbasePathand the canonical URL in the root layout.basePathdoes not rewritefetch(), so every client API call goes throughapiUrl(); a unit test pins config and helper together. - Lint, tests and build need only a placeholder
DATABASE_URL— Prisma must construct, but nothing connects (tests mock@/lib/db). - Vercel Web Analytics via
<Analytics />(@vercel/analytics) mounted in the root layout — privacy-friendly page-view metrics.
9 · Backups & durability
Pools, players, and picks exist only in Neon — the seed Team rows regenerate from data/worldcup2026.ts, but user data does not. After picks lock on Jun 10 that data is effectively frozen, so a snapshot at lock protects nearly everything.
On-demand (local)
npm run db:backup→ timestamped, gzippedpg_dumpinbackups/(git-ignored).npm run db:restore -- <file>restores (prompts first; dumps use--clean --if-exists).scripts/db-url.shresolves the direct/unpooled URL — best forpg_dump.
Automated (GitHub Actions)
.github/workflows/backup.ymlrunspg_dumpdaily + on demand.- Each dump is encrypted with gpg (AES-256, passphrase fed on stdin) and only the
.gpgis uploaded as a 90-day workflow artifact — the repo is public, so artifacts are visible to any signed-in GitHub user. - Needs
DATABASE_URL_UNPOOLEDandBACKUP_PASSPHRASErepo secrets; without the passphrase the job fails rather than upload plaintext. - Restore:
gpg --decryptthe artifact, thennpm run db:restore. - Neon point-in-time restore is a short-window safety net; these dumps are the durable copy.
10 · Repository map
app/
layout.tsx root layout · <Analytics/> · canonical metadata
page.tsx · HomeClient.tsx create / join a pool
pools/[code]/
page.tsx pool dashboard
picks/ page.tsx · PicksClient progressive bracket picker
leaderboard/ page.tsx · LeaderboardClient
scored standings + win % · sortable table
how-it-works/ · architecture/ static reference pages
admin/ page.tsx · AdminClient results entry (token-gated)
api/
pools/route.ts create pool
pools/[code]/join/route.ts join pool
pools/[code]/picks/route.ts atomic replace of a player's picks
admin/results/route.ts set team results / lock pool
admin/fetch-results/route.ts pull live results from football-data.org
admin/data/route.ts admin dashboard data (token-gated read)
admin/players/[id]/route.ts delete a player (picks cascade)
health/route.ts DB liveness check
components/ Navigation (client · active-link) · HeroBanner · ThemeToggle
lib/ db.ts (Prisma singleton) · session.ts (signed cookie) · admin-auth.ts
site.ts (BASE_PATH · apiUrl) · rate-limit.ts (in-memory)
scoring.ts (pure, cumulative) · lock.ts (pick deadline)
results.ts (map providers + derive fetched results)
win-probability.ts · tournament-bracket.ts (Elo Monte-Carlo)
data/ worldcup2026.ts (48 teams, rounds, points) · ratings.ts (Elo)
prisma/ schema.prisma · seed.ts
scripts/ backup-db.sh · restore-db.sh · db-url.sh
instrumentation*.ts · app/global-error.tsx Sentry (inert until DSN set)
.github/ workflows/ci.yml (lint · test · build · Playwright + Postgres · deploy)
workflows/backup.yml (scheduled, encrypted pg_dump)
__tests__/ vitest unit + component tests (Prisma mocked)
e2e/ playwright: smoke · admin (public pages) · flow (real DB)