rights reserved. S U M M I T Modern Application Development in the Cloud Danilo Poccia Principal Evangelist, Serverless AWS @danilop Iñigo Etxabe Founder & CTO Datik @ietxabe
rights reserved. S U M M I T Best practices for modern application development • Enable experimentation • Componentize applications • Update applications and infrastructure quickly • Model and provision application resources • Simplify infrastructure management • Improve application performance • Secure the entire application lifecycle
rights reserved. S U M M I T Best practices for modern application development • Enable experimentation by creating a culture of ownership • Componentize applications using microservices • Update applications and infrastructure quickly by automating the release pipeline • Model and provision application resources using infrastructure as code • Simplify infrastructure management with serverless technologies • Improve application performance by increasing observability • Secure the entire application lifecycle by automating security
rights reserved. S U M M I T AWS operational responsibility models On-Premises Cloud Less More Compute Virtual Machine EC2 Elastic Beanstalk AWS Lambda Fargate Databases MySQL MySQL on EC2 RDS MySQL RDS Aurora Aurora Serverless DynamoDB Storage Storage S3 Messaging ESBs Amazon MQ Kinesis SQS / SNS Analytics Hadoop Hadoop on EC2 EMR Elasticsearch Service Athena
rights reserved. S U M M I T • Transactions are SQL-ish • Query the Summary with SQL • “Records” are ION (JSON superset) documents • Journal is a cryptographically chained immutable ledger • Journal is also a database table • It’s serverless! Amazon Quantum Ledger Database Summary Journal Transactions
rights reserved. S U M M I T Integration options from AWS Amazon API Gateway Queues Simple Fully- managed Any volume Amazon SQS Pub/sub Simple Fully-managed Flexible Amazon SNS Orchestration Powerful Fully-managed Low code AWS Step Functions Connect Efficient Fully-managed Real-time Client-to-Service Messaging Orchestration
rights reserved. S U M M I T Serverless applications Services (anything) Changes in data state Requests to endpoints Changes in resource state Event source Function Node.js Python Java / JVM C# / PowerShell Go Ruby Runtime API
rights reserved. S U M M I T Anatomy of a Lambda function Handler() function Function to be executed upon invocation Event object Data sent during Lambda function Invocation Context object Methods available to interact with runtime information (request ID, log group, more) import json def lambda_handler(event, context): # TODO implement return { 'statusCode': 200, 'body': json.dumps('Hello World!') }
rights reserved. S U M M I T Lambda Layers Lets functions easily share code: Upload layer once, reference within any function Promote separation of responsibilities, lets developers iterate faster on writing business logic Built in support for secure sharing by ecosystem
rights reserved. S U M M I T Using Lambda Layers • Put common components in a ZIP file and upload it as a Lambda Layer • Layers are immutable and can be versioned to manage updates • When a version is deleted or permissions to use it are revoked, functions that used it previously will continue to work, but you won’t be able to create new ones • You can reference up to five layers, one of which can optionally be a custom runtime Lambda Layers arn:aws:lambda:region:accountId:layer:shared-lib Lambda Layers arn:aws:lambda:region:accountId:layer:shared-lib:2 Lambda Layers arn:aws:lambda:region:accountId:layer:shared-lib:3
rights reserved. S U M M I T Lambda Runtime API Bring any Linux compatible language runtime Powered by new Runtime API - Codifies the runtime calling conventions and integration points At launch, custom runtimes powering Ruby support in AWS Lambda, more runtimes from partners (like Erlang) Custom runtimes distributed as “layers” Rule Stack
rights reserved. S U M M I T AWS Serverless Application Model (SAM) AWSTemplateFormatVersion: '2010-09-09’ Transform: AWS::Serverless-2016-10-31 Resources: GetFunction: Type: AWS::Serverless::Function Properties: Handler: index.get Runtime: nodejs8.10 CodeUri: src/ Policies: - DynamoDBReadPolicy: TableName: !Ref MyTable Events: GetResource: Type: Api Properties: Path: /resource/{resourceId} Method: get MyTable: Type: AWS::Serverless::SimpleTable Just 20 lines to create: • Lambda function • IAM role • API Gateway • DynamoDB table O pen Source
rights reserved. S U M M I T SAM CLI sam init --name my-function --runtime python cd my-function/ sam build sam package --s3-bucket my-packages-bucket \ --output-template-file packaged.yaml sam deploy --template-file packaged.yaml \ --stack-name my-function-prod sam publish # To the AWS Serverless Application Repository
rights reserved. S U M M I T TweetSource: Type: AWS::Serverless::Application Properties: Location: ApplicationId: arn:aws:serverlessrepo:... SemanticVersion: 2.0.0 Parameters: TweetProcessorFunctionName: !Ref MyFunction SearchText: '#serverless - filter:nativeretweets' Nested apps to simplify solving recurring problems Standard Component Custom Business Logic Polling schedule (CloudWatch Events rule) trigger TwitterProcessor SearchCheckpoint TwitterSearchPoller Twitter Search API
rights reserved. S U M M I T AWS SAM Template Capabilities • Can mix in other non-SAM CloudFormation resources in the same template • i.e. Amazon S3, Amazon Kinesis, AWS Step Functions • Supports use of Parameters, Mappings, Outputs, etc • Supports Intrinsic Functions • Can use ImportValue (exceptions for RestApiId, Policies, StageName attributes) • YAML or JSON
rights reserved. S U M M I T Using AWS CloudFormation Export/ImportValue Outputs: WebServerSecurityGroup: Description: Security group for public web servers Value: Fn::GetAtt: - WebServerSecurityGroup - GroupId Export: Name: Fn::Sub: "${AWS::StackName}-SecurityGroupID” PublicSubnet: Description: Subnet for public web servers Value: Ref: PublicSubnet Export: Name: Fn::Sub: "${AWS::StackName}-SubnetID" Resources: WebServerInstance: Type: AWS::EC2::Instance Properties: InstanceType: t2.micro ImageId: ami-a1b23456 NetworkInterfaces: - GroupSet: - Fn::ImportValue: Fn::Sub: "${NetworkStackName}-SecurityGroupID" AssociatePublicIpAddress: 'true' DeviceIndex: '0' DeleteOnTermination: 'true' SubnetId: Fn::ImportValue: Fn::Sub: "${NetworkStackName}-SubnetID" Stack A – Network Stack B – Web Servers This is a Parameter
rights reserved. S U M M I T CodeDeploy – Lambda deployments in SAM templates Resources: GetFunction: Type: AWS::Serverless::Function Properties: AutoPublishAlias: live DeploymentPreference: Type: Canary10Percent10Minutes Alarms: - !Ref ErrorsAlarm - !Ref LatencyAlarm Hooks: PreTraffic: !Ref PreTrafficHookFunction PostTraffic: !Ref PostTrafficHookFunction Canary10Percent30Minutes Canary10Percent5Minutes Canary10Percent10Minutes Canary10Percent15Minutes Linear10PercentEvery10Minutes Linear10PercentEvery1Minute Linear10PercentEvery2Minutes Linear10PercentEvery3Minutes AllAtOnce
rights reserved. S U M M I T Lambda permissions model Fine grained security controls for both execution and invocation: Execution policies: • Define what AWS resources/API calls can this function access via IAM • Used in streaming invocations • E.g. “Lambda function A can read from DynamoDB table users” Function policies: • Used for sync and async invocations • E.g. “Actions on bucket X can invoke Lambda function Z” • Resource policies allow for cross account configst access
rights reserved. S U M M I T AWS SAM Policy Templates MyQueueFunction: Type: AWS::Serverless::Function Properties: ... Policies: # Gives permissions to poll an SQS Queue - SQSPollerPolicy: queueName: !Ref MyQueue ... MyQueue: Type: AWS::SQS::Queue ...
INSTALADOS START-UP DE EXITO MÁS DE 100 EMPRESAS DE TRANSPORTE HAN CONFIADO EN DATIK APORTAMOS VALOR DESDE EL AHORRO MÁS DE 10 MILLONES DE AHORRO PROPUESTOS A NUESTROS CLIENTES EXPERIENCIA INTERNACIONAL INFORMACIÓN DESDE MÁS DE 15 PAÍSES ESPECIALISTAS EN SEGURIDAD MÁS DE 180.00 HORAS DE VÍDEO ALMACENADOS Smart Information for a moving world! 15 DATIK EN CIFRAS...
OPERACIONAL MANTENIMIENTO DESCARGA REMOTA DEL TACÓGRAFO TICKETING WIFI A BORDO CLOUD PLATFORM COSTES OPERATIVOS SEGURIDAD OPERACIÓN SERVICIOS AL PASAJERO Smart Information for a moving world!
Monitores multimedia de exterior Aplicación móvil Monitores multimedia de interior y anunciador de audio El 360º de la información a pasajeros. • La aplicación móvil, los paneles multimedia para paradas, los paneles LED para el exterior de los vehículos y los anunciadores interiores informan al viajero en todo momento.
2014 2015 2016 2017 2018 2019 Primeros proyectos para trenes Primer empleado Transición hacia buses Irizar Group Gen 1 cloud Datik MX Datik UK Puntualidad e incidencias Conducción eficiente Video vigilancia Vehículos eléctricos Predictivo puertas y baterías Migration to AWS Gen 4 cloud Gen 2 cloud Gen 3 cloud Información a pasajeros Fatiga del conductor BREVE HISTORIA
2014 2015 2016 2017 2018 2019 GENERACIÓN 2 • Servidores balanceados Activo-Pasivo • Cambio a Angular.js y APIs REST • Alojador local • Arquitectura sencilla • Pocos componentes software • Desárrollo ágil • Desarrolladores de frontend y backend • Poco escalable y resiliente • Baja productividad (<50%) • Despliegues lentos • Gestión muy manual Gen 4 cloud Gen 2 cloud Gen 3 cloud • Único servidor en alojador local • Aplicación monolítica • Desarrollo basado en GWT Gen 1 cloud
y automatizables • Misma arquitectura y misma gestión en on-premises y en AWS • Ligero ahorro de costes (10%). Con reserva de instancias hasta 50% de ahorro • Alta productividad de la infraestructura (>80%) • Alta escalabilidad y auto-escalable • Alta resiliencia • Alta gestionabilidad (de 120 a 20 instancias) GENERACIÓN 4
a AWS ◦ Necesidad de disponer de un almacenamiento masivo ◦ Servicios gestionados ◦ Mayor autonomía y agilidad en la gestión de instancias • Por qué AWS: ◦ Líder del sector ◦ Disponibilidad de tutoriales, documentación y formación ◦ Red de empresas asociadas: consultores, asesoramiento • Logros obtenidos: ◦ Romper monolito e implementar arquitectura de micro servicios ◦ Pasar de 120 instancias (small-medium) EC2 a 20 (xlarge) ◦ 5 despliegues por semana (limitado por los recursos de desarrollo) ◦ Migración de Elastic Beanstalk a Kubernetes, reducción de costes del 10% (depende de uso) ◦ Con reserva de instancias, reducción de costes del 50% ◦ Arquitectura escalable, resiliente y optimizado en costes CONCLUSIONES
rights reserved. S U M M I T Positive Chat – Serverless architecture Amazon DynamoDB Amazon Cognito Amazon API Gateway WebSocket connection PositiveChat Lambda function Connections table Conversations table Topics table Web browser AWS Cloud S3 bucket for static assets (HTML, CSS, JS) Authentication Authorization To be implemented Amazon Comprehend Amazon Translate Amazon Rekognition To be implemented https://github.com/danilop/serverless-positive-chat D em o
rights reserved. S U M M I T $ wc -l positive-chat/app.js 326 positive-chat/app.js $ wc -l www/index.js 204 www/index.js backend + frontend ≃ 460 lines of code removing empty lines and comments D em o