AWS re:Invent 2016: Deep-Dive: Native, Hybrid and Web patterns with Serverless and AWS Mobile...

52
© 2016, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Richard Threlkeld, AWS 12/1/2016 Real-World Deep Dive: Native, Hybrid, and Web with Serverless and AWS Mobile Services MBL404

Transcript of AWS re:Invent 2016: Deep-Dive: Native, Hybrid and Web patterns with Serverless and AWS Mobile...

© 2016, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

Richard Threlkeld, AWS

12/1/2016

Real-World Deep Dive: Native,

Hybrid, and Web with Serverless

and AWS Mobile Services

MBL404

Agenda

• Common Concerns

• Overlapping Patterns

• Emerging Patterns

• Platforms

• Native Apps

• Hybrid Apps

• Mobile Web

Great Mobile Apps Run on AWS

Table Stakes

- AuthN/AuthZ

- Fine-grained access control

- Static asset download/refresh

- File uploads (images, video, etc.)

- User/system notifications

- API interaction (GET, POST, etc.)- REST, GraphQL, JSON-API

- Async communications

- Optimistic updates

- State- User preferences (cross-device)

- Systems of record/tables

- Mutability

- Analytics- Session information

- Custom events

Architecture Concerns

1. System

1. Scale

2. Costs

3. Security

2. App

1. Performance

• Network latency

• UX

• CPU

• Battery

2. Usability

• Accessibility

3. Security

4. State

Related:Development team speed

New-joiner contribution

Shared skills

Architecture: System

Token exchange

Session storage

Dataset sync

Amazon

CloudFront

Amazon

S3 Amazon

DynamoDB

Amazon

RDS

Amazon

Mobile Analytics

Amazon

SNS

Amazon

Cognito

Amazon API

Gateway

virtual private cloud

AWS

Lambda

Amazon

EC2/Amazon

ECSSession data

Custom event attributes

Custom metrics

Routing

API Negotiation

Static content

Images

Video

Binary data

Uploads

Granular Auth Controls

IAM Roles

• Fine-grained API access

• Enterprise SAML Federation

User Pool Lambda Triggers

Cognito Policy Variables

API Gateway Authorizers

• User Pool Authorizer

• Custom Authorizer

Takeaway:

Sort out Identity and Auth;

everything else gets easier

Amazon Cognito Identity and AWS Identity and Access

Management Variables

Amazon Cognito Points to Remember

Unique Identity

- DDB indexes

Short-Term Credentials

• Credentials object triple

• Token, access key, secret key

• Pass to AWS SDKs

• Sigv4 auto-signing

Amazon Cognito User Pools

- SRP

- Passwords never travel over wire

- Verifier calculated and stored

http://srp.stanford.edu/ndss.html

- Developer-only attributes

- API Gateway back-end calls

- Don’t send outside infra

Native Apps

Background vs. Real-time

https://d0.awsstatic.com/whitepapers/lambda-architecure-on-for-batch-aws.pdf

Analytics Lifecycle

SDK/REST API

(Android, iOS, JavaScript, Unity, Xamarin)Amazon

Mobile Analytics

Daily/Monthly Active Users

Sessions

Sticky Factor

In-app Revenue

Lifetime Value (LTV)

Retention

…. and more

(Pre-defined metrics with a few lines of code)

Amazon

S3Amazon

Redshift

Amazon

DynamoDB

Amazon

EMR

Amazon Machine

Learning

Amazon

API

Gateway

Amazon

Elasticsearch

Service

Amazon

RDS

Submit

Query

Assume a Role with Cognito

Create an instance of your

Mobile Analytics Application

Create->Record->Submit Events

Submitting Events: Android

Mutations

API

Gateway

AWS

Lambda

API Gateway-Generated SDK

- Signed Requests

Amazon Cognito:

User Pools + Identity Amazon

Kinesis

Amazon

DynamoDB

POST

GET

Service

Proxy

arn:aws:iam::ACCOUNT:*:user/*

API Gateway-Generated SDK

Provider

(APNS, GCM, MPNS,…)

Token Request

Amazon

SNS

SNS Platform Application

“Token”

Platform Endpoint

- Upload Certificates, API Keys, etc.

Upload Token

- AKA “Create Platform Endpoint”

- Client code in App Delegate, etc.

Client Push Token Management

Fine-grained Control

Send to Mobile Analytics

Sync datasets across devices

Add token to SNS

Add email/phone to SNS

Provider

(APNS, GCM, MPNS,…)

Amazon

SNS

Platform Application

“Token”

Platform Endpoint

Upload Token

- AKA “Create Platform Endpoint”

Add Email to Topic

Add Phone to Topic

Alternative Options

Amazon API

Gateway

Amazon

Cognito

User Pool

AWS

Lambda

Topic

Workflow Triggers

/myapi/register

Custom Authorizers

State Management

Cognito Datasets

• onSuccess()

• onFailure()

• onConflict()

• onDatasetDeleted()

• onDatasetsMerged()

State and User Preferences – Amazon Cognito Option

Amazon

Cognito

<k1,v1>

<kn,vn>

Administrator

AWS

Lambda

Amazon

Kinesis

Cognito Events

Cognito Streams

Push

Synchronization

DynamoDB

Access via Cognito assigned Role

Databases

Relational

Create interfaces

- REST/GraphQL/JSON-API

- API Gateway, ELB/ALB- Common: ASG behind ELB

using RDS Multi-AZ

- Platform HTTP calls- iOS: NSURLConnection,

NSURLSession, etc.

- Android: HttpClient(), HttpGet(),etc.

State & User Preferences – DynamoDB Option

Administrator

Push Notification

AWS

LambdaAmazon

Kinesis

Hash String Map

Hash String Map

Hash String Map

Amazon

DynamoDB

Amazon

SNS

Trigger

Amazon

Aurora

Network Management

Polling & connection setup are expensive

- Battery, CPU

- Wake devices via push then choose medium

- API Gateway GET/POST, Long Polling, Websocket, HTTP/2,

Amazon Cognito Sync, MQTT, etc.

Aggregate inbound/outbound messages

Re-use connections where possible

Xhr, Websocket,

etc.

Optional user

notification

Websockets

Application

Load Balancing

Amazon

ECS/EC2

AWS IoT

var connection = new WebSocket('ws://alb-XXXX.us-

east-1.elb.amazonaws.com:443/Livestream');

wss://<endpoint>.iot.<region>.amazonaws.com/mqtt

Websocket over MQTT

- Subscribe

- Publish

Hybrid Apps

Cordova

Formerly known as PhoneGap

Create mobile apps with HTML, CSS, JavaScript

Extended via plugins

WebView intermediary for rendering/communicating with platform

Ionic• UI framework built on Cordova using

Angular

Using AWS Services from Cordova

1. Download and include aws-sdk.min.js.

2. Reference in Cordova’s index.html:

3. Grant AWS endpoints access:

4. Call AWS SDK functions from index.js:

• Start with Amazon Cognito in onDevice

Cognito and Cordova

Push Notifications and Cordova

Yes you can initiate SNS-based Push to Cordova!

ANDROID:

$cordova plugin add phonegap-plugin-push –variable SENDER_ID="YOURID"

iOS:

$cordova plugin add phonegap-plugin-push

React Native

AWS Published SDK available:

• AWSLABS https://github.com/awslabs/aws-sdk-react-

native

Can easily add in AWS Native SDKs

React Native with AWS SDKs

1. Import Native AWS SDK & Bridging Modules

2. Create Singleton

React Native with AWS SDKs

3. Initialize in JavaScript

3. Add/Invoke methods

Demo: React Native with

Websockets using AWS IoT

Mobile Web

SDK Generation

- Native/Hybrid have SDKs bundled

- JavaScript SDK

- Builder: https://sdk.amazonaws.com/builder/js/

- Can use for Cordova too

- Use w/ Frameworks & tooling

- Deferred/selective loading

Common Mobile Web Requirements

• Reactive design for different form factors

• Non-blocking HTTP actions

• Auto refreshing

• State management

• Routing

• List Restaurants, view Menu/Orders

• Actions

• Place/Delete Orders

• ES6 syntax

Mobile Web by Example• React/Angular

• Component-based design, minimize round-trips

• State updates and dynamic page refresh

• React Router

• /restaurants, /menu:id, /order:id

• Babel• ES6 compiler

• Axios

• Promise-based XHR abstraction

• Materialize

• Reactive UX

• Based on Material Design

• Session Storage

• Keep track of latest operations

Angular + API Gateway

Toolbox

Webpack

- Code split on API Gateway

resources

- deferred loading, bundling

React Router

• Match routes with Services

- /Login Cognito

- Alternative: API Gateway

or ALB

- /* API Gateway {proxy+}

Infrastructure matters too!

- Core rendering as needed

- Homepage code shouldn’t block

login page or crypto libs

- Async load state when necessary

- User interactions

- Pagination

- Lazy load extra branches

Web Server Configuration

• S3 bucket

• Enable “Static Website” on bucket properties• Creates: BUCKETNAME.s3-website-us-east-1.amazonaws.com (regions vary)

• Add access policy to bucket

• Browser GET = s3:GetObject

• Ensure CORS is enabled for XHR calls to API Gateway

Serverless Mobile Web Zoom-In

Amazon

CloudFront

Amazon

S3

API

Gateway

Mobile apps

1. Optional

CDN hosting

of content

2. Webpage loaded with

Script references

3. Browser downloads

critical libs first, lazy

load others

5. Script libraries use XHR

browser requests to API

Gateway stage endpoints

4. Cognito AuthN/AuthZ:

User Pools + Identity

Serverless

Express

wrapper

Demo: Serverless Mobile Web

Mobile Web Analytics

Native

Interrogates app lifecycle

- Background queue filled with

session and custom events

- Session events batched & sentBackgrounded time > AWSValueSessionResumeDelay

- Custom events sent anytime

- Best practice: use

onPause, onStop,

onResume

SDK Session Management

Web

Configure default session length

Force event submission anytime

Window.localStorage ensures

persistence through browser/tab

exiting

Enhancing JavaScript Sessions

Debate: Apples vs. oranges?

Modern browsers offer visibilitychange() event:https://developer.mozilla.org/en-US/docs/Web/Events/visibilitychange

extendSession()

stopSession()

Mobile Engagement

Emerging consumer pattern:

1. Mobile users making requests

2. Mobile users fulfilling requests

Needs:

1. Order tracking

2. Notifications (two-way)

3. SLA management

Emerging Pattern: Request Tracking

Amazon API

Gateway

Amazon

SQS

Amazon

SNS

Amazon

DynamoDB

AWS

Lambda

Amazon

SQSLambda #1

TimeStamp CognitoID Acknowledged

DelaySeconds =

15 mins

Lambda #2SLA:TimeStamp+30min

= expTimeStamp

remaining =

expTimeStamp – Time.Now()

IF remaining >0 {

//Resubmit to SQS w/

//visibility timeout remaining

}ELSE{

//Business escalation logic

}

Poll for new

messages

Amazon

Mobile Analytics

Final Thoughts

Think Big & apply known patterns to new industries

Tools designed for one domain can be used in others

You can optimize and enhance on all platforms

- Hire to build a good culture

Focus on client & infrastructure end-to-end interactions

Thank you!

Remember to complete

your evaluations!