Skip to content
All writing

Offline-first leaderboards: grade on the server, not the phone

An offline-first quiz marks answers on the phone, so the phone always knows the score. Letting it report that score is how a leaderboard gets forged. Here is the scoring that holds when the client can't be trusted.

Quiz Slayer marks every answer on the phone, offline, the moment you press a key. That's the point of the app, and it means the phone always knows your score before any server does.

So the first leaderboard I wrote just asked the phone. A finished round sent lists of the question ids it had marked right and wrong, and the server did the arithmetic.

// The first version: the client reports its own result.
recordAttempt({ deviceId, correctIds, wrongIds, optionsCount, answers, timeTaken })

Anyone with the browser console open could send every correct id in the bank. Worse, nobody even had to cheat. Replaying the same ten questions you already knew paid out every time, so the top spot went to whoever repeated the easiest round most. That measures stamina, not knowledge.

Send answers, not scores

The fix moves the marking, not the trust. The phone still marks locally, because instant feedback is the product. But what it sends is raw: which option was picked for which question id. The server keeps its own copy of the answer keys, pushed from the build by a script behind an admin key, and grades from that.

How a finished round reaches the leaderboard

A sequence between the phone and the Convex backend. Step 1: the phone marks each answer at once, offline. Step 2: the finished round is queued in an IndexedDB outbox with its own attemptId, the question ids and the raw answers. The outbox waits for a connection. Step 3: it calls recordAttempt with the queued arguments, plus the player's secret when the player is anonymous (a signed-in player's session says who it is). Step 4: the server checks whether it has seen this attemptId; if so it returns the earlier result and adds no points. Step 5: it grades the answers with its own key: a question answered right for the first time earns 1, right again earns 0, wrong costs 1 divided by the number of options minus one. Step 6: it returns ranked and points. On success the phone deletes the item from the outbox; on a ConvexError it drops it; on a network error it keeps it and retries.

PhoneConvex123456Marked on the phoneQueued in the outboxSeen this attemptId?Grade with the server keyinstant feedback, offlineattemptId: "3f9c1a…"questionIds + answerswaits for a connectionrecordAttempt({ …args, secret? })yes → earlier result, +0first time right+1right again0wrong−1/(n−1){ ranked, points }ok → delete from outboxConvexError → drop itnetwork error → keep, retry
How a finished round reaches the leaderboard

Step 1: the phone marks each answer at once, offline. Step 2: the round is queued in an IndexedDB outbox with an attemptId, the question ids and the answers, until there is a connection. Step 3: the phone calls recordAttempt with those arguments, plus its secret if the player is anonymous. Step 4: Convex checks for the attemptId and returns the earlier result if it has one. Step 5: it grades with its own key, plus one for a first correct answer, nothing for a repeat, minus one over options minus one for a wrong one. Step 6: it returns ranked and points. The outbox then deletes the item on success, drops it on a ConvexError and keeps it to retry on a network error.

123456Marked at once, offline, explainedSeen this attemptId?PHONEPHONE · INDEXEDDB OUTBOXquestionIds + answersuntil onlinePHONE → CONVEXCONVEXyes → earlier result, +0CONVEX · GRADE WITH ITS KEYfirst time rightright again0wrongCONVEX → PHONEPHONE · OUTBOXnetwork error → keep, retryattemptId: "3f9c1a…"recordAttempt({ …args, secret? }){ ranked, points }+1ok → delete from outbox−1/(n−1)ConvexError → drop it

The phone only ever sends evidence. Points are decided at step 5, from the server's own copy of the key, and step 4 makes sending the same round twice harmless.

Score what can only be earned once

Server grading stops a forged list. It doesn't stop replays, because replayed answers are real answers. So a correct answer earns a point only the first time this player gets that question right. The server writes one row per player per question, and the next time the row is already there and the answer earns nothing.

Wrong answers go the other way, every time. Each costs 1/(n−1) of a point on a question with n options. With four options a blind guess wins a point a quarter of the time and loses a third three quarters of the time, which comes to exactly zero. Guessing can't climb the board. The server adds points up in units of 1/2520 of a point, because every penalty from 1/1 to 1/9 is a whole number of those. So a total never depends on rounding, or on how the answers were split across rounds.

for (const [i, id] of questionIds.entries()) {
  const q = key.get(id)
  const answer = answers[i]
  if (answer === null || !q || seen.has(id)) continue // unanswered, unknown, repeated
  seen.add(id)
 
  if (answer === q.correctIndex) {
    // Inserts the (player, question) row; false when it was already there.
    if (await masterOnce(playerId, id)) points += 1
  } else {
    points -= 1 / (q.optionsCount - 1)
  }
}

Make the outbox safe to resend

Offline-first means the round finishes long before the request does. Finished attempts go into an IndexedDB outbox and leave when a connection exists, on app start and on every online event. A request can land and its response get lost, so the outbox will sometimes resend a round the server already counted. Each attempt carries a random id minted when it's queued, and the server looks for it before grading. A match returns the earlier result instead of grading twice, and only to the player who sent it.

The outbox also has to tell two failures apart. A ConvexError means the server read the attempt and refused it, so resending can never succeed and the item is dropped. Anything else is the network, or the server saying "not now" (too many rounds in a minute, an account still being set up), and the item stays. It goes out again in a minute, or when the connection comes back.

Know whose round it is

Google sign-in came later, and it made the outbox harder. A round can be queued as an anonymous player and still be waiting when that device signs in, signs out or switches accounts. Sent as whoever is signed in at that moment, it would credit the wrong player.

So every queued round is tagged with the identity that played it, and a flush sends only the rounds that belong to the current one. The rest wait. The server checks too: a round finished before the account's player was deleted and started again is a ConvexError, so the phone drops it instead of crediting the new player.

The tradeoff

The keys still ship inside the app. Offline marking needs them, so a determined student can read every correct answer from the bundle. I chose that over losing instant feedback, which is the reason anyone opens the app.

What the scoring does is cap the damage. Reading the key gets you one point per question, once, which is exactly what learning the answer gets you. Nobody appears on the board until they've answered 20 questions, so a single lucky round doesn't count either. On a web build with a public number on it, this is the question I ask first: what does the client know, and what is it allowed to claim?

The takeaway

If the client has to know the answer, don't let it tell you the score. Send the evidence, grade it where your copy of the key lives, and make the reward something that can only be collected once.