Why Is Building a Multiplayer Game So Hard and What Can We Do to Fix It for Everyone

Rate this content
Bookmark
Making casual games has become easier than ever but setting up multiplayer still requires you to write network code, deal with websockets, load-balancing servers, co-locating servers and whatnot. 
I am building Playroom to solve this, a high-performance sync that handles the networking and the room management so you can focus on building your game.
18 min
28 Sep, 2023

Video Summary and Transcription

Asad Nehman discusses the challenges of making multiplayer games and suggests ways to simplify the process. He highlights the need for a backend, such as a Node.js server with Socket.io, to handle player connections. Rooms are introduced to connect players and their friends, allowing communication within each room. Hosting options like AWS EC2, Vercel, and Netlify can help scale the game globally. Playroom framework eliminates the need for server code, lobby systems, and managing player profiles.

Available in Español

1. Introduction to Making Multiplayer Games

Short description:

Asad Nehman discusses the challenges of making multiplayer games and suggests ways to simplify the process. He highlights the need for a backend, such as a Node.js server with Socket.io, to handle player connections. Rooms are introduced to connect players and their friends, allowing communication within each room. Room codes are used as unique channel IDs for communication, including player state and position. A lobby UI is necessary to share room codes, allowing players to join the same room. Customization options, such as avatars and colors, help differentiate between players.

Hi everyone, this is Asad Nehman. I'm going to talk about why it's so hard to make multiplayer games and what can we do to make it easier? So a little bit of what I mean. I am a developer. I make things. Specifically, I like to make developer tools and I have been doing so for 10 plus years. I also started an online IDE company in the past. I also like to play multiplayer games with my friends. So naturally I like to make multiplayer games.

So let's say I want to make a multiplayer game. Let's start with the most simple multiplayer game and see what challenges do we face. So the first thing you probably want to do is get a base single-player game, which you will then convert to a multiplayer game. This base game will probably have some game loop with them, and the multiplayer parts can be you adding more players into it and some logic around it, some competitions and stuff. And the first thing you would probably do to convert this into a multiplayer game is to add a backend to it. And in the context of web games, this is usually a Node.js server with some kind of a web socket framework like Socket.io. So what you probably want to do is handle the player connections and store those players in some global array inside your Node.js app, and then that way all the players can connect with each other using this web socket backend and this works.

But you soon realize that you also need to have some concept of Rooms in your game, in your server. So what the Rooms would do is, you would assign some room code to some players and what this allows you to do is connect each player and their friends with each other. So all of the players in all your games are not in the same room. They are in their own rooms and then rooms can start and end at their own times depending on when they start their games. So it sounds like these two players are in their own rooms and these two players are in their own rooms and they can only communicate within their own rooms. They cannot communicate with the players in other rooms. Simple enough. And yeah. So they can use this room code as a unique channel id through which they can communicate with each other. The communication can be player state and player position, scores, all that stuff.

Now, you need... Once you introduce room codes, you need a way to share these room codes with other players. So this can be some kind of a lobby UI that you need to make. So the lobby UI can be the host can start the game, they can share the room code, room link, QR code with other players, and that QR code or room link will have the room ID embedded into it, and when the other player opens this URL, they're automatically connected to the same room, and that way they can communicate with each other. You also need some way, some UI to add, you also need some kind of UI to add, allow players to pick their avatars, their colors, their names, so that to have some customization, and so that they can differentiate between the players.

2. Broadcasting Game State and Deploying Servers

Short description:

Once you have the game state broadcasting and synchronization in place, you need to deploy your game. Hosting options like AWS EC2, Vercel, and Netlify can help you scale your game globally. However, a challenge arises when your servers are isolated, and players connected to different servers can't interact. To solve this, you need to connect the servers to a central database like Redis, and deploy them across the world for low latency.

Yeah, and once you have that, you make your game. Your game is essentially, you broadcast your game state to the players, and the players broadcast their own state to the other players, and your job as a game maker is to combine those states, updates, and consume them, save them locally.

So as an example, one player can move and share the position to the WebSocket server, and the other players can read that position and update the player on their own screen, and vice versa. So essentially what you're doing is you're maintaining these global, your own global variables, which you want to sync across all the players in your own.

And most of the net code involved would be to make sure that these states are synced. Once you have that, you have a simple game. Now, you can't just share this game without deploying it somewhere. To deploy it, you need some place to host this game. This can be AWS EC2 instance, which I would recommend. You can use some service like Vercel, Netlify, and what they can do is host your game, scale your game across the world, have multiple instances running of your game based on the traffic coming to your game and once that happens, you realize the main problem here.

3. Connecting Servers and Using Alternative Solutions

Short description:

Your servers are isolated, but you can connect them to a central database like Redis to synchronize room states and player lists. Deploying servers and database replicas across the world ensures low latency for players. Instead of managing clusters and databases, consider using alternative solutions like Unity's Photon or netcode, or game server hosting services like Hathora, Revit, and Snapser. Firebase can also be used as a back-end for simple and non-arcade games. Additionally, peer-to-peer connections need to be implemented.

The problem is your servers are isolated. So let's say I'm connected to server A here and I use some room code to connect to the server and I share that room code with my other friend who is connected to server B. And they try to use the same room code but they don't see me. That's because server A and B are not interconnected with each other. So the state they hold, well the room states, the list of rooms they hold, is not the same because they are running on a completely separate process across the world.

And to solve this, what you need is to essentially connect them to a central database, maybe. So let's say you connect them to a database. So Redis is a good back end to do this. So the Redis can act as the back end of the back end, which then stores all the rooms and the states and the player lists and everything. And all these servers just sync with that central database, Redis in this case. But you also need to deploy this server and database pair across the world because your users can connect from far away and they shouldn't see lag in their game. So what do you want is deploy servers close to them and you also want to deploy the database replica close to them. So they do not see lag. And you start with developing a game but now you are managing your cluster and databases. That's not what you want to do. And every game developer faces a version of this when making multiplayer games. That's a lot of duplicate work. They don't want to manage all these servers. They just want to make the game.

Fortunately there are some better alternatives to just writing your own server. For example, Unity has Photon or netcode for game objects. There are services like Hathora, Revit, Snapser which host a game server for you. So you just give them the server code and they host it for you. You can also use Firebase as a back-end for games. This can be useful for simple games, non-arcade games and party games. These options are great. They are at least better than what we talked about before. But you still have to write a ton of non-game code and back-end server code. We also should talk about some other non-game code that you will probably need to do. Which is to figure out peer-to-peer connections.

4. Simplifying Game Setup with Playroom

Short description:

Direct player-to-player messaging reduces latency in fast-paced games. Client-side prediction ensures smooth player movement during updates. Game studios spend excessive time and cost on non-game code. The Playroom framework eliminates the need for server code, lobby systems, and managing player profiles. It provides a global variable for syncing room state across all players. Playroom simplifies game setup, including lobby connections and player invitations. Game logic handles player joining, leaving, and game state updates automatically.

So the messages are not routed to a server, instead sent directly to the other player, which reduces the latency for you. This is absolutely required for fast-paced games. You also probably want to add Gamepad support so that players can play it locally, split-screen or on the TV. You also want to do some kind of client-side prediction for player movements. Because while this update, for example, for a position is being sent to that player, that player shouldn't be stuck in space. They should see some kind of prediction happening. So the player is smoothly moving to the next step.

So, we talked to some game studios about their feedback on what the current infrastructure provides and how they feel about it. And we saw a common pattern that they are spending a ton of time and cost on making these multiplayer games. And yeah, it shouldn't be like this. It should be like this. So, let's rethink what it would look like if you didn't have to deal with any of the non-game code in your games. That would mean just not writing any server code at all. And yeah, you also don't want to write your own lobby system and UIs and managing player profiles and all that stuff. What if you just call one function and it just gives you the player list in this current room and just starts a game with that player list. And you don't have to worry about all the lobby connections, QR codes, room state, what is the room state that you want to sync across. It is just a global variable which you can just set and get from and it will automatically sync across all the players in this room, so you don't have to worry about how to get this state from device A to device B.

So for example I set state SCORE3 on device A on player A, and then I can just try to get the score on other device and get the updated state here. So that's the premise behind the framework called Playroom which I'm working on. Yeah let's see how it works. So first of all to use Playroom what you want to do is npm install playroom-get and after you do that you call this init() function that we call insertCoin. This tells Playroom to start, this tells Playroom to start the lobby system so it shows the lobby UI and from there it automatically handles all the creation, joining, player profiles and players picking their own colors and avatars and all that stuff. How? Let's see. So when you call insertCoin, the player sees this fullScreen UI which we call the lobby UI and players can, as I said, pick their avatars and colors and everything and they can also invite other players so they can share the link to your game with that unique URL or just the other player can just scan this QR code to join the same room. And the next step you want to do is write a game logic for players joining the game and players leaving the game. So, for example, when a player joins the game you probably want to add some sprite for them on the scene and when they quit you want to remove that sprite from the scene. And that's the player joining and leaving the game. The other thing you want to handle is the game state itself. So let's say you want to take some input, do some calculation and update the player position and once you do that the other players will automatically see that new position and update the player position on your screen. And this happens automatically.

5. Playroom Backend and Role Lifecycle

Short description:

You can easily set and get positions, player input, health, score, winner, and leaderboards using Playroom functions without writing any server code. Playroom relies on Cloud Play and DurableObjects for its backend, providing low-latency storage worldwide. The lifecycle of a role involves creating a new room for the first player, connecting other players through a unique URL, and managing the game state. Playroom maintains two types of connections: a reliable TCP socket through Playroom edge servers and an unreliable UDP or WebRTC connection between players. The latter is suitable for states like player positions.

You just have to set and get positions from the playroom functions and this is true for player positions, input, health, score, who is the winner, the leaderboards and all that stuff. And again you never wrote any server code for this, you just npm install this and initiate it in the playroom and then you are setting and getting the state. That's it.

So how does this work behind the scenes? So I guess the biggest secret sauce here is Cloud Play and DurableObjects. So Cloud Play has this added nodes across the world and they probably have added nodes within your ISP. So these are usually 50ms from you, latency wise. And the other thing is DurableObjects which is like a storage system that Cloud Play provides which lets you have consistent and low latency storage anywhere in the world. Yeah, that's like the backend for Playroom.

And let's go over the life cycle of a role I guess. So when the first player starts a game and the game calls insert coin, what the Playroom does is show the CRM for lobby and profile and everything. And behind the scenes, Playroom creates a new room for them. And they're connected to this room. And when they share this unique URL with them, with other players, they also join into the same room. And then when the host clicks the start, you just un-save room. And the Playroom manages the state.

And that's not all Playroom does. Playroom also provides a secondary connection for you. So, Playroom maintains two types of connections for you. One is the TCP socket that we discussed, which is reliable. It goes through the Playroom edge servers. And they are 80 to 150 milliseconds latency. The other type of connection is the UDP or WebRTC connection that Playroom maintains between the players. So, no Playroom edge server is involved in these connections. And these are using WebRTC. And they are unreliable by nature. So, that means that your state may not always reach the other end. But for some types of states, this is OK. For example, for player positions, this is fine because you will probably be sending the player position again in a few milliseconds again. So, if you miss one, it doesn't matter. You just send a new one.

6. Sending Player Positions and Playroom Benefits

Short description:

Playroom allows you to choose the type of state to send via different connections, like websockets or WebRTC. The feedback from game developers who have used Playroom has been positive. Its focus is on providing a simple SDK that allows game developers to focus solely on game-related code. To learn more about Playroom, visit Playroom.com or follow the speaker on Twitter.

If you try to send player positions using websockets, what'll happen is there'll be a kind of a number binding effect up there. Where they'll receive a bunch of positions and the players will be first stuck and they'll be fast forwarding. And that's not what you want. But Playroom lets you decide what kind of state you want to send via what kind of connection. And for each set state, you can decide if you want to send it via websockets or WebRTC. Otherwise, Playroom will decide itself based on the connection quality and all that stuff.

We shared Playroom with a bunch of game developers and the early feedback has been great. I guess the focus of Playroom is to make the simplest possible multi-layer SDK and the focus is for game developers to not write any code that is not related to the game. And, yeah, the feedback has been good. That's it from my side. Thank you very much. You can learn more about Playroom and join Playroom.com. You can also follow me on Twitter or scan this QR code to follow me on Twitter.

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

React Advanced Conference 2022React Advanced Conference 2022
25 min
A Guide to React Rendering Behavior
Top Content
React is a library for "rendering" UI from components, but many users find themselves confused about how React rendering actually works. What do terms like "rendering", "reconciliation", "Fibers", and "committing" actually mean? When do renders happen? How does Context affect rendering, and how do libraries like Redux cause updates? In this talk, we'll clear up the confusion and provide a solid foundation for understanding when, why, and how React renders. We'll look at: - What "rendering" actually is - How React queues renders and the standard rendering behavior - How keys and component types are used in rendering - Techniques for optimizing render performance - How context usage affects rendering behavior| - How external libraries tie into React rendering
React Summit 2023React Summit 2023
32 min
Speeding Up Your React App With Less JavaScript
Too much JavaScript is getting you down? New frameworks promising no JavaScript look interesting, but you have an existing React application to maintain. What if Qwik React is your answer for faster applications startup and better user experience? Qwik React allows you to easily turn your React application into a collection of islands, which can be SSRed and delayed hydrated, and in some instances, hydration skipped altogether. And all of this in an incremental way without a rewrite.
React Summit 2023React Summit 2023
23 min
React Concurrency, Explained
React 18! Concurrent features! You might’ve already tried the new APIs like useTransition, or you might’ve just heard of them. But do you know how React 18 achieves the performance wins it brings with itself? In this talk, let’s peek under the hood of React 18’s performance features: - How React 18 lowers the time your page stays frozen (aka TBT) - What exactly happens in the main thread when you run useTransition() - What’s the catch with the improvements (there’s no free cake!), and why Vue.js and Preact straight refused to ship anything similar
JSNation 2022JSNation 2022
21 min
The Future of Performance Tooling
Top Content
Our understanding of performance & user-experience has heavily evolved over the years. Web Developer Tooling needs to similarly evolve to make sure it is user-centric, actionable and contextual where modern experiences are concerned. In this talk, Addy will walk you through Chrome and others have been thinking about this problem and what updates they've been making to performance tools to lower the friction for building great experiences on the web.
JS GameDev Summit 2022JS GameDev Summit 2022
33 min
Building Fun Experiments with WebXR & Babylon.js
Top Content
During this session, we’ll see a couple of demos of what you can do using WebXR, with Babylon.js. From VR audio experiments, to casual gaming in VR on an arcade machine up to more serious usage to create new ways of collaboration using either AR or VR, you should have a pretty good understanding of what you can do today.
Check the article as well to see the full content including code samples: article. 

Workshops on related topic

React Summit 2023React Summit 2023
170 min
React Performance Debugging Masterclass
Featured WorkshopFree
Ivan’s first attempts at performance debugging were chaotic. He would see a slow interaction, try a random optimization, see that it didn't help, and keep trying other optimizations until he found the right one (or gave up).
Back then, Ivan didn’t know how to use performance devtools well. He would do a recording in Chrome DevTools or React Profiler, poke around it, try clicking random things, and then close it in frustration a few minutes later. Now, Ivan knows exactly where and what to look for. And in this workshop, Ivan will teach you that too.
Here’s how this is going to work. We’ll take a slow app → debug it (using tools like Chrome DevTools, React Profiler, and why-did-you-render) → pinpoint the bottleneck → and then repeat, several times more. We won’t talk about the solutions (in 90% of the cases, it’s just the ol’ regular useMemo() or memo()). But we’ll talk about everything that comes before – and learn how to analyze any React performance problem, step by step.
(Note: This workshop is best suited for engineers who are already familiar with how useMemo() and memo() work – but want to get better at using the performance tools around React. Also, we’ll be covering interaction performance, not load speed, so you won’t hear a word about Lighthouse 🤐)
JSNation 2023JSNation 2023
116 min
Make a Game With PlayCanvas in 2 Hours
Featured WorkshopFree
In this workshop, we’ll build a game using the PlayCanvas WebGL engine from start to finish. From development to publishing, we’ll cover the most crucial features such as scripting, UI creation and much more.
Table of the content:- Introduction- Intro to PlayCanvas- What we will be building- Adding a character model and animation- Making the character move with scripts- 'Fake' running- Adding obstacles- Detecting collisions- Adding a score counter- Game over and restarting- Wrap up!- Questions
Workshop levelFamiliarity with game engines and game development aspects is recommended, but not required.
JSNation 2023JSNation 2023
170 min
Building WebApps That Light Up the Internet with QwikCity
Featured WorkshopFree
Building instant-on web applications at scale have been elusive. Real-world sites need tracking, analytics, and complex user interfaces and interactions. We always start with the best intentions but end up with a less-than-ideal site.
QwikCity is a new meta-framework that allows you to build large-scale applications with constant startup-up performance. We will look at how to build a QwikCity application and what makes it unique. The workshop will show you how to set up a QwikCitp project. How routing works with layout. The demo application will fetch data and present it to the user in an editable form. And finally, how one can use authentication. All of the basic parts for any large-scale applications.
Along the way, we will also look at what makes Qwik unique, and how resumability enables constant startup performance no matter the application complexity.
React Day Berlin 2022React Day Berlin 2022
53 min
Next.js 13: Data Fetching Strategies
Top Content
WorkshopFree
- Introduction- Prerequisites for the workshop- Fetching strategies: fundamentals- Fetching strategies – hands-on: fetch API, cache (static VS dynamic), revalidate, suspense (parallel data fetching)- Test your build and serve it on Vercel- Future: Server components VS Client components- Workshop easter egg (unrelated to the topic, calling out accessibility)- Wrapping up
JS GameDev Summit 2022JS GameDev Summit 2022
121 min
PlayCanvas End-to-End : the quick version
Top Content
WorkshopFree
In this workshop, we’ll build a complete game using the PlayCanvas engine while learning the best practices for project management. From development to publishing, we’ll cover the most crucial features such as asset management, scripting, audio, debugging, and much more.
React Advanced Conference 2023React Advanced Conference 2023
148 min
React Performance Debugging
Workshop
Ivan’s first attempts at performance debugging were chaotic. He would see a slow interaction, try a random optimization, see that it didn't help, and keep trying other optimizations until he found the right one (or gave up).
Back then, Ivan didn’t know how to use performance devtools well. He would do a recording in Chrome DevTools or React Profiler, poke around it, try clicking random things, and then close it in frustration a few minutes later. Now, Ivan knows exactly where and what to look for. And in this workshop, Ivan will teach you that too.
Here’s how this is going to work. We’ll take a slow app → debug it (using tools like Chrome DevTools, React Profiler, and why-did-you-render) → pinpoint the bottleneck → and then repeat, several times more. We won’t talk about the solutions (in 90% of the cases, it’s just the ol’ regular useMemo() or memo()). But we’ll talk about everything that comes before – and learn how to analyze any React performance problem, step by step.
(Note: This workshop is best suited for engineers who are already familiar with how useMemo() and memo() work – but want to get better at using the performance tools around React. Also, we’ll be covering interaction performance, not load speed, so you won’t hear a word about Lighthouse 🤐)