You are on page 1of 71

Using Amazon Cognito and AWS Lambda

to replace a traditional mobile app backend


Bob Kinney
Senior Software Development Engineer
Amazon Cognito
Let's Build an App Notes App
Authen'cate users Store and share media
Manage users and
Store user-generated photos
identity providers
Media and share them

Your
Authorize access Mobile Deliver media
Securely access App Automatically detect mobile devices
cloud resources Deliver content quickly globally

Synchronize data Send push no'ca'ons


Sync user prefs
Bring users back to your app by sending
across devices
messages reliably

Analyze User Behavior Store shared data


Track active users, Store and query fast NoSQL data
engagement across users and devices

Track Reten'on Stream real-'me data


Manage funnels, Collect real-time clickstream logs
Campaign performances and take actions quickly
AWS Mobile
Authen'cate users Store and share media
Amazon Cognito Amazon S3
(Identity) Transfer Manager

Your
Authorize access Mobile Deliver media
AWS Identity and Amazon CloudFront
App
Access Management (Device Detection)

Synchronize data Send push no'ca'ons


Amazon Cognito Amazon SNS
(Sync) Mobile Push

Analyze User Behavior Store shared data


Amazon Mobile Amazon DynamoDB
Analytics (Object Mapper)

AWS Mobile SDK


Track Reten'on Stream real-'me data
Amazon Mobile Amazon Kinesis
Analytics (Recorder)
Authenticate users: Amazon Cognito
Amazon Cognito Overview

Identity Management Secure AWS Access Data Synchronization

Guest Guest
Your own
Auth

Manage authenticated Securely access AWS Synchronize users data


and guest users across services from mobile across devices and
identity providers devices and platforms platforms via the cloud
Identity Data Model
AWS Account

1:60

Iden0ty
Identity Pool: Pool of app users. Can be Pool
shared across apps. 1:n

Identity: An individual user. Consistent Iden0ty


Iden0ty
Iden0ty
across identity providers. Can be a guest
user. 0:n

Login: Identifier in a login provider. Dataset


Dataset
Login
Getting Started with Amazon Cognito in Three Steps

Sign up for an AWS Account and login to the AWS Management


Console

Create identitypool for authenticated and unauthenticated


users in the AWS Management Console

Download and integrate the AWS Mobile SDK and store


and sync user data in a dataset
Amazon Cognito Authflow
Login
Amazon Cognito Authflow
Amazon Cognito Authflow

AssumeRoleWithWebIden0ty
Amazon Cognito Authflow

AssumeRoleWithWebIden0ty
Amazon Cognito Authflow

AssumeRoleWithWebIden0ty
All this is handled by the creden0als provider.
Unauthenticated Identities
Transitioning to Authenticated
Linking Logins
Merging Identities
Authorize access:
Amazon Cognito + AWS IAM + Fine-grained access control
AWS IAM Roles
Mechanism for delivering temporary credentials
Has two policies
Trust (who can assume role)
Access (what resources the role can access)
3 types roles
AWS Service Roles
Cross-Account Access
Identity Provider Access
Roles for Amazon Cognito
2 roles
Authenticated users
Unauthenticated users
Access to Cognito Sync and Mobile Analytics
Can be modified to support access to any AWS service
Supports policy variables for fine-grained access control
Policy Variables Amazon S3
<!-- Write/Read/Delete individual items -->
{
"Effect":"Allow",
"Action":["s3:PutObject","s3:GetObject","s3:DeleteObject"],
"Resource":"arn:aws:s3:::BUCKET_NAME/${cognito-identity.amazonaws.com:sub}/*"
}

<!-- List these items -->


{
"Effect":"Allow",
"Action":"s3:ListBucket",
"Resource":"arn:aws:s3:::BUCKET_NAME",
"Condition":{"StringLike":{"s3:prefix":"${cognito-identity.amazonaws.com:sub}/"}}
}
Policy Variables Amazon S3
<!-- Write/Read/Delete individual items -->
{
"Effect":"Allow",
"Action":["s3:PutObject","s3:GetObject","s3:DeleteObject"],
"Resource":"arn:aws:s3:::BUCKET_NAME/${cognito-identity.amazonaws.com:sub}/*"
}

<!-- List these items -->


{ Will be replaced by the iden0ty ID
"Effect":"Allow",
"Action":"s3:ListBucket",
"Resource":"arn:aws:s3:::BUCKET_NAME",
"Condition":{"StringLike":{"s3:prefix":"${cognito-identity.amazonaws.com:sub}/"}}
}
Policy Variables Amazon DynamoDB

<! DynamoDB policy -->


{
"Effect": "Allow",
"Action": [ "dynamodb:GetItem", "dynamodb:Query",
"dynamodb:PutItem", "dynamodb:UpdateItem" ],
"Resource": "arn:aws:dynamodb:REGION:12345678:table/UserData",
"Condition": {
"ForAllValues:StringEquals": {
"dynamodb:LeadingKeys": "${cognito-identity.amazonaws.com:sub}"
}
}
}
Policy Variables Amazon DynamoDB

<! DynamoDB policy -->


{
"Effect": "Allow",
"Action": [ "dynamodb:GetItem", "dynamodb:Query",
"dynamodb:PutItem", "dynamodb:UpdateItem" ],
"Resource": "arn:aws:dynamodb:REGION:12345678:table/UserData",
"Condition": {
"ForAllValues:StringEquals": {
"dynamodb:LeadingKeys": "${cognito-identity.amazonaws.com:sub}"
}
}
}
Will be replaced by the iden0ty ID
Sync App Data: Amazon Cognito
Amazon Cognito Sync Features
Store App Data, Preferences, and State
Save app and user data to the cloud.

Work Offline
Data persisted to local storage first. Local data is Identity Pool

available regardless of connectivity.

No Backend
Simple client SDK eliminates need for server side
code.
User
Data
Sync data model
AWS Account
Identity Pool: Pool of app users. Can be 1:60
shared across apps. Iden0ty
Pool
Identity: An individual user. Consistent
1:n
across identity providers. Can be a guest
Iden0ty
user. Iden0ty
Iden0ty

Dataset: Per user grouping of data. The 1:20


most granular level of sync. Up to 1 MB.
Dataset
Dataset
Record: Key-value pair. Dataset

1:1024

Dataset
Dataset
Record
Amazon Cognito Synchronization

User
Data
Amazon Cognito Synchronization

User
Data
Amazon Cognito Synchronization

onConflict() {
User
Data
}
Amazon Cognito Synchronization

User
Data
Amazon Cognito Synchronization

User User
Data Data
Amazon Cognito Sync Additional Features
Push Synchronization
Integrate with Amazon SNS receive mobile push notifications when data changes.

Amazon Cognito Streams


Integrate with Amazon Kinesis to get real time and/or bulk exports of your data.
Backup to S3 or import into Amazon Redshift for analytics.

Amazon Cognito Events


Integrate with AWS Lambda to Trigger a Lambda function on synchronization. Use
for verification and/or modification of data before it's stored in Amazon Cognito.
Analyze User Behavior: Amazon Mobile Analytics
Amazon Mobile Analytics
Easily collect, visualize, and understand your app usage data at scale

Fast Scalable and Generous Own Your Data


Free Tier

Focus on metrics that Scale to billions of events Data collected are not
ma@er. Usage reports per day from millions of shared, aggregated, or
available within 60 minutes users. reused.
of receiving data from an
app.
Key Business Metrics
(with one line of code)
1. Monthly Ac0ve Users (MAU)
2. Daily Ac0ve Users (DAU)
3. New Users
4. Daily Sessions
5. S0cky Factor
6. 1-Day Reten0on
7. Avg. Revenue per DAU
8. Daily Paying Users
9. Avg. Paying DAU
Track Reten'on

User reten0on is a key indicator
to judge the outcome of a
marke0ng campaign, new feature
introduc0on, UX changes, app
updates, etc.

Mobile Analy0cs provide four
charts to track daily or weekly
rate of returning users, aYer rst
use of the app.
Track Custom Events
Get behavioral insights into app-specic ac0ons
that your users take.

Reports provide a view of how oYen custom


events occur. You can add further context with
A@ributes and Metrics, to each custom event.

Examples

Track the number of Number of songs played,


Likes/Shares, per ar0cle, per user session, in a
in a news app music app

In-app item popularity in Understand player


a shopping app abort rates per level,
in a game
Getting Started with Mobile Analytics in three steps

Sign up for an AWS Account and create or use an existing


Cognito ID in the AWS Management Console

Download and integrate the AWS Mobile SDK with one


line of code (Android/FireOS, iOS)

View engagement and session activity reports in the


AWS Management Console within minutes
Store and share media: Amazon S3
Amazon S3 Connector: Transfer Manager

Mul0part upload media (photos, videos, audio)


Fault tolerant download (e.g., assets)
No backend required
S3 Connector Automa0c retries
Pause, resume, cancel func0ons
Op0mized for na0ve OS
Deliver Media: Amazon CloudFront
How Amazon CloudFront Works

Get content Get content


OR

Content Content
Amazon S3 Custom
User requests
Edge location
(cache + network optimizations) Origin
Leverage AWS Edge Locations
London (2)
Sea@le New York (3)
South Bend Amsterdam (3)
Newark Dublin Stockholm
Hayward
Seoul Tokyo (2)
Palo Alto Warsaw

San Jose Paris (2)


Marseille Frankfurt (3)

Chennai
Ashburn (3) Milan
Atlanta Madrid Osaka
Los Angeles (2)
Jacksonville Taipei
Dallas (2) Hong Kong (2)
Mumbai
St.Louis Manila

Miami Singapore (2)

Rio de Janeiro
Sydney
Sao Paulo
Melbourne
Store Shared Data: Amazon DynamoDB
Amazon DynamoDB Connector: Object Mapper
High Scores
Simplies access to Amazon DynamoDB Joe 1500
in your app
Anna 800

Map client-side classes to Amazon Bob 750
DynamoDB tables

Removes the need to transform objects
into tables and vice versa Joe Anna Bob
Send Push Notifications: Amazon SNS Mobile Push
SNS publishes notifications on your behalf using the credentials you
obtain from each push service.

Apple APNS

Amazon SNS
Mobile Push
Google GCM

Amazon ADM
SNS encapsulates each device token inside an Amazon Resource
Name (ARN) endpoint.
ARN 1
Token A

Apple APNS
ARN 2
Token B
Amazon SNS
Mobile Push
Google GCM
ARN 3
Token C

Amazon ADM
Once you register a device with SNS, SNS proactively consumes
feedback about the corresponding token from the push service.

You can access


Token the underlying
Feedback
tokens and
feedback, but you
Amazon SNS Token dont have to do
Cloud App
Mobile Push Registra'on so in order to use
SNS.
ARN endpoints remain stable, even if the underlying token is
swapped or disabled.
ARN 1
Token A

Token X
Apple APNS
ARN 2
Token B
Amazon SNS Token Y
Mobile Push
Google GCM
ARN 3
Token C

Amazon ADM
You can publish unique messages to individual devices, or
broadcast identical messages to many devices at once.

Direct Publishing Broadcast with SNS Topics

Publish

Publish Publish

Publish
Grouping users by SNS Topic
Geography Activity Product
US West Coast Daily Ac0ves Flapping Bird Rio

Interest Tier Segment


49ers Premium Top 100 Players
Run Your Own Backend: AWS Lambda
Event-Driven Compute in the Cloud
Launched last November at re:Invent
Lambda functions: Stateless, request-driven code execution
Triggered by events in other services:
PUT to an Amazon S3 bucket
Write to an Amazon DynamoDB table
Record in an Amazon Kinesis stream
Makes it easy to
Transform data as it reaches the cloud
Perform data-driven auditing, analysis, and notification
Kick off workflows
Data Triggers: Amazon S3

Original image Thumbnailed image

1 3

Amazon S3 Bucket Events AWS Lambda


Data Triggers: Amazon DynamoDB

Update another table

Amazon DynamoDB AWS Lambda


Table and Stream
Send SNS no0ca0ons
Mobile Compute: Building Backends with Lambda

Launching Mobile Compute


Request/response
AWS Mobile SDK
Easy Personalization
for devices
for end users

Mobile App AWS Lambda


Easy Personalization

Which end user is this?

?
Which device is she using?

?
Calling Lambda Functions
Call from mobile or web apps
Wait for a response or send an event and continue
AWS SDK, AWS Mobile SDK, REST API, CLI
Send events from Amazon S3 or SNS:
One event per Lambda invocation, 3 attempts
Process DynamoDB changes or Amazon Kinesis records as events:
Ordered model with multiple records per event
Unlimited retries (until data expires)
Writing Lambda Functions
The Basics
Stock node.js
AWS SDK comes built in and ready to use
Lambda handles inbound traffic
Stateless
Use S3, DynamoDB, or other Internet storage for persistent data
Dont expect affinity to the infrastructure (you cant log in to the box)
Familiar
Use processes, threads, /tmp, sockets,
Bring your own libraries, even native ones
No Infrastructure to Manage

Focus on business logic,


not infrastructure
Upload your code; AWS
Lambda handles
Capacity
Scaling
Deployment
Monitoring
Logging
Web service front end
Security patching
Automatic Scaling

Lambda scales to match


the event rate
Dont worry about over
or under provisioning
Pay only for what you
use
New app or successful
app, Lambda matches
your scale
Bring your own code

Create threads and


processes, run batch
scripts or other
executables, and read/
write files in /tmp.
Include any library with
your Lambda function
code, even native
libraries.
Other Event Sources for Lambda
Amazon Simple Notification Service (SNS)
Easily target, route, transform, filter, or audit messages
Trigger an AWS Lambda function by sending it notifications
Turn Amazon CloudWatch alarms into actions

SNS Lambda Func0on


Other Event Sources for Lambda
Amazon Cognito
Before: Easily synchronize user data across their devices
Now: Take action when that data changes
Examples: Verify and respond to game state updates

Cognito Lambda Func0on


Capture Real-time Data: Amazon Kinesis
Amazon Kinesis Connector: Kinesis Recorder

Batching of requests
No0ca0on when batch size is reached
Handles any arbitrary data
Kinesis
Connector
Authen'cate users Store and share media
Amazon Cognito Amazon S3
(Identity) Transfer Manager

Your
Authorize access Mobile Deliver media
AWS Identity and Amazon CloudFront
App
Access Management (Device Detection)

Synchronize data Send push no'ca'ons


Amazon Cognito Amazon SNS
(Sync) Mobile Push

Analyze User Behavior Store shared data


Amazon Mobile Amazon DynamoDB
Analytics (Object Mapper)

AWS Mobile SDK


Track Reten'on Stream real-'me data
Amazon Mobile Amazon Kinesis
Analytics (Recorder)
Connect
AWS Mobile Home
http://aws.amazon.com/mobile
AWS Mobile Blog
http://mobile.awsblog.com
Twitter
@awsformobile
Forums
http://forums.aws.amazon.com

StackOverflow
http://stackoverflow.com/tags/amazon-web-services

GitHub
http://github.com/aws/
http://github.com/awslabs/

You might also like