Serverless Multiplayer Game that Scales…
Game development is a very complex and multidisciplinary activity and surely the success of games as one of most profitable areas in entertainment domain could not be incidentally.
If you’re a game developer, you would know how complex the development process is. There is planning, design, development, testing, releasing, and many other aspects. However, you can not create something captivating if you follow those obsolete practices.
Old practices make the development process quite hard. The schedules clash, there’s miscommunication, dependencies, and most importantly, everything is happening simultaneously. These problems limit innovation and creativity.
Game Development is immensely iterative process with rapidly changing requirements. Many of the game developers focused mainly on to maximize the time spent building features and less time configuring servers, managing infrastructure, and mastering scale.
🔰What does serverless means ?
Serverless is a cloud-native development model that allows developers to build and run applications without having to manage servers. There are still servers in serverless, but they are abstracted away from app development.
AWS Serverless provides four key benefits for customers. First, it can help move from idea to market faster, by reducing operational overhead. Second, customers may realize lower costs with serverless by not over-provisioning hardware and software to operate. Third, serverless scales with user activity. Finally, serverless services provide built-in integration, allowing you to focus on your game instead of connecting pieces together.
For AWS Gaming customers, these benefits allow your teams to spend more time focusing on gameplay and content, instead of undifferentiated tasks such as setting up and maintaining servers and software. This can result in better gameplay and content, and a faster time-to-market.
Lets get acquainted with how serverless framework assist in creating a scalable multiplayer game.
Introducing the Simple Trivia Service
The Simple Trivia Service offers single- and multi-player trivia games with content created by players. There are many features in Simple Trivia Service found in games, such as user registration, chat, content creation, leaderboards, game play, and a marketplace.
Authenticated players can chat with other players, create and manage quizzes, and update their profile. They can play single- and multi-player quizzes, host quizzes, and buy and sell quizzes on the marketplace. The single- and multi-player game modes show how games with different connectivity and technical requirements can be delivered with serverless first architectures. The game modes and architecture solutions are covered in the Simple Trivia Service backend architecture section.
Simple Trivia Service front end
The Simple Trivia Service front end is a Vue.js single page application (SPA) that accesses backend services. The SPA app, accessed via a web browser, allows users to make requests to the game endpoints using HTTPS, secure WebSockets, and WebSockets over MQTT. These requests use integrations to access the serverless backend services.
Vue.js helps make this reference architecture more accessible. The front end uses AWS Amplify to build, deploy, and host the SPA without the need to provision and manage any resources.
These steps will configure the Qwizardly UI to utilize the features deployed during the Backend Setup.
- Navigate to the serverless-trivia-game/frontend directory.
- Run the command
npm installto install dependencies.
- Edit the file src/services/AWSConfig.js. Add the values for your endpoints and region that you copied from the backend setup and save the file.
Note: These values are from steps 3 and 8 in the Backend Setup section.
- Run the command
npm run serveto run the webapp locally.
Note: The avatar notification relies on service workers that are activated only in production build. To run this locally use the following steps instead of 4.
- Run the command
npm install -g serve
- Run the command
npm run buildto create a production build for the frontend in the dist/ folder
- Run the command
serve -s -p 8080 dist/to run the webapp locally on port 8080
- Once the app is running, navigate to http://localhost:8080 to use the Simple Trivia Service frontend.
Simple Trivia Service backend architecture
The backend architecture for Simple Trivia Service is defined in a set of AWS Serverless Application Model (AWS SAM) templates for portions of the game.
Services used for building the game:
👉AWS Lambda: Lambda enables serverless microservice features in Simple Trivia Service.
👉Amazon API Gateway: API Gateway provides serverless endpoints for HTTP/RESTful and WebSocket communication while IoT delivers a serverless endpoint for WebSockets over MQTT communication.
👉DynamoDB: Amazon DynamoDB is a fully managed proprietary NoSQL database service that supports key–value and document data structures.
👉Amazon Simple Notification Service: Amazon Simple Notification Service is a notification service provided as part of Amazon Web Services.It provides a low-cost infrastructure for the mass delivery of messages, predominantly to mobile users.
👉AWS Step Functions: AWS Step Functions is a low-code, visual workflow service that developers use to build distributed applications, automate IT and business processes, and build data and machine learning pipelines using AWS services.
👉Amazon Kinesis: Amazon Kinesis Data Streams is a serverless streaming data service that makes it easy to capture, process, and store data streams at any scale.
👉Amazon S3: Amazon Simple Storage Service (Amazon S3) is an object storage service that offers industry-leading scalability, data availability, security, and performance. You can use Amazon S3 to store and retrieve any amount of data at any time, from anywhere.
👉Amazon Athena: Amazon Athena is a serverless, interactive query service to query data and analyze big data in Amazon S3 using standard SQL.
👉Amazon Cognito: provides secure, standards-based login and a user directory.
This set of steps will deploy a number of AWS resources to your account, including DynamoDB tables, Lambda functions, API Gateway instances, and Cognito User Pools.
- Create an AWS Account if you do not already have one.
- Clone this repo using
- Use the command
aws iot describe-endpoint --endpoint-type iot:Data-ATS --region <your_region>to obtain the IoT endpoint. Copy this value down, as it is also required for the backend and user interface.
- Navigate to the serverless-trivia-game directory and run the command
./prebuild.sh. This script will build 2 layers, which are required for the project, as well as installing Node.JS dependencies. When the script is finished, you should be in the directory serverless-trivia-game.
- Navigate to the serverless-trivia-game/backend directory.
- Run the command
sam build --use-containerto package the application. This is used to compile your functions in a Docker container that behaves like a Lambda environment, so they're in the right format when you deploy them to the AWS Cloud.
- Run the command
sam deploy --guidedto start the deployment of the application. The following options are presented during this step:
Stack name: sts
Region: <your selected region>
IoTEndpoint: <your IoTEndpoint from step 3>
Confirm changes before deploy: N
Allow SAM CLI IAM role creation: Y
Save arguments to configuration file: Y
SAM configuration file: samconfig.toml
Note: The project includes a samconfig.toml file with the rights for
CAPABILITY_AUTO_EXPAND.AUTO_EXPAND is required to support SAM Nested Templates, which this project includees.
- Copy the outputs from the
sam deploycommand. You will need these to setup Simple Trivia Service's user interface.
Note: The token for CloudFormation may timeout. If it does, navigate to the AWS CloudFormation page, find the
stsstack and click on the
Outputstab to get these values.
Supporting Architectures and Game Types:
Simple Trivia Service’s three game modes define how players interact with the backend services. These modes align to different architectures used within the game.
“Single Player” quiz architecture
Single player quizzes have simple rules, short play sessions, and appeal to wide audiences. Single player game communication is player-to-endpoint only. This is accomplished with API Gateway via an HTTP API.
Four Lambda functions (ActiveGamesList, GamePlay, GameAnswer, and LeaderboardGet) enable single player games. These functions are integrated with API Gateway and respond to specific requests from the client. API Gateway forwards the request, including URI, body, and query string, to the appropriate Lambda function.
When a player chooses “Play”, a request is sent to API Gateway, which invokes the ActiveGamesList function. This function queries the ActiveGames DynamoDB table and returns the list of active games to the user.
The player selects a game, resulting in another request triggering the GamePlay function. GamePlay retrieves the game’s questions from the GamesDetail DynamoDB table. The front end maintains the state for the user during the game.
When all questions are answered, the SPA sends the player’s responses to API Gateway, invoking the GameAnswer function. This function scores the player’s responses against the GameDetails table. The score and answers are sent to the user.
Additionally, this function sends the player score for the leaderboard and player experience to two SNS topics (LeaderboardTopic and PlayerProgressTopic). The ScorePut and PlayerProgressPut functions subscribe to these topics. These two functions write the details to the Leaderboard and Player Progress DynamoDB tables.
This architecture processes these two actions asynchronously, resulting in the player receiving their score and answers without having to wait. This also allows for increased security for player progress, as only the PlayerProgressPut function is allowed to write to this table.
Finally, the player can view the game’s leaderboard, which is returned to the player as the response to the GetLeaderboard function. The function retrieves the top 10 scores and the current player’s score from the Leaderboard table.
“Multi-player — Casual and Competitive” architecture
These game types require player-to-player and service-to-player communication. This is typically performed using TCP/UDP sockets or the WebSocket protocol. API Gateway WebSockets provides WebSocket communication and enables Lambda functions to send messages to and receive messages from game hosts and players.
Game hosts start games via the “Host” button, messaging the LiveAdmin function via API Gateway. The function adds the game to the LiveGames table, which allows players to find and join the game. A list of questions for the game is sent to the game host from the LiveAdmin function at this time. Additionally, the game host is added to the GameConnections table, which keeps track of which connections are related to a game. Players, via the LivePlayer function, are also added to this table when they join a game.
The game host client manages the state of the game for all players and controls the flow of the game, sending questions, correct answers, and leaderboards to players via API Gateway and the LiveAdmin function. The function only sends game messages to the players in the GameConnections table. Player answers are sent to the host via the LivePlayer function.
To end the game, the game host sends a message with the final leaderboard to all players via the LiveAdmin function. This function also stores the leaderboard in the Leaderboard table, removes the game from the ActiveGames table, and sends player progression messages to the Player Progress topic.
“Multi-player — Live Scoreboard” architecture
This is an extension of other multi-player game types requiring similar communications. This uses IoT with WebSockets over MQTT as the transport. It enables the client to subscribe to a topic and act on messages it receives. IoT manages routing messages to clients based on their subscriptions.
This architecture moves the state management from the game host client to a data store on the backend. This change requires a database that can respond quickly to user actions. Simple Trivia Service uses ElastiCache for Redis for this database. Game questions, player responses, and the leaderboard are all stored and updated in Redis during the quiz. The ElastiCache instance is blocked from internet traffic by placing it in a VPC. A security group configures access for the Lambda functions in the same VPC.
Game hosts for this type of game start the game by hosting it, which sends a message to IoT, triggering the CacheGame function. This function adds the game to the ActiveGames table and caches the quiz details from DynamoDB into Redis. Players join the game by sending a message, which is delivered to the JoinGame function. This adds the user record to Redis and alerts the game host that a player has joined.
Game hosts can send questions to the players via a message that invokes the AskQuestion function. This function updates the current question number in Redis and sends the question to subscribed players via the AskQuestion function. The ReceiveAnswer function processes player responses. It validates the response, stores it in Redis, updates the scoreboard, and replies to all players with the updated scoreboard after the first correct answer. The game scoreboard is updated for players in real time.
When the game is over, the game host sends a message to the EndGame function via IoT. This function writes the game leaderboard to the Leaderboard table, sends player progress to the Player Progress SNS topic, deletes the game from cache, and removes the game from the ActiveGames table.
Conclusion: A serverless approach for your application could be perfect. If you need to spin up an app fast, serverless might be your solution. Instead of weeks and months to deploy an app, you can do it within hours and days. The reason behind this is that you don’t have to concern yourself with infrastructure. You can focus on the code and release it immediately. Scalability is automatic and you don’t have to worry about any provisioning needs.
🎁Github Repo for Setup and Instructions: https://github.com/aws-samples/serverless-trivia-game
- Serverless Compute : https://aws.amazon.com/blogs/compute/building-a-serverless-multiplayer-game-that-scales/
- Serverless real-time analytics: https://d1.awsstatic.com/architecture-diagrams/ArchitectureDiagrams/serverless-analytics-for-mobile-gaming.pdf?gamd_mp6
- Serverless In-Game Screenshot Processor Pipeline for Game Studios: https://d1.awsstatic.com/architecture-diagrams/ArchitectureDiagrams/serverless-in-game-screenshot-processing-ra.pdf?did=wp_card&trk=wp_card
- Serverless game on AWS: https://github.com/aws-samples/serverless-games-on-aws
- Blogs on serverless architecture: https://serverlessland.com/