A real-time game needs more than a browser that can draw a puck. Two players must be authenticated, matched, assigned sides, and kept in sync even when their network connections behave differently. A match also needs a clear ending, a record for history, and a deployment that supports WebSocket connections.
This guide starts with one two-player air hockey match and grows it into a full-stack application. It uses NETPONG as a source-code reference while describing a design you can build and test independently.
Why NestJS fits this application
NestJS gives the HTTP API, the WebSocket gateway, and the game service explicit places to live. A controller handles HTTP requests, a gateway receives or sends socket events, and an injectable service owns application logic. Modules declare which providers they own and which dependencies they import. The main benefit is that game rules can be tested through a service without needing a real socket or browser. NestJS modules · NestJS providers · NestJS gateways
The NETPONG backend is organized around features. The root module assembles authentication, users, chat, game, email, health, and metrics, alongside configuration and the PostgreSQL connection. The game module registers its controller, gateway, and service. It imports the user and metrics modules and registers the match entity with TypeORM. This example shows the shape of the code to look for. The filenames are representative, with the supporting modules shortened for readability.
src/ main.ts Application bootstrap and shared middleware app.module.ts Root module and infrastructure wiring auth/ Sign-in, tokens, and authentication guards user/ Profiles, friends, blocking, search, and statistics chat/ Chat gateway, conversation service, and message model game/ game.module.ts Feature dependencies and providers game.controller.ts HTTP endpoints for game records and statistics game.gateway.ts Socket events and delivery game.service.ts Matchmaking, sessions, and simulation entities/ Persisted match records dto/ Event payload definitions email/ Email delivery support health/ Health endpoints metrics/ Application counters and gauges Use that structure to decide where code goes. An HTTP endpoint for match history belongs in the controller. The gateway handles a movement message and obtains the authenticated identity. The service decides whether the player belongs to the match and updates the game state. A database repository persists the result. When a gateway starts carrying the scoring rules, it becomes difficult to test the game without also testing Socket.IO. NETPONG root module · NETPONG game module
Authenticate the connection and validate its events
Start with accounts and sign-in. Store password hashes with a dedicated password-hashing algorithm. For socket connections, authenticate the handshake, then associate the connection with a stable user ID. A socket ID identifies the current connection and may change when the browser reconnects. Use the authenticated user ID for ownership and the socket or room membership for delivery. OWASP Password Storage Cheat Sheet · Socket.IO server socket instance
Validate a socket event at the transport boundary and authorize it at the feature boundary. A movement message needs finite numeric coordinates. Its sender also needs to belong to the active match and control one paddle in it. Test both conditions. A valid payload by itself does not imply that the user is allowed to act on a particular match. Nest gateways support pipes, so a DTO and a WebSocket-aware validation path can make malformed payloads fail before they reach the simulation. NestJS WebSocket pipes · NestJS WebSocket guards
Match two players before starting the game
Keep a queue per mode. When two eligible players are waiting, take them out of the queue and create one match record in memory with a match ID, the two user IDs, their sides, and an initial state. A player should belong to at most one queue or active match at a time. Make repeated queue requests safe, since a retry or double click can send the same intent twice.
Give the match a readiness phase. Notify both clients that a match was found, and wait for each to finish loading and signal ready. Define what happens if either player leaves before it starts. A practical policy is to expire the invitation and let the remaining player rejoin the queue. Choose a separate policy for a disconnect in the middle of a match, such as a short reconnection window followed by a forfeit.
Both clients -> join the same mode queue Server -> assigns one match ID and a side to each player Both clients -> signal readiness after loading Server -> runs the match and broadcasts state Clients -> send input and render received state Server -> ends the match, publishes the result, saves history Socket.IO rooms are an easy way to send state to members of a match. Join the room on the server after checking membership. NETPONG’s example delivers match state directly to the two current socket IDs. Either approach can work in a single server process. A Socket.IO room groups recipients. The match state and its rules still belong to the game service. Socket.IO rooms · NETPONG game gateway
Keep the simulation authoritative
Clients send input. The server owns paddle positions, puck motion, collisions, scoring, and the winner. In air hockey, one client message can set a target position. At each simulation step, clamp that target to the player’s side and move the actual paddle toward it by a bounded distance. Apply the same rules regardless of how often a browser sends messages. This makes scoring decisions consistent across the two clients and gives the simulation a small set of rules to test.
Run simulation on a deliberate tick schedule and measure elapsed time or use a fixed-step accumulator. Browser rendering and server simulation are separate clocks. Limit catch-up work after a stall so one slow event-loop turn does not produce an unbounded amount of work on the next turn. Start by sending snapshots with a match ID, sequence or tick number, positions, and score. Measure payload size and latency before adding delta compression. NETPONG game service
On the client, keep the latest snapshot outside the React render path if updates are frequent. Use a draw loop to render on a canvas with requestAnimationFrame(). Convert pointer coordinates to the same logical space on every screen size. Once a basic client works, experiment with interpolation between buffered snapshots and measure the visual smoothness against the extra display delay. Keep buttons, text, and match results in normal UI components. MDN requestAnimationFrame
Design reconnection and match history as separate paths
Socket.IO preserves message order, and its default delivery guarantee is at most once. A disconnected client can miss events. On reconnection, authenticate the user again, check the match membership, and provide a current snapshot. A client should be able to resume from that snapshot even if it missed several movement or score messages. Socket.IO offers connection state recovery where supported, but the application still needs a recovery path for cases where it cannot restore the session. Socket.IO delivery guarantees · Socket.IO connection state recovery
Use PostgreSQL for durable data such as account identities, match results, and chat history. Keep per-frame state in memory while you build the first working server. Assign each match a unique ID. Write the result and any related statistics in a transaction if they must succeed together, and protect the match ID with a unique constraint so retrying the finish operation cannot create a second result. Once that write succeeds, a history endpoint can return the result even after the socket disconnects. PostgreSQL transactions · PostgreSQL constraints
Deploy and verify the complete path
Package the frontend, backend, and database in a Compose setup with documented environment variables. Keep actual credentials outside Git. Test the deployed page over HTTPS so you can verify secure WebSocket traffic through the same route real users take. If you use a reverse proxy, check that the Socket.IO path, WebSocket upgrade handling, and timeouts match the app. A working API endpoint alone does not prove that the socket path is working. Docker Compose services · Socket.IO reverse proxy guide
- Build one arena and confirm that puck collisions, scoring, and movement bounds work in isolated tests.
- Connect two separate browsers. Confirm that they receive the same match ID, different sides, and the same final score.
- Click join twice, let readiness time out, and disconnect during a match. Check that each event leaves the queue and match in a consistent state.
- Reconnect a player and confirm that the new socket can resume from a snapshot. Finish a match twice in a test and verify that history contains one result.
- Repeat the flow through the deployed proxy with two clients on different devices. Use application logs and metrics to tell connection failures apart from matchmaking, simulation, or persistence failures.
Once this path is stable, add the surrounding features one at a time. Chat needs its own rules for who can see and send messages. Friend lists and presence should agree on who is online. A practice opponent can use the same paddle-input interface as a human player. New arenas can change visual rendering while keeping the same protocol. These features are easier to add when the backend already has clear boundaries.
The full NETPONG source gives readers a concrete example to trace from the root module to the gateway, service, database, and browser.