Building asynchronous play on Cloudflare's free tier
A Wizard-Chess Tournament got asynchronous play this week. You make your move, close the game, and come back when your opponent has answered, which might be ten minutes later or two days later. The game is built in Godot 4, and the server side is a small TypeScript relay on Cloudflare Workers. Here's how it fits together and the problems I ran into while building it.
The server doesn't know the rules
The game's engine is deterministic: the same starting seed and the same list of actions give the same game on every machine. Live online play already relies on that. Both players run the full game, and after each turn they compare a hash of the game state.
That meant the async server could be a delayed proxy. It stores each turn as a message it never opens, passes it on to the other player, keeps the move clock, sends the "your turn" notification and enforces limits. When a turn arrives, the other player's client rebuilds the match from every turn so far, using the same engine code that plays back replays, and checks the hash the sender included. If the hashes don't match, the match is void.
Because the server never runs the rules, I didn't have to port anything to TypeScript, and there's no second copy of the rules that could drift out of step with the game. A new card or a balance change doesn't touch the server at all, and storing a few kilobytes per turn costs almost no CPU. The price is that the server can't stop a modified client from sending an illegal move. The opponent's client catches it on replay and the match ends, which is acceptable for an unranked mode. A ranked async ladder would need the server to record results itself, so that's left for later.
All of this depends on the game being deterministic. A game that can't replay a match exactly would need a server that runs the rules, which is a much bigger and more expensive thing to build.
Lots of small objects instead of one server
I looked at a few other ways to host it first:
- A normal always-on server with a database. I know how to run one, but it costs money every month whether anyone plays or not, it needs patching, and something has to keep scanning the database for move clocks that have run out.
- Serverless functions with a key-value store. That's cheap, but two players accepting the same open challenge at the same moment would race each other, and there are no timers.
- Plain storage, like a cloud bucket or Steam Cloud. Writes still need authentication, which means a server anyway, and Steam Cloud is per account, so it can't pass a move from one player to another.
I went with Cloudflare Durable Objects, which I'd only read up on a little while before. I watched a video by ThePrimeagen about Cloudflare buying Deno, and that sent me off to find out what Durable Objects actually were. Once I understood them, they looked like a good fit for correspondence games.
A Durable Object is a small piece of code with its own storage, reached by name. The platform starts it when a request comes in and lets it sleep when nothing is happening. The relay uses three kinds: one object per match, one per player, and a single lobby that lists open challenges.
A match turned out to be a good unit to build around. Its object owns the turns, the clock and both seats, and since it handles requests one at a time, only one of two players racing for the same open challenge gets it. Each object can also set an alarm, so a match sets one for its move deadline, and when it fires the side to move loses on time. Nothing has to scan every match. Correspondence games sit idle most of the time, and an idle object doesn't cost anything, which is why the free tier is enough. There's also no machine for me to look after.
The whole relay runs locally with Cloudflare's tools too, so the Godot client talked to a server on my laptop long before anything was deployed, and the tests run in the real Workers runtime with alarms included. That local setup also answers the usual worry about building on one vendor. The runtime underneath Workers, workerd, is open source and runs Durable Objects itself, so if I ever need to leave Cloudflare, the same objects can run on a server of my own. I'd lose the free hosting and have to replace a few Cloudflare-only extras, like the request rate limits, but the relay's code wouldn't need a rewrite.
Before writing the real relay I spent a day on a throwaway prototype that tried the risky platform pieces end to end: checking a Steam login on the server, a Steam stat that only the server can write, Steam notifications reaching an offline player, and alarms on the free tier. Everything worked, and that's what settled the choice of Durable Objects. It also turned up a few Steam surprises early, which I'll get to below.
Staying inside the free tier
Cloudflare's free plan has daily limits on requests and storage writes. Once a limit is used up, further requests fail until the next day, and nothing is charged. Most of the cost work went into keeping well inside those limits.
The biggest decision was to keep only what's in flight on the server. The demo allows three async games, and the counter for that is a Steam stat that only the server can set and that can never go down. Finished games are saved as replays on each player's own machine. A player object with nothing open for 30 days deletes itself and is rebuilt from Steam if that player comes back, and a finished match deletes itself a few days after it ends.
Each turn carries a full snapshot of the board, about 16 KB, so that a player on a newer version of the game can restart the match from it. The server only needs the most recent one, so it drops the previous snapshot whenever a new turn arrives from the same game version. A 100-turn match ends up at about 20-30 KB instead of 1.6 MB.
The menus ask the server for news every three minutes, and an open async match checks every 15 seconds, asking only for the turns it doesn't have yet. Neither runs while you're in another game. The first version of the relay saved a "last seen" time on every one of those checks, which would have spent the daily write budget on reads. Now it only saves when something changed or the stamp is a day old. Steam notifications tell players when it's their turn, so nobody needs to leave the game open to find out.
There's a limit on everything else as well: logins per IP address, requests per player, open games, challenges per day, the size of a turn and of a whole match, and one notification per match per minute. The login limit is there because every login costs a call to Steam's Web API on my publisher key, and that key's daily quota is shared by every player. A flood of logins could use it up for everyone.
Problems I ran into
Game updates in the middle of a match
A live match lasts twenty minutes, but an async one can run for a week and span several patches. Every turn carries a version key built from the save format, the rules version and a fingerprint of the card data. A client on a newer version restarts the match from the latest board snapshot and carries on under the new rules, while a client on an older version asks the player to update. Each build ships the list of every released version key, because a release missing from that list would make every later build refuse its matches. The publish script won't upload a build whose key isn't in the list. I had to put this in place before the first public match, since changing it afterwards would break every game in progress.
Refusing a move can strand the opponent
With a move clock, a refused move hurts more than the player who sent it. The first version of the relay refused any turn that pushed a match past its size limit. That left the player stuck on their move until they lost on time, and a player could pad their own turns to push the match towards the limit just before it was the opponent's move. Now a match that reaches the limit ends as void, and nobody loses.
Side effects that fail halfway
One turn touches the match, both players' match lists, the lobby, a Steam notification and sometimes a Steam stat. Any of those calls can fail, and a deploy can restart an object between two of them. During testing, a "your turn" notification after an accepted challenge went missing that way, because one code path forgot to save the note that it was still owed. Now the match writes down everything it still owes in the same save as the move, and its alarm retries each step, waiting a little longer each time, until it goes through. A failed notification never undoes a valid move.
One request at a time, mostly
A Durable Object handles one request at a time, but only while it's working with its own storage. While it waits on an outside call, like Steam's Web API or another object, other requests can run. So reading a value, calling Steam and then writing the value back can wipe out a change made in between. Every method that changes state now runs under an explicit lock, and the objects always call each other in the same direction, so two of them can never end up waiting on each other. There's a second trap in the platform's lock: an error thrown inside it resets the whole object, so my lock helper catches errors inside and rethrows them outside.
Counting each game once
The demo's three-game limit counts a game when it starts. Creating a challenge holds a slot, and a decline or an expiry gives it back. If a request crashes and leaves a hold behind, the hold expires after six hours. If the step that counts a started game is lost, the match retries it, since a lost count would be a free game.
Challenges from strangers
Anyone can challenge any Steam account. Challenges other people send you don't count against your own limit of open games, so nobody can lock you out by sending invites, and there's a cap on how many can be waiting for one player. Creating challenges is limited per day too, because cancelling and re-creating one in a loop would otherwise send a stream of notifications.
Steam's quirks
Players opt in to game notifications through the Steam overlay the next time the game runs. The notification texts are uploaded per app on the partner site, and without them Steam shows a generic "New turn waiting". Steam chat invites to a game that isn't running show a "launch with custom arguments" warning, and Steam only keeps the latest invite from each sender. So the notification is the main way a challenge reaches you, the chat invite is an extra, and every challenge can also be found inside the game.
Asynchronous play is in the free demo of A Wizard-Chess Tournament on Steam, with three games to try it and no limit in the full version. If you're working on something similar and have questions, you can find me on Discord: https://discord.gg/bqhP4WK8rW