Lessons from DND AI: keeping a party together over Socket.IO when connections drop, budgeting tokens, and charging for credits on the server.
DND AI is a Dungeons & Dragons-style game where an AI Game Master narrates the story from players' choices. Several people play together in a room, so the product has two hard parts: real-time state, and an AI that costs money every time it speaks.
Rooms that survive bad connections
Players close laptops and lose signal. With Socket.IO each game is a room, and the part that matters is what happens next:
- Join adds a player and sends them the current game state.
- Disconnect is handled explicitly instead of treated as leaving, so the party survives.
- Rejoin puts a returning player back into the game they were in.
Treating a dropped connection as normal makes the game feel stable.
Keep the rules on the server
Game logic and AI calls live in the Express API, not in the browser. That keeps every player's screen consistent and keeps API keys and billing out of reach of a modified client.
Budgeting tokens
A long campaign eventually outgrows the model's context window. Token budgeting with tiktoken means counting before sending, which beats finding out from an error or a surprise bill.
Narration and art
The Game Master's lines can be read aloud with Google Cloud Text-to-Speech, and character and scene images are generated, processed with sharp and stored on S3.
Credits enforced in middleware
AI generation has a real cost, so usage is credit-based with Stripe. The important detail is where it's enforced: in API middleware on the server, before a generation runs. A button that is merely greyed out in the UI protects nothing.
Takeaways
- Design for disconnects first.
- Keep the server authoritative.
- Count tokens before you send.
- Enforce billing where the cost is incurred.