Our game clock does not live in the app, because a serverless function cannot hold a timer for fifteen seconds
A pub quiz is a sequence of deadlines. A question opens, a window of a few seconds runs, the window closes whether or not anyone answered, and after a pause the next question opens on its own. Nothing about that is interesting until you ask which process is holding the stopwatch. For a while, ours was partly inside the Next.js route that closes a question: the route closed it, then slept, then…
A pub quiz is a series of timed tasks. Each question has a short window for answering, then it closes automatically, regardless of whether anyone answered correctly. The process of opening and closing questions is handled by a server-side function. However, this approach has a flaw - serverless functions can be frozen after sending a response, making sleep commands unreliable.
This led to two issues: timers advancing independent of session mode, and timers persisting across deploys, causing questions to remain open indefinitely.
To address this, the server-side function takes charge of timer management. Three timers handle different tasks: closing questions, advancing questions, and sending the final leaderboard. A timer is essentially a cached calculation based on the question launch time, window duration, and grace period. The server re-calculates these timers every three seconds by querying the database, ensuring timers remain accurate and up-to-date.
This approach allows the server to handle timer management, eliminating the risks associated with in-memory timers. When a deploy occurs, the old process clears its timers, closes connections, and restarts. The new process, after reconnecting, takes three seconds to re-establish timers from the database, ensuring a seamless transition for players.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.