Developing a successful mobile game today is about more than just the game: Users expect backend services like user authentication, downloadable content, and social features. Using our AWS Mobile SDK for iOS and Android, it’s easier than ever to build a game with these services. This session will provide a step-by-step approach to add features to your game such as user identity management, dynamic content updates, cross-platform data sync, and more. We’ll demonstrate how to use the AWS Mobile SDK to securely interact with services such as Amazon Cognito, Amazon DynamoDB, Amazon S3, and Amazon EC2. Finally, we’ll provide a few common architecture patterns and scalability tips for AWS game backend(s).
3. AWS Gaming Solutions
Authenticate users
Authorize access
Synchronize data
Manage users and identity providers
Securely access cloud resources
Sync user preferences across devices
Store and Deliver media
Send Push Notifications
Store user-generated photos Media and share them
Bring users back to your app by sending messages reliably
Store shared data
Store and query fast NoSQL data across users and devices
Analyze User Behavior
Track active users, engagement
4. AWS Gaming Solutions
Introducing AWS Mobile Services
Amazon Cognito Amazon Mobile Analytics Amazon SNS Mobile Push
Kinesis Recorder DynamoDB Mapper S3 Transfer Mgr SQS Client SES Client
Core Building Block
Services
Mobile Optimized
Connectors
Mobile Optimized
Services
Your Mobile Game
AWS Mobile SDK for iOS, Android & Unity, API Endpoints, Management Console
Compute Storage Networking Analytics Databases
Integrated SDK
AWS Lambda
Lambda
Functions
λ λ
λ
λ
6. AWS Gaming Solutions
Amazon Cognito
Simplifies Identity and
Access Management
Securely access all
AWS services from
Mobile device
Cross-device and
Cross-platform Sync
Implement security best
practices
“Your App data is secure, available offline, and kept in sync between devices”
Synchronize user’s data
across devices and
platforms
Manage users as
unique identities across
identity providers
Guest Your own
Auth
7. AWS Gaming Solutions
Getting Started with Cognito in 3 steps
Sign up for AWS Account and login to AWS Management Console
Download and integrate the Mobile SDK and store and
sync user data in a dataset
Create an identitypool for authenticated and
unauthenticated users in the AWS Console
8. AWS Gaming Solutions
Amazon Cognito Security
Set granular access permissions on AWS
resources
Safeguard AWS Credentials
Helps implement security best practices
EC2 S3 DynamoDB Kinesis
9. AWS Gaming Solutions
Amazon Cognito Security Architecture
End Users
App with
AWS Mobile
SDK
Access
to AWS
Services
Login OAUTH/OpenID
Access Token
Cognito ID,
Temp
Credentials
Access
Token
Pool ID
Role ARNs
Cognito ID
(Temp
Credentials)
DynamoDB
Developer
Cognito Identity
Broker
S3
Mobile Analytics
Cognito Sync
Store
AWS
Management
Console
10. AWS Gaming Solutions
Developer Authenticated Identities
Cognito ID
(Temp
Credentials)
DynamoDB
End Users
Developer
Access
to AWS
Services
Cognito Identity
Broker
Get OpenID Token
Username
password
Cognito ID,
Temp Credentials
S3
Mobile Analytics
Cognito Sync
Store
AWS
Management
Console
OIDC Token
Pool ID
Role ARNs
User Authentication
System
(Running on AWS or not)
OIDC Token
OIDC Token
12. AWS Gaming Solutions
Amazon Cognito Sync
User Data
Storage and
Sync
Any Platform
iOS/Android/FireOS
Store App Data, Preferences and State
Save app and device data to the cloud and merge
them after login
Cross-device Cross-OS Sync
Sync user data and preferences across devices
with one line of code
Work Offline
Data always stored in local SQLite DB first.
Works seamlessly when intermittent or no
connectivity
k/v data
Identity pool
13. AWS Gaming Solutions
Integrating Cognito Sync functionality is simple
Initialize the CredentialsProvider and CognitoClient
Call synchronize on the dataset
Create or open Dataset and Add Key Values
CognitoCachingCredentialsProvider credentialsProvider = new
CognitoCachingCredentialsProvider( getApplicationContext(), "IDENTITY_POOL_ID”,
Regions.US_EAST_1);
CognitoSyncManager client = new CognitoSyncManager( getApplicationContext(),
Regions.YOUR_REGION, credentialsProvider);
dataset.synchronize(syncCallback);
client.openOrCreateDataset(datasetName);
dataset.put(key, value);
14. AWS Gaming Solutions
Integrating Cognito Sync functionality is simple
Initialize the AWSCognitoSyncClient
Call synchronize on the dataset
Create or open Dataset and Add Key Values
AWSCognitoDataset *dataset = [syncClient openOrCreateDataset:@"myDataSet"];
[dataset setString:@"my value" forKey:@"myKey"];
NSString *value = [dataset stringForKey:@"myKey"];
AWSCognito *syncClient = [AWSCognito defaultCognito];
[dataset synchronize];
iOS
20. AWS Gaming Solutions
Amazon Mobile Analytics
Scalable and Generous
Free Tier
Focus on metrics that matter. Usage
reports available within 60 minutes of
receiving data from an app
Fast
Scale to billions of
events per day from
millions of users.
Own Your Data
“Easily collect, visualize and understand your app usage data at scale”
Data collected are not
shared, aggregated, or
reused
21. AWS Gaming Solutions
Getting Started with Mobile Analytics
in 3 steps
Sign up for AWS Account and create or use existing Cognito ID in
the AWS Management Console
View engagement and session activity reports in the
AWS Management console within minutes
Download and integrate the Mobile SDK with one line of
code (Android/FireOS, iOS)
22. AWS Gaming Solutions
Key Business Metrics
(with one line of code)
1. Monthly Active Users
(MAU)
2. Daily Active Users
(DAU)
3. New Users,
4. Daily Sessions,
5. Sticky Factor,
6. 1-Day Retention,
7. Avg. Revenue per DAU,
8. Daily Paying Users,
9. Avg. Paying DAU
23. AWS Gaming Solutions
Get behavioral insights into app specific
actions that your users take
Reports provide a view of how often custom
events occur. You can add further context
with Attributes and Metrics, to each custom
event
Track the number of
Likes/Shares, per
article, in a news app
Understand player
abort rates per
level, in a game
Number of songs
played, per user
session, in a music
app
In-app item popularity
in a shopping app
Track Custom Events
24. AWS Gaming Solutions
Integrating Mobile Analytics is simple
Initialize the MobileAnalyticsManager. That’s it!
For Custom Events activity reports, add events.
Add OnResume() and OnPause()
private static MobileAnalyticsManager analytics;
analytics = MobileAnalyticsManager.getOrCreateInstance
(this.getApplicationContext(), "appId", "identityPoolId”);
EventClient eventClient = analytics.getEventClient();
MobileAnalyticsEvent levelCompleteEvent=eventClient.createEvent("LevelComplete");
eventClient.recordEvent(levelCompleteEvent);
analytics.getSessionClient().resumeSession();
analytics.getSessionClient().pauseSession();
analytics.getEventClient().submitEvents();
25. AWS Gaming Solutions
Integrating Mobile Analytics is simple
Initialize the AWSMobileAnalytics object. That’s it!
Submit the event. If we don't call submitEvents, events
will automatically be submitted at periodic intervals.
Create add Custom Events
[eventClient submitEvents];
id<AWSMobileAnalyticsEventClient> eventClient =
analytics.eventClient;
id<AWSMobileAnalyticsEvent> levelEvent = [eventClient
createEventWithEventType:@"LevelComplete"];
AWSMobileAnalytics *analytics = [AWSMobileAnalytics
mobileAnalyticsForAppId:@"yourAppId" identityPoolId: @"cognitoId"];
iOS
27. AWS Gaming Solutions
Each platform works differently, and push gets more
complex as you scale to support millions of devices.
Cloud App
Platform Services Mobile Apps
28. AWS Gaming Solutions
Amazon SNS
Cross-platform
Mobile Push
Internet
Apple APNS
Google GCM
Amazon ADM
Windows WNS and
MPNS
Baidu CP
New features:
Message Expiry Time
Message Attributes
Delivery Status
Broadcast
iOS 8 support.
Amazon SNS Mobile Push
Android Phones and Tablets
Apple iPhones and iPads
Kindle Fire Devices
Android Phones and Tablets in China
iOS
Windows Desktop and Windows Phone
Devices
30. AWS Gaming Solutions
Joe Anna Bob
Highscores
Joe 1500
Anna 800
Bob 750
Amazon DynamoDB Connector: Object Mapper
Simplifies access to Amazon
DynamoDB in your app
Map client-side classes to Amazon
DynamoDB tables
Removes the need to transform
objects into tables and vice versa
31. AWS Gaming Solutions
Amazon DynamoDB: Example
@DynamoDBTable(tableName = ”Highscores")
public static class HighScore{
private int id, highScore;
private String name;
@DynamoDBHashKey(attributeName = "id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@DynamoDBAttribute(attributeName=”name")
public String getName() {
return name;
}……
id name highscore
17 Joe 25
23 Anna 67
32 Bob 55
Table: Highscores
32. AWS Gaming Solutions
Amazon DynamoDB: Example
// Build a highscore object
HighScore highScore = new HighScore();
highScore.setId(17);
highScore.setName(”Joe");
highScore.setHighScore(25);
// Save book object to dynmaoDB
mapper.save(highScore);
// Update item and save object again
highScore.setHighScore(118);
mapper.save(highScore);
// Load another book
HighScore anotherHighScore = mapper.load(HighScore.class,23);
33. AWS Gaming Solutions
Some Best Practices for Backend Services
S3:
• How you name your S3 Objects is very Important.
• Randomize the prefix of your object keys to ensure better distribution on
S3’s partitions.
• You don’t have to worry about the bucket name itself.
• If your app is GET heavy on S3 Objects, consider using CloudFront
DynamoDB:
• Keep item size small
• Store metadata in Amazon DynamoDB and large blobs in Amazon S3
• Avoid hot keys and hot partitions
• Use conditional/OCC updates
35. AWS Gaming Solutions
AWS Mobile SDKs for Gaming
1. AWS Mobile SDK for Android
2. AWS Mobile SDK for iOS
3. AWS Mobile SDK for Xamarin (New - Dev Preview)
4. AWS Mobile SDK for Unity
36. AWS Gaming Solutions
Introducing the AWS SDK for Unity
• Generally Available as of May
2015
• Services available
Amazon DynamoDB
Amazon S3
Amazon Cognito
Amazon Mobile Analytics
Amazon SNS
• Kick off AWS Lambda with SNS
and/or S3
• Can build custom plugins with
AWS .NET SDK if desired
37. AWS Gaming Solutions
SDK Installation and Setup
• Download AWS Unity SDK and unzip
– http://aws.amazon.com/mobile/sdk/
• Import the desired package(s) into Unity as a Custom
Package
– CognitoSync Package
– DynamoDB Package
– S3 Package
– MobileAnalytics Package
– SNS Package
• Add the AWSPrefab to Scene in Unity
38. AWS Gaming Solutions
Grumpy Flappy Game
• Demo will showcase
– Cognito Identity
– Cognito Sync
– Mobile Analytics
• Similar Demos will be open-sourced …and
polished
– Showing more of the AWS services
• Other Unity Samples Available on GitHub
40. AWS Gaming Solutions
Grumpy Flappy : Services Setup
• Set up Cognito Identity Pool
– Create Grumpy Flappy Identity Pool
– Retrieve Identity Pool ID
• Set up Mobile Analytics App
– Add Grumpy Flappy App
– Retrieve App ID
42. AWS Gaming Solutions
Adding DynamoDB
• Create DynamoDB Table
– Using DynamoDB Console
– Using code with createTable method
– Using Visual Studio with AWS Toolkit for Visual Studio:
http://aws.amazon.com/net/
– Example:
• Table Name: GrumpyScoreTable
• Primary Key Type: Hash
• Hash Attribute Name: PlayerID,
• Hash Type: Number
• Create DynamoDB Client
AmazonDynamoDBClient client = new
AmazonDynamoDBClient(RegionEndpoint.USEast1)
43. AWS Gaming Solutions
Using DynamoDB
• Add a High Score Record
– Create High Score Object
[DynamoDBTable("GrumpyScoreTable")]
class FlappyScoreData
{ [DynamoDBHashKey] // hash key
public int PlayerID { get; set; }
[DynamoDBProperty]
public int LastScore { get; set; }
[DynamoDBProperty]
public int HighScore {get; set; }
}
– Save High Score Record to DynamoDB
_context.SaveAsync<HighScore>(myScore,
(AmazonDynamoResult<VoidResponse> result) =>
{ if (result.Exception != null) { this.displayMessage += "Save
failed ; “ +result.Exception.Message; }
44. AWS Gaming Solutions
Adding Simple Storage Service (S3)
• Create S3 Bucket (set permissions)
– Using S3 Console
– Using code with PutBucket and PutBucketRequest
– Using Visual Studio with AWS Toolkit for Visual Studio:
http://aws.amazon.com/net/
– Example:
• Bucket Name: grumpyflappy_bucket
• Create an S3 Transfer Manager
AmazonS3Client S3Client =
new AmazonS3Client (credentials ,RegionEndpoint.USEast1);
45. AWS Gaming Solutions
Using Simple Storage Service (S3)
• Download an Object
– Get Badge Picture (bragging rights)
var request = new GetObjectRequest ()
{ BucketName = bucketName,
Key = downloadKey,
};
S3Client.GetObjectAsync (request, GetObjectCallback,null);
• Upload an Object
Stream stream = null;
stream = new FileStream(uploadSrcFilePath, FileMode.Open, FileAccess.Read,
FileShare.Read);
var postRequest = new PostObjectRequest
{ Key = uploadKey, Bucket = bucketName, InputStream = stream };
S3Client.PostObjectAsync (postRequest, PostObjectCallback,null);
46. AWS Gaming Solutions
AWS Resources
• AWS Mobile Blog
– http://mobile.awsblog.com
• AWS Mobile Services
– http://aws.amazon.com/mobile/
• AWS Mobile SDK
– http://aws.amazon.com/mobile/sdk/
• AWS Mobile Developer Guides
– Unity: http://docs.aws.amazon.com/mobile/sdkforunity/developerguide
– iOS: http://docs.aws.amazon.com/mobile/sdkforios/developerguide
– Android:
http://docs.aws.amazon.com/mobile/sdkforandroid/developerguide/Welcom
e.html
Hi, My name is Dhruv Thukral and I am a Solutions Architect for Gaming here at AWS.
I am joined by Tara Walker, who is a Technical Evangelist at AWS.
The topic of our presentation is Build & Deploy Your Mobile Game with AWS. We have quite a few slides to go through so lets get started.
So creating a mobile game is not just about the Mobile game anymore. The game itself is quite important, but there is a lot more to it.
-First, You need to manage players in your game. Every mobile game or app these days is about acquiring and keeping players and so you want to be able to to provide as much flexibility to your players to be able to authenticate themselves.
-You need to be able to provide value added features to these registered users which often means elevated access to your backend resources such as databases and storage.
-You need to focus on users and not devices, most often players will play your game on multiple devices like an iPad and iPhone to a Android Tablet and Android Phone
-A lot of games are driven by DLC, you need to be able to deliver this content to your users when they require it. No one likes to wait to be able to download a map pack or new level that they just paid for.
-Analytics is a huge part of mobile gaming, I was once had a major mobile customer tell me we are a 70% analytics and a 30% gaming company. Now whether you agree or disagree with that philosophy, this trend is becoming a part of mobile gaming that cant be ignored.
-You need to be able to constantly engage with your users. Usually hooked with the results of your analytics, you can target users with PN’s to inform them of new DLC, or send them promotional messages
-Finally, with features such as leaderboards and highscores, you probably would want to save that shared data somewhere.
We have a full range of services that are fully integrated with the rest of AWS offering, and optimized for mobile use cases, are accessible via a single Mobile SDK and share the same scalable, on-demand, global infrastructure of all our other AWS services.
Cognito provides 3 major advantages
Sync user data across devices
Simplifies Management of users as unique identities across identity providers
Implement AWS security best practices for accessing various AWS services
And Lets first touch on the security aspect. We have seen a lot of developers tend to embed their AWS credentials in their app. These credentials are compromised if the app is decompiled.
Amazon Cognito, eliminates the need to embed you AWS credentials in the app.
Your mobile app authenticates with the identity provider (IdP) using the provider’s SDK. Once the end user is authenticated with the identity provider, the OAuth or OpenID Connect token returned from the identity provider is passed by your app to Amazon Cognito, which returns a new Cognito ID for the user and a set of temporary, limited-privilege AWS credentials. Amazon Cognito supports the creation and token vending process for unauthenticated users as well as authenticated users. Amazon Cognito creates a random, unique identifier for each unauthenticated user.
You can use the unique identifier generated for your app users in your Identity and Access Management policies. For example you can create a policy for an S3 bucket that only allows a particular user access to their own folder thus setting granular access permissions on AWS resources.
Architecturally, Amazon Cognito has two parts: Cognito identity Broker and Cognito Sync Store. Users first login with login provider of their choice and App with SDK does the rest.
In the past, to access cloud services, developers embed aws credentials which is access key id and secret key within the application, this is highly unsecure because it is easy to unip the apk file and get access to keys.
Now we make it extremely secure by not only create temprory creds that are valid only for one hour but also limiting the access to other data. The users only have access to store and sync in their own dataset.
Once you get the temp cred, you can access other AWS services like S3 to store video, for example, DynamoDB to store shared data like leaderboards, kinesis to store streaming data logs and so on.
With Amazon Cognito developers can synchronize application data across an end user’s devices with a single line of code.
With Amazon Cognito, developers can securely store application data, such as preferences and game state in the AWS cloud. With synchronized application data, developers can give your users a consistent, unified experience on their app across all of their mobile devices.
Developers can use Amazon Cognito directly from their mobile app without building or maintaining any backend infrastructure. Amazon Cognito handles secure application data storage and sync, enabling them to focus on their application experiences, instead of the heavy lifting of creating and managing a user application data sync solution.
It manages the complexity of conflict resolution and intermittent network connectivity by managing offline cache ensuring your application can always deliver a great user experience. Each data set in the Amazon Cognito sync store can be synchronized on all devices associated with an identity simply by calling the synchronize () method.
Here is some sample code that shows you how to use cognito sync.
You first create a credentials provider, pass it your application context, your identity pool if and the region.
You then pass the sync manager your credentials provider and your app context and region.
Then adding values to dataset is as simple as opening a dataset. You can have upto a max of 20 datasets per identity so you can group your datasets into user_preferences, inventory, achievements etc, and then you simply add key value pairs to these datasets.
To sync a dataset just call the synchronize method. By default the last update always wins in a sync call if you have multiple clients updating the same dataset.
Handles multipart upload automatically to make the best use of bandwidth and you don’t have to worry about splitting the file into multiple chunks and keep track of the byte range requests.
You create a new S3 client and use your previously created credentials provider. Then set the region. Then create a TU object and simply call the upload and download methods.
3 major advantages for Mobil Anayltics
Measures the most commonly measured metrics automatically for you.
It has a very generous free tier, 100M free events per month, 1 per M events
Own your data, to be ingested in your processing and visualization tool of choice
Quick Overview: Track nine pre-selected metrics in a simple to review dashboard to get a quick idea of engagement
Active Users: Track how many users engage with your app daily and monthly and monitor sticky factor to gauge engagement, appeal, and monetization
Sessions: Track how often your app is used on a given day and how often each user opens your app during a day
Retention: Measure the rate at which customers come back to your app on a daily and weekly basis, after first use
Revenue: Track in-app revenue trend data to identify areas for monetization improvement
Custom Events: Track custom defined user actions specific to your app
Sticky factor
Custom Events let you track any action taken in your app, giving you an incredibly powerful insight into your user’s experience and behavior.
Custom Events are often used to track social events such as number of Likes/Shares, app specific events such as play progress/song played, and in-app purchase events such as transactions per product SKU.
Songs played is the custom even per session. Attribute numerical value associated with the data metric. Attribute: Weaponsused sword, how many people used the sword?
You initialize the MA manager in a similar way. You pass in the app comntext, the appId and the identity pool id. Then for app session related events you called the Session Client, and for Custom Events, you call the Event Client.
If you don’t call submitEvents, events will automatically be submitted at multiple intervals.
Amazon SNS Mobile Push is a managed, scalable, cross-platform push intermediary service. It abstracts the complexity of different push notification services and allows developers to send push notifications across different mobile endpoints. You can subscribe to topics and and send messages which is then relayed to apple and google notifications services
We discussed user data, now lets talk about shared data.
It is highly likely that your app will have some data that you would want to share across users who will be on different platforms and devices. To ensure a fluid experience you would want quick and reliable access to the shared data. As an example, lets take one of the most common use cases in games – many games track high scores, leader boards and achievements to add a social element to the game and to increase user engagement. For that you need a quick access database in the cloud that you can query from the client. DynamoDB is a perfect solution for that.
So what is DynamoDB?
It is a fully managed NoSQL database service. Through its provisioned throughput model, it guarantees predictable performance. As your app can become an instant success overnight and your users can increase from 10s and 100s to 100 of thousands in matter of days. DynamoDB scales seamlessly. There is no cap in the table sizes and throughput limits. It uses SSD-based storage nodes that delivers low-latency access. And there is no administrative overhead.
Now lets talk about how you can access DynamoDB from the AWS Mobile SDK in you Mobile App. In addition to the low-level APIs, we provide DynamoDB Object Mapper that simplifies access to Amazon DynamoDB. Using the Object Mapper, you can map you client-side classes to DynamoDB tables. The client library handles transforming the objects into tables and vice versa, eliminating the need for you to write redundant code.
To see how easy it is to access DynmaoDB, lets look at an example
Now in your mobile app, you can use DynamoDB defined annotations to map client side classes to DynamoDB tables. For this example, we will create a mapping class called Highscore which will have the same fields as the DynamoDB table and Get and Set method for each field.
Next you will simple build a book object and set the required fields.
To save the object to DynamoDB, you will simply use DynamoDBObjectMapper save(..) method
To update the item again, simply update the fields in the object and call save(..) again.
And finally to load another book, you can call the DynamoDBObjectMapper load(..) method and use the hash key. In this case we have set the id as the hash key.
So imagine a case where your dynamodb key is user_id and you are storing everything for that use against that key, high scores, inventory, purchases etc in a per user JSON object. This will lead to a high number of changes and reads from the same key. So you end up with a hot key. Better to create multiple tables and spread it out. Separate tables for Inventory, Purchases etc.
Event Driven: This mean Lambda executes code on an event. The event could be sourced from other AWS services, or could be something that you define on your own. You can also chain multiple events, and allow Lambda functions to trigger other Lambda functions. What kind of events are currently supported?
Custom event: JSON data defined by your application in the call to the AWS SDK or CLI
S3 Notifications: when an action is made on an Amazon S3 Bucket, the lambda function will be notified
DynamoDB change: when a line is added, changed, removed from DynamoDB, the lambda function will be notified
Kinesis: you can subscribe to a Kinesis stream
Cannot access resources currently within a VPC