Skip to content
Mai Trinh
  • Web App
  • 16 min read

My web game was "fine"… until I measured it

The site felt a bit slow, and I was about to rewrite the server in Rust. Measuring showed the website never ran on that server: the culprit was a CSP line that blocked the CDN cache, and on the relay, a loop that sent the whole list to everyone.

Mai Trinh

Software Engineer

On this page

A casual web game with more than 60 standalone games; all numbers measured on 1 December 2026.

At a glance

  • The problem: the home page of a small web game was never served from the CDN cache (always MISS, 2-second cold starts), and the WebSocket relay on a 2-core VPS would overload at around 2,000 people with the site open.
  • The cause: a nonce-based CSP forced every page to render dynamically; the HTML carried 263 KB of inline SVG covers; every game's CSS loaded on every page; and the online lobby resent the whole list to each person whenever one thing changed.
  • The result: six rounds of fixes, none of them a change of technology. Pages come from the CDN in about 50–60 ms; a 1,000-person lobby went from 75% to 15% of a CPU core; the HTML, the CSS and the redirect at / all got leaner.

Background: a small web game that was "fine"

Chơi Chút is a small web game I built: more than 60 mini games that run right in the browser, from chess, xiangqi and ô ăn quan to 2048, minesweeper and pool. No install, no ads. The website is written in Next.js and runs on Vercel. Playing with friends and the online lobby, though, need a WebSocket server that runs all the time to pass moves between two players, so I set up a small Node.js relay on a VPS.

The VPS is very modest: 2 vCPUs (Intel Xeon E5-2680 v4, from 2016), 2 GB of RAM, shared with a few other projects of mine. When I checked, the whole machine had only about 1 GB of RAM free. The relay runs in Docker with a 256 MB RAM limit, so that if it misbehaves it can't take the other sites down with it.

Everything worked. No errors, no complaints, not many players yet. But every time I opened the site myself, it felt a bit slow. Not broken, just slower than I thought a small game site should be. The problem was that I didn't know exactly where the slowness came from.

And there was another worry: what if one day lots of people play at once? Could a VPS with 2 cores and 2 GB of RAM cope?

Should I rewrite it in Rust?

My first thought was to move the server to Rust. The reasons sounded quite reasonable:

  • No garbage collector: Node.js now and then has to pause to clean up memory, while Rust manages memory at compile time, so latency is steadier and more predictable.
  • Far less RAM: each WebSocket connection in Rust (with tokio) costs only a few KB. Under a 256 MB limit, the same RAM could hold many more connections.
  • Compiled to machine code: no JavaScript runtime, fast startup, and better use of a weak CPU.
  • Memory safety and safe concurrency: the compiler blocks a whole class of bugs before the code even runs.
  • A small Docker image: a single binary of a few MB, compared with a full Node image.

On paper, this was exactly the right fit for a small VPS.

But rewriting a server means one more language to maintain, more time, and the risk of new bugs. Before doing that, I asked myself: am I sure the server is what's slow?

Round 0: measure first

I decided to stop guessing and measure. No fancy tools needed:

curl -s -o /dev/null -w "ttfb=%{time_starttransfer} total=%{time_total} size=%{size_download}\n" https://choichut.maitrinh.dev/vi
curl -sI https://choichut.maitrinh.dev/vi | grep -i x-vercel-cache

The first command measures time to first byte (TTFB) and page size. The second tells whether Vercel served the page from its CDN cache.

Live site, before any fix

  • First visit to the home page (cold start)

    Value
    TTFB about 2.0 seconds
  • Later visits

    Value
    0.3–0.5 seconds
  • CDN cache (x-vercel-cache)

    Value
    MISS every time
  • Visiting /

    Value
    an extra 307 redirect to /vi (0.2–0.9 seconds)
  • Home page HTML

    Value
    412 KB uncompressed (60 KB with brotli)
  • JS + CSS on first load

    Value
    about 300 KB compressed, 49 KB of it the main CSS file

My feeling was right: the site really was slow. A home page that is almost identical for everyone was never cached, and the first visitor had to wait 2 seconds.

But there was something I'd overlooked from the start: the website doesn't run on the VPS. It runs on Vercel. The relay on the VPS only serves games with friends and has nothing to do with loading pages. If I rewrote the relay in Rust, the website would be exactly as slow as before.

From this table I took four jobs for the web side (cache, redirect, HTML, CSS) and one open question for the relay (how many people it can take). I worked through them one round at a time, measuring again after each.

Round 1: get pages into the CDN cache

Before the fix

  • x-vercel-cache always MISS: every view was rendered again on the server.
  • TTFB about 0.3–0.5 seconds with a warm server, about 2 seconds on a cold start.

The culprit: one line of security config

When I built the site, I followed a "strict CSP" (Content Security Policy) guide to guard against XSS. The common approach uses a nonce: each request generates a random string, attached to the CSP header and to every <script> tag. The browser only runs scripts that carry that exact nonce.

In Next.js, the nonce is created in the proxy (middleware) and read back by the layout. Trimmed down, the code looked like this:

// proxy.ts (before, trimmed)
const nonce = Buffer.from(crypto.randomUUID()).toString('base64');
const csp = `script-src 'self' 'nonce-${nonce}' 'strict-dynamic'; style-src 'self' 'nonce-${nonce}'; ...`;

// app/[lang]/layout.tsx (before, trimmed)
export const dynamic = 'force-dynamic';
// ...
const nonce = (await headers()).get('x-nonce');

Sounds very safe. But think it through: if every request has a different nonce, every request's HTML is different too. The page can't be built ahead of time and can't be cached on the CDN. Every view has to be rendered on the server, and if the server is "asleep", the user waits for a cold start.

The Next.js docs actually say this clearly: with a nonce, every page must render dynamically, you lose static optimization and ISR, and the CDN can't cache. But when you follow a security guide, few people read as far as the performance trade-off.

Besides the nonce, I found a few other things quietly forcing pages to render dynamically:

  • Invite links (?room=...) read the query string to build a custom preview title when shared in chat ("You're invited to a Caro table").
  • The daily chess puzzle depends on today's date.
  • "Hell" mode pipes generates a random puzzle on the server.

What I changed

A fixed CSP instead of a nonce. I moved to a fixed policy, set in next.config.ts so it applies to every path, including pages served straight from the CDN:

// core/security/index.ts (after)
export function contentSecurityPolicy(development = false): string {
  return [
    "default-src 'self'",
    `script-src 'self' 'unsafe-inline' 'wasm-unsafe-eval'${development ? " 'unsafe-eval'" : ''}`,
    "style-src 'self' 'unsafe-inline'",
    // ... img, font, connect-src to the relay, worker-src, frame-ancestors 'none' ...
  ].join('; ');
}

The layout dropped force-dynamic and headers(), and uses generateStaticParams instead to prebuild the page for each language.

The trade-off: the CSP now allows inline scripts ('unsafe-inline'), because a static page can't carry a nonce. The XSS protection is a little thinner than before. I accepted that because:

  • Scripts can still only load from the site's own domain.
  • Nothing renders user content as HTML; React escapes everything.
  • The other headers stay as they were: frame-ancestors 'none', X-Frame-Options, HSTS…
This was a considered decision, not "turn off security to go faster". If your site renders user-generated content as HTML, think harder about it.

Prerendering and ISR.

  • The home page and the chess puzzle pages: prebuilt, refreshed every 5 minutes (export const revalidate = 300), so the popular-games order and the new daily puzzle still update.
  • Each game's page: generateStaticParams returns an empty array, meaning it renders on the first visit and is cached after that.
  • "Hell" mode pipes: still rendered per request with await connection(), because every visit needs a new puzzle.

Keeping invite-link previews. An invite link has to read the query string for its custom preview title, so it can't be static. Rather than let it drag the whole home page into dynamic rendering, I split it into its own route with a rewrite:

// next.config.ts
async rewrites() {
  const room = [{ type: 'query' as const, key: 'room' }];
  return {
    beforeFiles: [
      { source: '/:lang([a-z]{2})', has: room, destination: '/:lang/invite' },
      { source: '/:lang([a-z]{2})/play/caro', has: room, destination: '/:lang/play/caro/invite' },
    ],
  };
}

Whoever opens an invite link still sees the original URL in the address bar and still gets the custom preview. Every other normal visit gets the cached page.

A slimmer proxy. The proxy used to run on every request to generate the nonce. Now it has only two jobs: handle paths without a language prefix, and mark the API as no-store. Pages that already have a language no longer go through the proxy. I added a small test so the language list in the proxy's matcher can never drift from the site's language config.

Checks before deploying

I ran the production build on my machine and checked:

  • Build output: the home page, game pages and chess puzzle pages are all marked as prerendered; only invite links and "hell" mode pipes still render on demand.
  • Pages return x-nextjs-cache: HIT, with the CSP and all the security headers present.
  • Invite links still get the right title, "You're invited to a Caro table", and the page still joins the room on its own.
  • A test game of chess: the computer still moves, so the Stockfish engine (WebAssembly) still runs under the new CSP.
  • No CSP errors in the console; all 353 tests pass.

Result

Measured on the live site

  • CDN cache

    Before
    always MISS
    After
    HIT or PRERENDER
  • Server response time (TTFB minus TLS)

    Before
    about 300 ms, about 2 seconds on a cold start
    After
    about 50–60 ms

Two consequences I infer from pages now coming from the CDN cache, rather than measured directly: visitors to a cached page no longer hit cold starts, and more views add almost no work for the server.

The most important part isn't the 50 ms but the second consequence: in principle, whether 10 or 100,000 people open the home page at once, the CDN serves it instead of the server. That answers the "what if it gets busy" worry on the web side, without changing language or upgrading the machine.

An unexpected bug while checking the live site

While checking the live site after deploying, I found that the "Invite someone online" button on individual game pages did nothing. It turned out the online lobby panel was only mounted on the home page: the button fired an "open lobby" event, but nothing on the game page was listening. This bug had nothing to do with the optimization, but if I hadn't checked production carefully I'd never have seen it. After the fix, I tried again on the live site: pressing the button on the Caro page opens the "Play online" panel with the right game already selected.

One more small note: the site has a service worker, so a browser that has visited before may still run the old JS for one visit. When checking after a deploy, remember to unregister the service worker and clear the cache in your test tab.

Round 2: load testing the relay, and the bottleneck wasn't where I thought

The web side now had the CDN to lean on. The realtime relay on the VPS is different: it has to hold a live connection for every player and can't be cached. This is where the question "do I need Rust?" actually means something.

How I measured

I didn't fire load at the real VPS, since it also runs other sites. Instead, I ran the relay's exact Docker image on my machine and tried to make it exactly as slow as the VPS:

  • Measure CPU speed on both sides. The same benchmark (building the lobby list and turning it into JSON for 3 seconds) gave 36,538 runs/second on my machine and 13,035 runs/second on the VPS. One VPS core is about 2.8 times slower.
  • Limit the container to 0.4 CPU and 256 MB of RAM. At that level, the benchmark inside the container roughly matches one VPS core. The relay is single-threaded, so one core is what needs simulating.
  • A load test script (relay/loadtest.mjs) simulates two kinds of users: game tables (two people, each making a move every 2 seconds, faster than real players) and people sitting in the lobby (each switching game about once a minute). Every fake player has its own IP address, so the relay's per-IP limits behave as they would with real people.
  • What I measured: the container's CPU and RAM, and the latency of a move (from one side sending to the other side receiving).

This measurement has limits: it doesn't include TLS encryption (on the VPS that's Caddy's job, on the other core) and it doesn't include real network latency.

Twice I nearly drew the wrong conclusion because of the tooling

Docker created fake latency. On the first run, with 2,000 tables, p95 latency was already at 113 ms while CPU was only a third used. The cause is how Docker limits CPU: by default it works in 100 ms periods, so at 0.4 CPU the container runs for 40 ms and is then paused for 60 ms. A real VPS has no such stalls. Shrinking the period to 10 ms (--cpu-period=10000 --cpu-quota=4000) brought p95 at the same load down from 113 ms to 20 ms.

Were the dropped connections at 5,000 tables real? At 5,000 tables (the MAX_ROOMS ceiling in the code), 1,000 to 2,900 connections were cut mid-test (ECONNRESET), while the relay log showed no errors. I ran two control tests: the relay outside Docker, and inside Docker with no CPU limit. Both held all 10,000 connections with no errors. But in the unlimited run, the relay used 42% of one core on my machine, which is about 1.2 VPS cores. So the failure was real: one VPS core can't keep up with 5,000 tables, and new connections were dropped because the relay couldn't finish the handshake in time.

Results before any fix

Relay on my machine, CPU limited to one VPS core. CPU is a percentage of one VPS core.

  • 500 tables

    Connections
    1,000
    CPU
    ~12%
    RAM
    37 MB
    Move latency (median / p95 / p99)
    1 / 2 / 6 ms
    Errors
    0
  • 2,000 tables

    Connections
    4,000
    CPU
    ~33%
    RAM
    65 MB
    Move latency (median / p95 / p99)
    1 / 20 / 272 ms
    Errors
    0
  • 5,000 tables

    Connections
    10,000
    CPU
    overloaded
    RAM
    104 MB
    Move latency (median / p95 / p99)
    3 / 507 / 619 ms
    Errors
    1,000–2,900 connections dropped
  • 100 tables + 300 in the lobby

    Connections
    500
    CPU
    ~25%
    RAM
    33 MB
    Move latency (median / p95 / p99)
    1 / 103 / 599 ms
    Errors
    0
  • 100 tables + 1,000 in the lobby

    Connections
    1,200
    CPU
    ~75%
    RAM
    42 MB
    Move latency (median / p95 / p99)
    77 / 388 / 641 ms
    Errors
    0
  • 100 tables + 2,000 in the lobby

    Connections
    2,200
    CPU
    overloaded
    RAM
    46 MB
    Move latency (median / p95 / p99)
    230 / 824 / 1,592 ms
    Errors
    0

Outgoing traffic for the lobby alone: 7.4 MB/s with 300 people, 23.7 MB/s with 1,000, and 26.5 MB/s with 2,000 (by then held back by the CPU).

Reading the table

  • RAM is never the limit. 10,000 connections take only 104 MB of the 256 MB. My "Rust uses less RAM" argument didn't solve any problem that actually existed here.
  • Game tables are cheap. About 4,000 tables (8,000 people playing, each moving every 2 seconds) fit in one VPS core.
  • The lobby is the bottleneck, and it arrives much sooner: 1,000 people already take about three quarters of a core, and 2,000 is overload. Worse, a heavy lobby slows moves at every table: at 1,000 people, median latency jumped from 1 ms to 77 ms.

Why is the lobby so expensive? Every page of the site connects to the lobby, so the number of people in the lobby is the number of people with the site open. And every time someone joins, leaves or switches game, the relay batches the changes for 150 ms and then does this:

  1. Rebuilds the whole list of people online (up to 200 people, about 10 KB).
  2. Sends it to everyone.
  3. Turns the list into JSON separately for each person (because each copy includes the recipient's id and the invites that person can see).

Once the lobby is busy enough that something is always changing, the relay broadcasts the whole list about 6–7 times a second, to each person. The numbers match: traffic grows almost in proportion to the number of people (7.4 MB/s for 300, 23.7 MB/s for 1,000), so each person with the site open costs the relay about 25 KB per second, even if they never open the lobby panel.

This is an algorithm bug: resending everything when only one thing changed. Rewritten in Rust, the relay would still have to send the same bytes to the same people.

Round 3: the lobby sends only what changed

What I changed

  • Someone joining the lobby gets the full list once.
  • After that the relay sends only the changes: who joined, who left, who switched game. Changes are batched every 0.5 seconds, turned into JSON once, and the same bytes go to everyone.
  • Invites are sent as "add" or "remove", and only to the people who can see that invite.
  • Opening a second tab no longer sends a message to the whole lobby.
  • The web side merges the changes into the list it already has. The UI shows at most 200 rows, but the "Online now" count still counts everyone.

I deployed the web first and the relay second: the new web understands both the old and the new message format, so no tab broke during the switch.

Checks

  • The relay passes 17 tests, including a new one for the changes: switching game, opening a second tab, leaving the lobby, and checking that the full list is sent exactly once.
  • A test with "real people": the browser is person A, a script plays person B. When B joins the lobby they appear in A's list, switching game shows "playing Chess", an invite shows up for A right away, and leaving makes B disappear.

Result

Same method, same load

  • 300

    CPU before → after
    25% → 8%
    Traffic before → after
    7.4 → 0.1 MB/s
    Move latency p95 before → after
    103 → 2 ms
  • 1,000

    CPU before → after
    75% → 15%
    Traffic before → after
    23.7 → 0.8 MB/s
    Move latency p95 before → after
    388 → 19 ms
  • 2,000

    CPU before → after
    overloaded → 17%
    Traffic before → after
    (choked) → 3 MB/s
    Move latency p95 before → after
    824 → 54 ms
  • 5,000

    CPU before → after
    not measurable → 32%
    Traffic before → after
    not measurable → 19 MB/s
    Move latency p95 before → after
    not measurable → 164 ms

Before, 1,000 people already made moves visibly slower and 2,000 was overload. Now 5,000 people still run on about a third of a core and 74 MB of RAM.

The fix isn't the end of the story. Each change is still sent to everyone, and more people means more changes, so traffic now grows faster than the number of people: 5 times the people (from 1,000 to 5,000) means about 24 times the traffic (from 0.8 to 19 MB/s). At 5,000 people, 19 MB/s is about 150 Mbit/s: the next limit will be bandwidth, not CPU. The next step, when needed, is to send the list only to people who have the lobby panel open. I wrote that down and stopped here, because the site is a long way from those numbers.

Round 4: home page HTML weighed down by 77 drawings

Before the fix

On the live site, after round 1, the home page HTML was 394 KB uncompressed. (In round 0 I measured 412 KB; the two measurements were a few hours apart and I didn't chase the difference.) I downloaded that HTML and broke down what it was made of:

Home page HTML from the live site; the compressed column is gzip, compressed on my machine

  • Game covers: SVG drawn straight into the HTML

    Uncompressed
    263 KB
    Compressed
    ~26 KB
  • Data for React (mostly UI translation strings)

    Uncompressed
    91 KB
    Compressed
    ~31 KB
  • Everything else

    Uncompressed
    ~40 KB
    Compressed
    ~8 KB
  • Total

    Uncompressed
    394 KB
    Compressed
    ~66 KB

Two thirds of the HTML was covers. Each game card has a small SVG drawing of its board. The home page has 77 cards for 67 games (some games appear in two sections, for example both in "New" and in the main list), and all 77 were drawn straight into the HTML, even the ones at the very bottom. The code that draws them (about 1,000 lines) was also in the downloaded JS.

What I changed

  • Each cover became a static file /covers/<id>.svg (67 files, about 3 KB each), generated at build time and served from the CDN.
  • Game cards use <img loading="lazy">: images below the fold only load when you scroll to them.
  • The cover-drawing code is no longer in the JS sent to the browser.

Two details worth noting. One: Next.js doesn't let route handlers use react-dom/server, so I wrote a small function that turns the SVG tree into a string. Two: an <img> can't use the page's fonts, so the SVG files declare system fonts; the text on the covers looks slightly different from before, but it's hard to notice at card size.

Checks

  • Compared each file with the SVG React was rendering on the live site: all 67 files identical.
  • On page load only 34 of the 77 images were fetched; none failed.

Result

Measured on the live site

  • Home page HTML, uncompressed

    Before
    394 KB
    After
    160 KB
  • Home page HTML, brotli

    Before
    60 KB (measured in round 0)
    After
    39 KB

On the local build, after the fix, the home page HTML is 143 KB uncompressed (40 KB gzipped), and the initial JS is 225 KB gzipped. I didn't measure the local build before the fix; the closest comparison is the live site's JS at the time, 237 KB.

The live site's HTML is larger than the local one (160 vs 143 KB), probably because the real popular-games data is bigger; I haven't verified this.

Something I only saw when checking production: right after a deploy, the first request for each cover took about 1 second because the CDN didn't have it yet, so the cards flashed grey boxes. I requested all 67 files once to warm the cache in the CDN region near me; the first visitor in another region may still see grey boxes once.

I left the React data (about 31 KB compressed) as it is: those are the translation strings the UI needs to run.

Round 5: splitting CSS per game

Before the fix

Every page had to load all of the site's CSS before it could show anything: 51 KB gzipped (measured on the local build), with the main file at 272 KB uncompressed. Most of it was game-specific CSS, in a single 12,800-line arcade.css. Someone opening the home page to play minesweeper still had to download the CSS for Senet.

What I changed

The games' code was already lazy-loaded per module. I made the CSS follow the same path: any rule used by only one module moves into a CSS file next to that module, imported by the module itself.

That sounds simple, but there's a trap: cascade order. In one CSS file, a later rule beats an earlier one of equal specificity. Once split, a game's CSS loads after the shared CSS, so it will win against rules it used to lose to. The UI can change without a single line of CSS being edited.

So instead of moving rules by hand, I wrote a script that classifies each rule:

  1. Build the import graph to know which files belong to only one module, and which classes only that file uses.
  2. A rule moves only if every selector in it (including each branch of a comma list and inside :is()) uses classes from exactly one module.
  3. Any rule whose outcome could change because of order (a later rule, same specificity, same property family, that could apply to the same element) stays in the shared file. About 310 rules stayed because of this.

Result: about 113 KB of rules moved into 21 small files, each loaded only when its game or dialog opens.

Checking: compare every property of every element

With 67 games, eyeballing isn't enough. I saved the bundled CSS from the old build, then for each game:

  1. Capture the computed style of every element on the page (including ::before and ::after).
  2. Swap the stylesheets for the old CSS, on that same DOM.
  3. Capture again and compare every property.

Before trusting a "0 differences" result, I ran a control: turn off one module's CSS file entirely and run again. The comparison immediately reported 13 differing elements (the board lost its colour). It catches real bugs.

Local build

  • Game in a window on the home page, desktop

    Games
    66
    Result
    all match
  • Game in a window on the home page, phone

    Games
    66
    Result
    all match
  • Game's own page, desktop

    Games
    23 representative games, chess puzzles, "hell" mode pipes
    Result
    all match
  • Game's own page, phone

    Games
    7 representative games
    Result
    all match
  • Feedback panel, support dialog

    Games
    —
    Result
    match

The 67th game is the chess puzzle, which has its own page and doesn't open in a window. For the own-page context, I only ran representative games for each module rather than all 67.

The comparison saved me, and also fooled me

I had to redo the split three times to get the final version.

First time: the comparison reported a margin difference on the xiangqi board. Hunting for the cause, I found two real holes in the classifier: it computed :is() specificity wrongly (counting every class in the list, while the CSS spec takes only the highest), and it could move a combined rule like .caro-board, .xiangqi-board { … } into the xiangqi module, leaving Caro behind. I fixed both and split again from scratch.

Second time: the comparison reported that the computer's piece border in Dōbutsu shogi changed colour, from plum red to bright red. This one was real. The original rule used border-top, a later rule used border-top-color; the script compared property names literally, so it didn't see the two rules collide. I changed it to compare by property family (border*, margin*, background*…) and split again.

Third time: xiangqi reported a margin difference again. This time I dug all the way down, and it turned out to be noise in the measurement itself: with the same CSS, the marginLeft the browser returned for that element still flipped between 0 and 301 px, while the board stayed perfectly centred on screen. So the signal in the first round was most likely this same noise. It led me to two real holes in the script, but it wasn't a UI bug itself.

Another false alarm: the crosshair in the darts game wobbles by itself in JavaScript between the two captures.

My takeaway: an automated check is valuable because it forces you to look for the cause, but each of its signals has to be verified like anything else.

Result

  • Render-blocking CSS on every page, gzipped (local build)

    Before
    51 KB
    After
    34 KB
  • Main CSS file, uncompressed (local build)

    Before
    272 KB
    After
    192 KB
  • Render-blocking CSS, brotli (live site)

    Before
    about 57 KB
    After
    38 KB

The saving is only about a third, because many early games (2048, sudoku, Caro…) were written straight into the main file, so their CSS is still in the shared part, plus the 310 rules kept back to be safe.

Round 6: dropping the redirect at the root

Before the fix

Visiting choichut.maitrinh.dev/ returned a 307 and only then moved on to /vi (or another language). Every first visit, and every launch of the installed app (PWA), paid an extra network round trip: I measured 0.2 to 0.9 seconds.

What I changed

For the exact path /, the proxy does an internal rewrite to the right language's page (by cookie, then Accept-Language, defaulting to Vietnamese). The URL in the browser stays /, with no redirect. Deeper paths like /play/caro still redirect as before.

This small change brought three things that had to be done together:

  • Caching. The same URL now returns different content to different people. The response at / must carry Cache-Control: private, no-cache, so no shared cache stores one person's Vietnamese page and serves it to an English reader. (I meant to add a Vary header too, but Next.js overwrites it on page responses.)
  • Invite links. /?room=… has to rewrite straight to the invite page, because I wasn't sure Vercel would handle a chain of two rewrites the same way my machine does.
  • Service worker. The installed app starts at /, while the service worker used to cache only /vi and /en for offline use.

Checks

Before the change, I reviewed everything that depends on the path. Two conclusions: browser-side code doesn't read the language from the URL, so nothing breaks; and SEO is safe, because the page at / still carries a canonical tag pointing to the page of the language it's showing (/vi, /en…).

After the change, I ran an AI code review: several independent passes, each from a different angle, and every finding had to survive an extra step that tried to disprove it. It found nothing wrong with routing, caching or SEO, but did point out two small bugs in the offline copy, both caused by my own change:

  1. Opening an invite link saved the invite page (titled "You're invited…") over the offline copy of the home page.
  2. After switching language, the offline copy of / was still in the old language.

I fixed both: visits with ?room= aren't cached, and whenever the home page of a language is cached, it's also written under the / key.

What worried me most was Vercel's CDN behaviour, which can't be tested locally. Right after deploying, I sent interleaved requests to / with different languages, in two rounds:

  • No headers

    Result (both rounds)
    Vietnamese
  • Accept-Language: en

    Result (both rounds)
    English
  • Japanese cookie, plus Accept-Language: en

    Result (both rounds)
    Japanese
  • Accept-Language: fr

    Result (both rounds)
    French
  • No headers, sent again right after

    Result (both rounds)
    still Vietnamese

Not once was the wrong language returned, and the content still came from the CDN cache of the matching language's page (x-vercel-cache: HIT).

Result

Measured on the live site

  • Visiting /

    Before
    307, then load /vi
    After
    200, the home page directly
  • Redirects recorded by the browser

    Before
    1
    After
    0
  • Extra time for the redirect

    Before
    0.2–0.9 seconds
    After
    gone
  • Invite link at /?…room=…

    Before
    redirect, then the invite page
    After
    straight to the invite page, right title

Summary: before and after

  • 1

    Problem
    Pages not cached
    Before
    always MISS; server responds in ~300 ms, ~2 seconds on a cold start
    After
    HIT; ~50–60 ms
    Measured where
    live site
  • 3

    Problem
    Lobby chokes when busy
    Before
    1,000 people use ~75% of a core, sending 23.7 MB/s
    After
    ~15%, 0.8 MB/s; 5,000 people still fine
    Measured where
    relay on my machine, CPU at one VPS core
  • 4

    Problem
    Heavy home page HTML
    Before
    60 KB brotli
    After
    39 KB
    Measured where
    live site
  • 5

    Problem
    Every game's CSS on every page
    Before
    ~57 KB brotli
    After
    38 KB
    Measured where
    live site
  • 6

    Problem
    Redirect at /
    Before
    an extra 0.2–0.9 seconds
    After
    gone
    Measured where
    live site

Round 2 changed nothing; it was the measuring round that showed what round 3 had to do.

So what about Rust?

I went back to the reasons at the start of the post, this time with numbers:

  • "Uses less RAM": RAM was never the limit. 10,000 connections take 104 MB.
  • "Makes better use of a weak CPU": maybe, but what ate the CPU was resending the whole list to everyone. Fixing how it's sent cut CPU 5 times at 1,000 people and traffic about 30 times. I didn't write a Rust version, so I can't say how much CPU it would save; but changing language can't cut traffic, because the same bytes still have to be sent.
  • And the hidden assumption behind all of it, "a faster server means a faster website": the website never ran on the VPS.

Rust is still a good option when the relay is truly limited by how fast it handles each message, for example once the number of tables goes past what one VPS core can handle (about 4,000) and I don't want to split across machines. That day is far off, and when it comes, I already have a load test script to tell me whether a rewrite is worth it.

A checklist for a small site that's "fine"

  1. Read the cache header (x-vercel-cache or your provider's equivalent). If a page that's nearly the same for everyone still says MISS, something is blocking the cache.
  2. Measure TTFB on the first visit and later ones. A big gap is a sign of cold starts.
  3. Look for what forces dynamic rendering: nonces, headers(), cookies(), searchParams, Math.random() or Date.now() at render time.
  4. Look at HTML size, not just JS, and break down what it's made of.
  5. Know where the code actually runs: the website, the API and the realtime server may live in completely different places.
  6. Load test before changing technology, and don't fire load at a machine that's serving real users. A copy throttled to the real machine's speed is enough to find the bottleneck.
  7. Doubt your tools too. Docker's CPU limit, a value returned by the browser, an animation running on its own: all three gave me false signals in a single day.
  8. Look for "resend everything to everyone whenever anything changes". It works great with 10 people.
  9. Every time you loosen a security setting, write down what you gain and what you lose.
  10. Check the live site again after every deploy. Two bugs in this post (the invite button not opening the lobby, grey boxes while the CDN was cold) only showed up there.

Wrapping up

Before measuring, I was going to rewrite the server in Rust to make the most of the VPS. After measuring, I found the VPS had nothing to do with the slow pages: the main culprit was a nonce-based CSP, along with a few other things forcing dynamic rendering, so no page was ever cached. And when I measured that server itself, the bottleneck wasn't the language either, but a loop that sent the whole list to everyone.

Six rounds, and none of them needed a change of technology. Every one of them started with a number.

"It's fine" usually just means nobody has measured it yet.
  • Next.js
  • CDN cache
  • CSP
  • WebSocket
  • Load test
  • Measurement