How to build a real-time multiplayer game using only Firebase as a backend

Koya Tamura
9 min readMar 10, 2020

--

Hi, I’m Koya, a solo mobile game developer. I released Magic21, the realtime 2-players card game whose rule is based on blackjack in February 2020. It is a logical and strategic game but also you need your own luck and to read the opponent’s mind. It is available on App Store and Google Play Store. Download it here!

Trailer Version 0.2.0

There are 2 key features of Magic21.

  • A real-time turn-based game: slow-paced, not latency-sensitive
  • 2-players game

To achieve these, matchmaking and battle in real-time are required. And obviously, something codes on the server is necessary. Then I decided to build Magic21 using Unity C# as a client-side and Firebase as a server-side. Choosing Unity C# is common for game development but why Firebase? In this article, I’m explaining the reasons why I use Firebase as a backend as a service (BaaS for short) and how to use it in Magic21.

Why I choose Firebase for game development

When we solely develop a game that needs backends, we have a bunch of choices of BaaS for games. For example Playfab, GameSparks, Photon, etc… I actually used to use them experimentally and kept thinking which BaaS is a better choice for me. And then I listed up my two requirements as below.

  • I want to use something BaaS at a reasonable price as possible
  • I want to learn something that is adaptive and applicable to a wide range of fields

I explain these in detail.

I want to use something BaaS at a reasonable price as possible

The price of BaaS for games tends to be expensive because they give us so many features that game developers want. BaaS for games provide matchmaking, leaders board, real-time API, etc. They are amazingly useful, especially for real-time multiplayer games. BaaS for games allow us to create a matchmaking system on our game in one week. This is why BaaS for games are expensive generally.

Whereas Firebase doesn’t have functions specialized for game development. But as I mentioned before, Magic21 only needs middlewares or frameworks that can resolve 2-players matchmaking and real-time battle, and Firebase Realtime Database with Unity SDK does solve that (mentioning it later). Additionally, the price is not as expensive as BaaS for games. This is one of the reasons I’m using Firebase in game development.

(But now it is unclear how low-priced the payment of Firebase compare to other BaaS accurately. To keep reporting this, please download Magic21 from here and play it to join this experiment. If I collect enough data, I will publish a new article about a summary of the payment report!)

I want to learn something that is adaptive and applied a wide range of fields

Also from another perspective, when I learn new things as a software engineer, I want these new things to be applicable to other products that are not only games. In my case, if I learn BaaS for games, this skill will be only for game development. However, I already planned to build another web and mobile application near the future so I wanted to pick up something for them. During I was thinking of it, I found this video which gave a presentation about developing games with Firebase.

When I watched this video, I was excited because this video ensures that Firebase is also suitable for game development. I had had a few experiences of using Firebase on iOS. So I felt that I could take advantage of my previous experience in my current game development. Additionally, this video implies that Google keeps investing Firebase for game developers. Actually Firebase SDK for Unity has been updated constantly. This is another reason why I’m using Firebase for developing Magic21.

I’m sure that you can create a mobile game no matter what BaaS you use. But once you build your game using BaaS, it is locked in BaaS you choose. This means you might live together with BaaS you choose until you or your game die. Should be serious when thinking of which BaaS you use, like a marriage. (I’ve never regret to choose Firebase, and my wife as well 😆 )

How to use Firebase on Magic21

As I mentioned before, The two key features of Magic21 are here.

  • A real-time turn-based game: slow-paced, not latency-sensitive -> Real-time game
  • 2-players game -> Matchmaking

Let’s go over these features.

Realtime Two-Players Game Implementation

When we use Firebase and need to use any database system, you need to select which database you use, Realtime Database or Cloud Firestore (The official document said the difference between them). For realtime game development, it is a better choice to choose the Realtime Database. The critical reason is that Realtime Database SDK for Unity has a powerful API that is event listeners for subscribing to changes values on Realtime Database. B̵u̵t̵ ̵C̵l̵o̵u̵d̵ ̵F̵i̵r̵e̵s̵t̵o̵r̵e̵ ̵S̵D̵K̵ ̵d̵o̵e̵s̵n̵’̵t̵ ̵s̵u̵p̵p̵o̵r̵t̵ ̵U̵n̵i̵t̵y̵.̵ While I was writing this article, On March 5th, 2020, Firebase SDK for Unity added experimental support for Cloud Firestore on version 6.12.0! What a timely topic. 😜 Cloud Firestore for Unity also supports near-real-time listeners. But Firebase Support Team said:

since version 6.12.0 Unity SDK now supports real time updates, but this is an experimental support, it should be considered as a beta phase and probably is not ready for production environments yet.

Eventually, it is better to use Realtime Database so far in the case of Unity.

Here is the core concept of how to implement a realtime two-players game.

1. Create a new database

Before coding, create a new database named matches on Realtime Database and use it instead of the default database because of scaling (mentioning it later). I recommend naming a database name as ${project_id}-${database_name}. Database names should be unique through all projects. So you can avoid conflicts using this rule. In this case, my test project id is test-project-a1c6e so I name test-project-a1c6e-matches. And notice that you need to upgrade your plan to Blaze plan to create a new database.

Creating a new database on Realtime Database

2. Setup SDK and add event listeners

Setup the Firebase project and SDK like this documentation. And then add event listeners on thematchesdatabase. Here is a sample C# code.

Initialize Firebase App and add a listener

3. Send a request to Cloud Functions

Send a request to Cloud Functions for something action. For example in Magic21, drawing cards, casting spells, etc. Here is what we need.

4. Modify Values on Realtime Database

After Cloud Functions receives a request from clients, Cloud Functions updates values on matches database on Realtime Database. Here are great video tutorials for Cloud Functions with Realtime Database. I have watched these videos a million times.

5. Receive changed values

Clients are always notified when values on Realtime Database are changed if you add a listener of ValueChanged in advance.

6. Perform something on clients

Clients can handle values that clients receive from Realtime Database. So we can perform whatever we want on our client by using values from Realtime Database.

Actual game screen with the dashboard of Realtime Database

About scaling

Now I’m mentioning scaling. According to pricing and pricing FAQ, each database on Realtime Database has a limit of 200K simultaneous connections. What should I do if matches database needs more than 200k simultaneous connections? This is what we need. Just create more databases such asmatches2, matches3databases to shard matches data. Fantastic! 😙

(But now it is enough to have only one database. Please download Magic21 from here and play it to spike database traffic! 😜 If I need to shard my databases, I will publish a new article about it with interesting data like DAU, MAU, and so on!)

OK, now we got how to develop a multiplayer game. But how do we make a match with two players? Go on the next.

Matchmaking

Google I/O 2019 announced a bunch of tips for gaming. I found another video that introduced building matchmaking with an open-source called Open Match. I burned my curiosity with Open Match and read its basic concept.

(https://open-match.dev/site/docs/getting-started/#concepts-for-the-demo)

It is literally an amazing tool but I don’t want to use other tools any more except for Firebase because of solo development. So I tried to realize a matchmaking system by using Firebase.

Here is a brief summary of matchmaking by Firebase.

The Matchmaking on Magic21

The point is that I combine Realtime Database and Cloud Firestore. Why? There are two requirements to build matchmaking.

  • Notify a new match found to clients
  • Need transaction for operations of reading, writing, deleting operation atomically through different data collections

As I mentioned, Realtime Database SDK allows subscribing ValueChanged events. That is a crucial feature for notifying a new match found to clients. Though, its transaction isn’t capable of operating with multiple databases. The transaction on Realtime Database works only a certain path on a single database. In my case, there are two databases that matchmaking system operates with, matchesdatabase and match-queuedatabase. Thus, I’m using Realtime Database for only notifying a new match found to players.

In contrast, Cloud Firestore is adequate to operate with multiple collections using a transaction. In my matchmaking system, Cloud functions execute these processes with a transaction:

  1. Find 2 players with similar ratings from match-queue collection
  2. Create a new match on matches collection
  3. Delete these 2 players from match-queue collection

This is why I combine two databases.

As I mentioned, since March 5th, 2020, Cloud Firestore SDK starts supporting Unity. That means my matchmaking could be simplified using only Cloud Firestore. This might be another topic of my future article.

Wrap Up

I described how to create realtime game especially focusing on differences between Firebase Realtime Database and Cloud Firestore. To maximize these Firebase tools, we need to learn them precisely. Use Firebase effectively, make the great app fast!

And as you notice, Firebase also provides a bunch of documents and helpful video resources. If you still can not resolve your own problem by referencing these resources, you can ask Firebase Support Team directly. They probably reply to your question in 1–2 days. This is also surely helpful. Thank you Firebase Support Team!

Magic21 is using not only Cloud Functions, Realtime Database, and Cloud Firestore, but also Firebase Authentication and Remote Config. And In the future, I will use more. I want to challenge how far can Magic21 does by using only Firebase as a solo developer. Please join my challenge to play Magic21! I guarantee that Magic21 itself is so much fun.

Thank you for completing this journey. Follow me on Medium and Twitter, and clap it! That motivates me to keep posting other tips! And leave any comment without hesitation 😄

--

--

Koya Tamura

Digital Board Games Creator. Bring unique fun board games into a digital world by using Unity and Firebase.