SlideShare a Scribd company logo
AWS Lambda in Swift
Andrea Scuderi - Lead iOS @ Shpock

@andreascuderi13
NSLondon - 3rd of December 2020
AWS Lambda in Swift
Agenda
• What is a Lambda?

• How can I code a Lambda with Swift?


• Development Tools


• Building Tools


• Deployment Tools


• Introduction to a Serverless REST API in Swift
What is a Lambda?
HW, VM, Container vs Serverless
What are the advantages of it?
λServers Virtual Machines Containers
Function as a Service


FaaS
Abstraction LevelHW SW
HW, VM, Container vs Serverless
What are the advantages of it?
λServers Virtual Machines Containers
Function as a Service


FaaS
Deployment SpeedDays μs (micro-seconds)
HW, VM, Container vs Serverless
What are the advantages of it?
λServers Virtual Machines Containers
Function as a Service


FaaS
ScalabilitySPoF


(Single Point of Failure)
Auto-Scaling
HW, VM, Container vs Serverless
What are the advantages of it?
λServers Virtual Machines Containers
Function as a Service


FaaS
Business ModelPay Upfront Pay Per Use
Monolithic vs Microservices
Architecture
User
Interface
Business
Logic
Data
Access
Layer
DB
User
Interface
Micro


service Micro


service
Micro


service
Micro


service
Micro


service
DB DB DB
Monolithic


• Simpler


• Lower Latency


• Higher Throughput
Microservice


• Loose coupling


• More reliable


• Less resource


• Easier scaling


• More Agile


• High complexity


• Less communication
AWS Serverless Landscape
• COMPUTE: Lambda


• STORAGE: S3, EFS


• DATA STORE: DynamoDB, Aurora


• API PROXY: API Gateway


• MESSAGING: SNS, SQS, Kinesis


• ORCHESTRATION: Step Functions


• MONITORING: CloudTrail


• SECURITY: IAM, Cognito
AWS Lambda
Function as a Service (FaaS)
• Serverless


• Managed Micro-Service


• Event driven


• Stateless


• Auto-Scaling


• Pay per use (Sub-second metering)


• Logging and monitoring is included


• Code container


• Multi-Language support


• Can run Linux compatible language runtime via Runtime API
© 2019, Amazon Web Services, Inc. or its affiliates. All 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
C# / F# / PowerShell
Go
Ruby
Runtime API
How can I code a Lambda with Swift?
Hello World
Project setup
> mkdir HelloWorldLambd
a

> cd HelloWorldLambd
a

> swift package init --type=executabl
e

> xed Package.swif
t
Hello World
Update Package.swift
import PackageDescription


let package = Package(


name: "HelloWorldLambda",


products: [




.executable(name: "HelloWorldLambda", targets: ["HelloWorldLambda"]),


],


dependencies: [


.package(url: "https://github.com/swift-server/swift-aws-lambda-runtime.git", from: "0.1.0"),


],


targets: [


.target(


name: "HelloWorldLambda",


dependencies: [


.product(name: "AWSLambdaRuntime", package: "swift-aws-lambda-runtime"),


]),


.testTarget(


name: "HelloWorldLambdaTests",


dependencies: ["HelloWorldLambda"]),


]


)
Hello World
Add your code to main.swift
import AWSLambdaRuntime


struct Request: Codable {


let name: String


}


struct Response: Codable {


let message: String


}


Lambda.run { (context, request: Request, callback: @escaping (Result<Response, Error>) -> Void) in




let response = Response(message: "Hello!: (request.name)")




callback(.success(response))


}
Hello World
Run your Lambda locally
> export LOCAL_LAMBDA_SERVER_ENABLED=tru
e

> swift run HelloWorldLambd
a

> curl --location --request POST 'http://localhost:7000/invoke'


--header 'Content-Type: text/plain'


--data-raw '
{

"name": "Andrea
"

}
'

{"message":"Hello!: Andrea"
}
Apple - Swift NIO
https://github.com/apple/swift-nio
• SwiftNIO - NIO == non-blocking I/O


• cross-platform


• asynchronous event-driven network application framework


• for rapid development of maintainable high performance protocol servers &
clients.


• Low level framework


• use-cases: where"thread-per-connection" model of concurrency is inef
f
icient or
untenable.


• Is the fundamental part of most of the Server Side Swift frameworks
Apple - Swift NIO
https://github.com/apple/swift-nio
• EventLoop:


• The event loop is an object that waits for events (usually I/O) to happen and then
f
ires
some kind of callback when they do.


• EventLoopFuture<T>:


• manage operations that complete asynchronously.


• a container for the return value of a function that will be populated at some time in the
future


• EventLoopPromise<T>:


• Each EventLoopFuture<T> has a corresponding EventLoopPromise<T>, which is the object
that the result will be put into. When the promise is succeeded, the future will be ful
f
illed.
HTTPSLambda
Swift NIO + AsyncHTTPClient
import AWSLambdaRuntime


import AsyncHTTPClient


import NIO


struct Event: Codable {


let url: String


}


struct Response: Codable {


let content: String


}


struct HTTPSLambda: EventLoopLambdaHandler {




// MARK: - In & Out


typealias In = Event


typealias Out = Response




// MARK: - Lambda Handler


func handle(context: Lambda.Context, event: Event) -> EventLoopFuture<Response> {




guard let request = try? HTTPClient.Request(url: event.url) else {


return context.eventLoop.makeFailedFuture(LambdaError.invalidRequest)


}




return httpClient.execute(request: request, deadline: nil)


.flatMapThrowing { (response) throws -> String in


guard let body: ByteBuffer = response.body,


let value: String = body.getString(at: 0, length: body.readableBytes) else {


throw LambdaError.invalidContent


}


return value


}.map { content -> Response in


return Response(content: content)


}


}
> git clone https://github.com/Andrea-Scuderi/HelloWorldLambda
HTTPSLambda
Swift NIO + AsyncHTTPClient
// MARK: - HTTPClient Configuration


let httpClient: HTTPClient




static let lambdaRuntimeTimeout: TimeAmount = .seconds(30)




static let timeout = HTTPClient.Configuration.Timeout(


connect: lambdaRuntimeTimeout,


read: lambdaRuntimeTimeout


)




static let configuration = HTTPClient.Configuration(timeout: timeout)


// MARK: - LambdaError


enum LambdaError: Error {


case invalidRequest


case invalidContent


}




// MARK: - Init


init(context: Lambda.InitializationContext) {




// Use HTTPClient on the same EventLoop used by AWSLambda


self.httpClient = HTTPClient(


eventLoopGroupProvider: .shared(context.eventLoop),


configuration: HTTPSLambda.configuration


)


}


}


Lambda.run(HTTPSLambda.init)
AWS Lambda Swift Runtime
Lambda Architecture & Building pipeline
User Lambda Swift Code
AWS Lambda Swift Runtime
bootstrap
Swift Libraries for Runtime
swift:5.3-amazonlinux2
❌
To run the Lambda on AWS we need:


- build the binary for Amazon Linux 2


- copy all the Swift runtime libraries required
in the zip bundle
AWS Lambda in Swift
Development Tools
Code
Build+
Deploy
Swift Amazon Linux 2
Swift 5.x
Build AWS Lambda in Swift
• Requirements: Docker Desktop, Bash


> git clone https://github.com/Andrea-Scuderi/HelloWorldLambd
a

> cd HelloWorldLambd
a

> ./scripts/build-and-package.sh HelloWorldLambd
a

> ls .build/lambda/HelloWorldLambda/lambda.zi
p
swift:5.3-amazonlinux2
AWS Lambda Deployment tools
Pick your favourite…, mine is Serverless framework
• AWS Management Console (manual upload)


• AWS CLI - Command line interface (Scripting)


• AWS CloudFormation: Infrastructure as code


• AWS SAM Serverless Application Model: deployment tool


• Serverless: Cloud Agnostic Multiplatform deployment tool


• ….
Deploy AWS Lambda in Swift
After you have created your account on AWS, you need to install:


• AWS CLI: https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2-
mac.html


• Serverless framework:


> curl -o- -L https://slss.io/install | bas
h

> ./scripts/serverless-deploy.s
h
Test the Deployment
CloudFormation
• Cleanup


> ./scripts/serverless-remove.sh HelloWorldLambd
a
Introduction to a Serverless REST API in Swift
REST API
AWS Serverless Architecture
• API Gateway


• Lambda


• Create


• Read


• Update


• Delete


• List


• DynamoDB
AWS Serverless Swift API Template
Full working Demo


• https://github.com/swift-sprinter/aws-serverless-swift-api-template


• `Product` demo API in Swift


• Use SOTO Library (AWS SDK for Swift)


• YAML template for Serverless


• Deployments Scripts
Question Time
Tanks for listening
• Follow me!


• Twitter: @andreascuderi13


• Linkedin: https://www.linkedin.com/in/andreascuderi/


• Medium: https://medium.com/@andreascuderi73
Ad

More Related Content

What's hot (17)

DevOps Days Tel Aviv - Serverless Architecture
DevOps Days Tel Aviv - Serverless ArchitectureDevOps Days Tel Aviv - Serverless Architecture
DevOps Days Tel Aviv - Serverless Architecture
Antons Kranga
 
JavaDay Lviv: Serverless Archtiectures
JavaDay Lviv: Serverless ArchtiecturesJavaDay Lviv: Serverless Archtiectures
JavaDay Lviv: Serverless Archtiectures
Antons Kranga
 
Patterns and practices for real-world event-driven microservices
Patterns and practices for real-world event-driven microservicesPatterns and practices for real-world event-driven microservices
Patterns and practices for real-world event-driven microservices
Rachel Reese
 
AWS Primer and Quickstart
AWS Primer and QuickstartAWS Primer and Quickstart
AWS Primer and Quickstart
Manish Pandit
 
Serverless cat detector workshop - cloudyna 2017 (16.12.2017)
Serverless cat detector   workshop - cloudyna 2017 (16.12.2017)Serverless cat detector   workshop - cloudyna 2017 (16.12.2017)
Serverless cat detector workshop - cloudyna 2017 (16.12.2017)
Paweł Pikuła
 
Serverless
ServerlessServerless
Serverless
Daniel Cottone
 
Docker on AWS - the Right Way
Docker on AWS - the Right WayDocker on AWS - the Right Way
Docker on AWS - the Right Way
AllCloud
 
Serverless APIs with JavaScript - Matt Searle - ChocPanda
Serverless APIs with JavaScript - Matt Searle - ChocPandaServerless APIs with JavaScript - Matt Searle - ChocPanda
Serverless APIs with JavaScript - Matt Searle - ChocPanda
Paul Dykes
 
2016 - Serverless Microservices on AWS with API Gateway and Lambda
2016 - Serverless Microservices on AWS with API Gateway and Lambda2016 - Serverless Microservices on AWS with API Gateway and Lambda
2016 - Serverless Microservices on AWS with API Gateway and Lambda
devopsdaysaustin
 
Kubernetes on AWS
Kubernetes on AWSKubernetes on AWS
Kubernetes on AWS
Grant Ellis
 
Streams and serverless at DAZN
Streams and serverless at DAZNStreams and serverless at DAZN
Streams and serverless at DAZN
Yan Cui
 
ApacheCon NA - Apache Camel K: connect your Knative serverless applications w...
ApacheCon NA - Apache Camel K: connect your Knative serverless applications w...ApacheCon NA - Apache Camel K: connect your Knative serverless applications w...
ApacheCon NA - Apache Camel K: connect your Knative serverless applications w...
Nicola Ferraro
 
2020.02.15 DelEx - CI/CD in AWS Cloud
2020.02.15 DelEx - CI/CD in AWS Cloud2020.02.15 DelEx - CI/CD in AWS Cloud
2020.02.15 DelEx - CI/CD in AWS Cloud
Peter Salnikov
 
Open stack ocata summit enabling aws lambda-like functionality with openstac...
Open stack ocata summit  enabling aws lambda-like functionality with openstac...Open stack ocata summit  enabling aws lambda-like functionality with openstac...
Open stack ocata summit enabling aws lambda-like functionality with openstac...
Shaun Murakami
 
ApacheCon NA - Apache Camel K: a cloud-native integration platform
ApacheCon NA - Apache Camel K: a cloud-native integration platformApacheCon NA - Apache Camel K: a cloud-native integration platform
ApacheCon NA - Apache Camel K: a cloud-native integration platform
Nicola Ferraro
 
DevEx | there’s no place like k3s
DevEx | there’s no place like k3sDevEx | there’s no place like k3s
DevEx | there’s no place like k3s
Haggai Philip Zagury
 
Serverless Framework Workshop - Tyler Hendrickson, Chicago/burbs
 Serverless Framework Workshop - Tyler Hendrickson, Chicago/burbs Serverless Framework Workshop - Tyler Hendrickson, Chicago/burbs
Serverless Framework Workshop - Tyler Hendrickson, Chicago/burbs
AWS Chicago
 
DevOps Days Tel Aviv - Serverless Architecture
DevOps Days Tel Aviv - Serverless ArchitectureDevOps Days Tel Aviv - Serverless Architecture
DevOps Days Tel Aviv - Serverless Architecture
Antons Kranga
 
JavaDay Lviv: Serverless Archtiectures
JavaDay Lviv: Serverless ArchtiecturesJavaDay Lviv: Serverless Archtiectures
JavaDay Lviv: Serverless Archtiectures
Antons Kranga
 
Patterns and practices for real-world event-driven microservices
Patterns and practices for real-world event-driven microservicesPatterns and practices for real-world event-driven microservices
Patterns and practices for real-world event-driven microservices
Rachel Reese
 
AWS Primer and Quickstart
AWS Primer and QuickstartAWS Primer and Quickstart
AWS Primer and Quickstart
Manish Pandit
 
Serverless cat detector workshop - cloudyna 2017 (16.12.2017)
Serverless cat detector   workshop - cloudyna 2017 (16.12.2017)Serverless cat detector   workshop - cloudyna 2017 (16.12.2017)
Serverless cat detector workshop - cloudyna 2017 (16.12.2017)
Paweł Pikuła
 
Docker on AWS - the Right Way
Docker on AWS - the Right WayDocker on AWS - the Right Way
Docker on AWS - the Right Way
AllCloud
 
Serverless APIs with JavaScript - Matt Searle - ChocPanda
Serverless APIs with JavaScript - Matt Searle - ChocPandaServerless APIs with JavaScript - Matt Searle - ChocPanda
Serverless APIs with JavaScript - Matt Searle - ChocPanda
Paul Dykes
 
2016 - Serverless Microservices on AWS with API Gateway and Lambda
2016 - Serverless Microservices on AWS with API Gateway and Lambda2016 - Serverless Microservices on AWS with API Gateway and Lambda
2016 - Serverless Microservices on AWS with API Gateway and Lambda
devopsdaysaustin
 
Kubernetes on AWS
Kubernetes on AWSKubernetes on AWS
Kubernetes on AWS
Grant Ellis
 
Streams and serverless at DAZN
Streams and serverless at DAZNStreams and serverless at DAZN
Streams and serverless at DAZN
Yan Cui
 
ApacheCon NA - Apache Camel K: connect your Knative serverless applications w...
ApacheCon NA - Apache Camel K: connect your Knative serverless applications w...ApacheCon NA - Apache Camel K: connect your Knative serverless applications w...
ApacheCon NA - Apache Camel K: connect your Knative serverless applications w...
Nicola Ferraro
 
2020.02.15 DelEx - CI/CD in AWS Cloud
2020.02.15 DelEx - CI/CD in AWS Cloud2020.02.15 DelEx - CI/CD in AWS Cloud
2020.02.15 DelEx - CI/CD in AWS Cloud
Peter Salnikov
 
Open stack ocata summit enabling aws lambda-like functionality with openstac...
Open stack ocata summit  enabling aws lambda-like functionality with openstac...Open stack ocata summit  enabling aws lambda-like functionality with openstac...
Open stack ocata summit enabling aws lambda-like functionality with openstac...
Shaun Murakami
 
ApacheCon NA - Apache Camel K: a cloud-native integration platform
ApacheCon NA - Apache Camel K: a cloud-native integration platformApacheCon NA - Apache Camel K: a cloud-native integration platform
ApacheCon NA - Apache Camel K: a cloud-native integration platform
Nicola Ferraro
 
DevEx | there’s no place like k3s
DevEx | there’s no place like k3sDevEx | there’s no place like k3s
DevEx | there’s no place like k3s
Haggai Philip Zagury
 
Serverless Framework Workshop - Tyler Hendrickson, Chicago/burbs
 Serverless Framework Workshop - Tyler Hendrickson, Chicago/burbs Serverless Framework Workshop - Tyler Hendrickson, Chicago/burbs
Serverless Framework Workshop - Tyler Hendrickson, Chicago/burbs
AWS Chicago
 

Similar to Aws Lambda in Swift - NSLondon - 3rd December 2020 (13)

DevOps, Microservices and Serverless Architecture
DevOps, Microservices and Serverless ArchitectureDevOps, Microservices and Serverless Architecture
DevOps, Microservices and Serverless Architecture
Mikhail Prudnikov
 
What’s new in serverless - re:Invent 2020
What’s new in serverless - re:Invent 2020What’s new in serverless - re:Invent 2020
What’s new in serverless - re:Invent 2020
AWS Chicago
 
Building Serverless APIs (January 2017)
Building Serverless APIs (January 2017)Building Serverless APIs (January 2017)
Building Serverless APIs (January 2017)
Julien SIMON
 
Apache OpenWhisk Serverless Computing
Apache OpenWhisk Serverless ComputingApache OpenWhisk Serverless Computing
Apache OpenWhisk Serverless Computing
Upkar Lidder
 
Serverless Architectural Patterns & Best Practices
Serverless Architectural Patterns & Best PracticesServerless Architectural Patterns & Best Practices
Serverless Architectural Patterns & Best Practices
Daniel Zivkovic
 
Serverless computing
Serverless computingServerless computing
Serverless computing
Dmitriy Ivanov
 
Building Serverless APIs on AWS
Building Serverless APIs on AWSBuilding Serverless APIs on AWS
Building Serverless APIs on AWS
Julien SIMON
 
An introduction to serverless architectures (February 2017)
An introduction to serverless architectures (February 2017)An introduction to serverless architectures (February 2017)
An introduction to serverless architectures (February 2017)
Julien SIMON
 
Girish Bhatia: 2024 CommunityDay AWS Lambda develop locally with SAM, Docker ...
Girish Bhatia: 2024 CommunityDay AWS Lambda develop locally with SAM, Docker ...Girish Bhatia: 2024 CommunityDay AWS Lambda develop locally with SAM, Docker ...
Girish Bhatia: 2024 CommunityDay AWS Lambda develop locally with SAM, Docker ...
AWS Chicago
 
Building serverless apps with Node.js
Building serverless apps with Node.jsBuilding serverless apps with Node.js
Building serverless apps with Node.js
Julien SIMON
 
Webinar: Serverless Architectures with AWS Lambda and MongoDB Atlas
Webinar: Serverless Architectures with AWS Lambda and MongoDB AtlasWebinar: Serverless Architectures with AWS Lambda and MongoDB Atlas
Webinar: Serverless Architectures with AWS Lambda and MongoDB Atlas
MongoDB
 
AWS re:Invent 2020 Serverless Recap
AWS re:Invent 2020 Serverless RecapAWS re:Invent 2020 Serverless Recap
AWS re:Invent 2020 Serverless Recap
Daniel Zivkovic
 
Aws lambda and accesing AWS RDS - Clouddictive
Aws lambda and accesing AWS RDS - ClouddictiveAws lambda and accesing AWS RDS - Clouddictive
Aws lambda and accesing AWS RDS - Clouddictive
Clouddictive
 
DevOps, Microservices and Serverless Architecture
DevOps, Microservices and Serverless ArchitectureDevOps, Microservices and Serverless Architecture
DevOps, Microservices and Serverless Architecture
Mikhail Prudnikov
 
What’s new in serverless - re:Invent 2020
What’s new in serverless - re:Invent 2020What’s new in serverless - re:Invent 2020
What’s new in serverless - re:Invent 2020
AWS Chicago
 
Building Serverless APIs (January 2017)
Building Serverless APIs (January 2017)Building Serverless APIs (January 2017)
Building Serverless APIs (January 2017)
Julien SIMON
 
Apache OpenWhisk Serverless Computing
Apache OpenWhisk Serverless ComputingApache OpenWhisk Serverless Computing
Apache OpenWhisk Serverless Computing
Upkar Lidder
 
Serverless Architectural Patterns & Best Practices
Serverless Architectural Patterns & Best PracticesServerless Architectural Patterns & Best Practices
Serverless Architectural Patterns & Best Practices
Daniel Zivkovic
 
Building Serverless APIs on AWS
Building Serverless APIs on AWSBuilding Serverless APIs on AWS
Building Serverless APIs on AWS
Julien SIMON
 
An introduction to serverless architectures (February 2017)
An introduction to serverless architectures (February 2017)An introduction to serverless architectures (February 2017)
An introduction to serverless architectures (February 2017)
Julien SIMON
 
Girish Bhatia: 2024 CommunityDay AWS Lambda develop locally with SAM, Docker ...
Girish Bhatia: 2024 CommunityDay AWS Lambda develop locally with SAM, Docker ...Girish Bhatia: 2024 CommunityDay AWS Lambda develop locally with SAM, Docker ...
Girish Bhatia: 2024 CommunityDay AWS Lambda develop locally with SAM, Docker ...
AWS Chicago
 
Building serverless apps with Node.js
Building serverless apps with Node.jsBuilding serverless apps with Node.js
Building serverless apps with Node.js
Julien SIMON
 
Webinar: Serverless Architectures with AWS Lambda and MongoDB Atlas
Webinar: Serverless Architectures with AWS Lambda and MongoDB AtlasWebinar: Serverless Architectures with AWS Lambda and MongoDB Atlas
Webinar: Serverless Architectures with AWS Lambda and MongoDB Atlas
MongoDB
 
AWS re:Invent 2020 Serverless Recap
AWS re:Invent 2020 Serverless RecapAWS re:Invent 2020 Serverless Recap
AWS re:Invent 2020 Serverless Recap
Daniel Zivkovic
 
Aws lambda and accesing AWS RDS - Clouddictive
Aws lambda and accesing AWS RDS - ClouddictiveAws lambda and accesing AWS RDS - Clouddictive
Aws lambda and accesing AWS RDS - Clouddictive
Clouddictive
 
Ad

Recently uploaded (20)

Maxon CINEMA 4D 2025 Crack FREE Download LINK
Maxon CINEMA 4D 2025 Crack FREE Download LINKMaxon CINEMA 4D 2025 Crack FREE Download LINK
Maxon CINEMA 4D 2025 Crack FREE Download LINK
younisnoman75
 
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AIScaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
danshalev
 
Avast Premium Security Crack FREE Latest Version 2025
Avast Premium Security Crack FREE Latest Version 2025Avast Premium Security Crack FREE Latest Version 2025
Avast Premium Security Crack FREE Latest Version 2025
mu394968
 
Solidworks Crack 2025 latest new + license code
Solidworks Crack 2025 latest new + license codeSolidworks Crack 2025 latest new + license code
Solidworks Crack 2025 latest new + license code
aneelaramzan63
 
WinRAR Crack for Windows (100% Working 2025)
WinRAR Crack for Windows (100% Working 2025)WinRAR Crack for Windows (100% Working 2025)
WinRAR Crack for Windows (100% Working 2025)
sh607827
 
Explaining GitHub Actions Failures with Large Language Models Challenges, In...
Explaining GitHub Actions Failures with Large Language Models Challenges, In...Explaining GitHub Actions Failures with Large Language Models Challenges, In...
Explaining GitHub Actions Failures with Large Language Models Challenges, In...
ssuserb14185
 
Designing AI-Powered APIs on Azure: Best Practices& Considerations
Designing AI-Powered APIs on Azure: Best Practices& ConsiderationsDesigning AI-Powered APIs on Azure: Best Practices& Considerations
Designing AI-Powered APIs on Azure: Best Practices& Considerations
Dinusha Kumarasiri
 
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdfMicrosoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
TechSoup
 
Adobe Master Collection CC Crack Advance Version 2025
Adobe Master Collection CC Crack Advance Version 2025Adobe Master Collection CC Crack Advance Version 2025
Adobe Master Collection CC Crack Advance Version 2025
kashifyounis067
 
Not So Common Memory Leaks in Java Webinar
Not So Common Memory Leaks in Java WebinarNot So Common Memory Leaks in Java Webinar
Not So Common Memory Leaks in Java Webinar
Tier1 app
 
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRYLEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
NidaFarooq10
 
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
Egor Kaleynik
 
Pixologic ZBrush Crack Plus Activation Key [Latest 2025] New Version
Pixologic ZBrush Crack Plus Activation Key [Latest 2025] New VersionPixologic ZBrush Crack Plus Activation Key [Latest 2025] New Version
Pixologic ZBrush Crack Plus Activation Key [Latest 2025] New Version
saimabibi60507
 
Societal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainabilitySocietal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainability
Jordi Cabot
 
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
steaveroggers
 
Exploring Code Comprehension in Scientific Programming: Preliminary Insight...
Exploring Code Comprehension  in Scientific Programming:  Preliminary Insight...Exploring Code Comprehension  in Scientific Programming:  Preliminary Insight...
Exploring Code Comprehension in Scientific Programming: Preliminary Insight...
University of Hawai‘i at Mānoa
 
Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]
saniaaftab72555
 
How can one start with crypto wallet development.pptx
How can one start with crypto wallet development.pptxHow can one start with crypto wallet development.pptx
How can one start with crypto wallet development.pptx
laravinson24
 
Revolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptxRevolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptx
nidhisingh691197
 
Kubernetes_101_Zero_to_Platform_Engineer.pptx
Kubernetes_101_Zero_to_Platform_Engineer.pptxKubernetes_101_Zero_to_Platform_Engineer.pptx
Kubernetes_101_Zero_to_Platform_Engineer.pptx
CloudScouts
 
Maxon CINEMA 4D 2025 Crack FREE Download LINK
Maxon CINEMA 4D 2025 Crack FREE Download LINKMaxon CINEMA 4D 2025 Crack FREE Download LINK
Maxon CINEMA 4D 2025 Crack FREE Download LINK
younisnoman75
 
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AIScaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
danshalev
 
Avast Premium Security Crack FREE Latest Version 2025
Avast Premium Security Crack FREE Latest Version 2025Avast Premium Security Crack FREE Latest Version 2025
Avast Premium Security Crack FREE Latest Version 2025
mu394968
 
Solidworks Crack 2025 latest new + license code
Solidworks Crack 2025 latest new + license codeSolidworks Crack 2025 latest new + license code
Solidworks Crack 2025 latest new + license code
aneelaramzan63
 
WinRAR Crack for Windows (100% Working 2025)
WinRAR Crack for Windows (100% Working 2025)WinRAR Crack for Windows (100% Working 2025)
WinRAR Crack for Windows (100% Working 2025)
sh607827
 
Explaining GitHub Actions Failures with Large Language Models Challenges, In...
Explaining GitHub Actions Failures with Large Language Models Challenges, In...Explaining GitHub Actions Failures with Large Language Models Challenges, In...
Explaining GitHub Actions Failures with Large Language Models Challenges, In...
ssuserb14185
 
Designing AI-Powered APIs on Azure: Best Practices& Considerations
Designing AI-Powered APIs on Azure: Best Practices& ConsiderationsDesigning AI-Powered APIs on Azure: Best Practices& Considerations
Designing AI-Powered APIs on Azure: Best Practices& Considerations
Dinusha Kumarasiri
 
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdfMicrosoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
TechSoup
 
Adobe Master Collection CC Crack Advance Version 2025
Adobe Master Collection CC Crack Advance Version 2025Adobe Master Collection CC Crack Advance Version 2025
Adobe Master Collection CC Crack Advance Version 2025
kashifyounis067
 
Not So Common Memory Leaks in Java Webinar
Not So Common Memory Leaks in Java WebinarNot So Common Memory Leaks in Java Webinar
Not So Common Memory Leaks in Java Webinar
Tier1 app
 
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRYLEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
NidaFarooq10
 
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
Egor Kaleynik
 
Pixologic ZBrush Crack Plus Activation Key [Latest 2025] New Version
Pixologic ZBrush Crack Plus Activation Key [Latest 2025] New VersionPixologic ZBrush Crack Plus Activation Key [Latest 2025] New Version
Pixologic ZBrush Crack Plus Activation Key [Latest 2025] New Version
saimabibi60507
 
Societal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainabilitySocietal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainability
Jordi Cabot
 
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
steaveroggers
 
Exploring Code Comprehension in Scientific Programming: Preliminary Insight...
Exploring Code Comprehension  in Scientific Programming:  Preliminary Insight...Exploring Code Comprehension  in Scientific Programming:  Preliminary Insight...
Exploring Code Comprehension in Scientific Programming: Preliminary Insight...
University of Hawai‘i at Mānoa
 
Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]
saniaaftab72555
 
How can one start with crypto wallet development.pptx
How can one start with crypto wallet development.pptxHow can one start with crypto wallet development.pptx
How can one start with crypto wallet development.pptx
laravinson24
 
Revolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptxRevolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptx
nidhisingh691197
 
Kubernetes_101_Zero_to_Platform_Engineer.pptx
Kubernetes_101_Zero_to_Platform_Engineer.pptxKubernetes_101_Zero_to_Platform_Engineer.pptx
Kubernetes_101_Zero_to_Platform_Engineer.pptx
CloudScouts
 
Ad

Aws Lambda in Swift - NSLondon - 3rd December 2020

  • 1. AWS Lambda in Swift Andrea Scuderi - Lead iOS @ Shpock @andreascuderi13 NSLondon - 3rd of December 2020
  • 2. AWS Lambda in Swift Agenda • What is a Lambda? • How can I code a Lambda with Swift? • Development Tools • Building Tools • Deployment Tools • Introduction to a Serverless REST API in Swift
  • 3. What is a Lambda?
  • 4. HW, VM, Container vs Serverless What are the advantages of it? λServers Virtual Machines Containers Function as a Service FaaS Abstraction LevelHW SW
  • 5. HW, VM, Container vs Serverless What are the advantages of it? λServers Virtual Machines Containers Function as a Service FaaS Deployment SpeedDays μs (micro-seconds)
  • 6. HW, VM, Container vs Serverless What are the advantages of it? λServers Virtual Machines Containers Function as a Service FaaS ScalabilitySPoF (Single Point of Failure) Auto-Scaling
  • 7. HW, VM, Container vs Serverless What are the advantages of it? λServers Virtual Machines Containers Function as a Service FaaS Business ModelPay Upfront Pay Per Use
  • 8. Monolithic vs Microservices Architecture User Interface Business Logic Data Access Layer DB User Interface Micro service Micro service Micro service Micro service Micro service DB DB DB Monolithic • Simpler • Lower Latency • Higher Throughput Microservice • Loose coupling • More reliable • Less resource • Easier scaling • More Agile • High complexity • Less communication
  • 9. AWS Serverless Landscape • COMPUTE: Lambda • STORAGE: S3, EFS • DATA STORE: DynamoDB, Aurora • API PROXY: API Gateway • MESSAGING: SNS, SQS, Kinesis • ORCHESTRATION: Step Functions • MONITORING: CloudTrail • SECURITY: IAM, Cognito
  • 10. AWS Lambda Function as a Service (FaaS) • Serverless • Managed Micro-Service • Event driven • Stateless • Auto-Scaling • Pay per use (Sub-second metering) • Logging and monitoring is included • Code container • Multi-Language support • Can run Linux compatible language runtime via Runtime API © 2019, Amazon Web Services, Inc. or its affiliates. All 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 C# / F# / PowerShell Go Ruby Runtime API
  • 11. How can I code a Lambda with Swift?
  • 12. Hello World Project setup > mkdir HelloWorldLambd a > cd HelloWorldLambd a > swift package init --type=executabl e > xed Package.swif t
  • 13. Hello World Update Package.swift import PackageDescription let package = Package( name: "HelloWorldLambda", products: [ .executable(name: "HelloWorldLambda", targets: ["HelloWorldLambda"]), ], dependencies: [ .package(url: "https://github.com/swift-server/swift-aws-lambda-runtime.git", from: "0.1.0"), ], targets: [ .target( name: "HelloWorldLambda", dependencies: [ .product(name: "AWSLambdaRuntime", package: "swift-aws-lambda-runtime"), ]), .testTarget( name: "HelloWorldLambdaTests", dependencies: ["HelloWorldLambda"]), ] )
  • 14. Hello World Add your code to main.swift import AWSLambdaRuntime struct Request: Codable { let name: String } struct Response: Codable { let message: String } Lambda.run { (context, request: Request, callback: @escaping (Result<Response, Error>) -> Void) in let response = Response(message: "Hello!: (request.name)") callback(.success(response)) }
  • 15. Hello World Run your Lambda locally > export LOCAL_LAMBDA_SERVER_ENABLED=tru e > swift run HelloWorldLambd a > curl --location --request POST 'http://localhost:7000/invoke' --header 'Content-Type: text/plain' --data-raw ' { "name": "Andrea " } ' {"message":"Hello!: Andrea" }
  • 16. Apple - Swift NIO https://github.com/apple/swift-nio • SwiftNIO - NIO == non-blocking I/O • cross-platform • asynchronous event-driven network application framework • for rapid development of maintainable high performance protocol servers & clients. • Low level framework • use-cases: where"thread-per-connection" model of concurrency is inef f icient or untenable. • Is the fundamental part of most of the Server Side Swift frameworks
  • 17. Apple - Swift NIO https://github.com/apple/swift-nio • EventLoop: • The event loop is an object that waits for events (usually I/O) to happen and then f ires some kind of callback when they do. • EventLoopFuture<T>: • manage operations that complete asynchronously. • a container for the return value of a function that will be populated at some time in the future • EventLoopPromise<T>: • Each EventLoopFuture<T> has a corresponding EventLoopPromise<T>, which is the object that the result will be put into. When the promise is succeeded, the future will be ful f illed.
  • 18. HTTPSLambda Swift NIO + AsyncHTTPClient import AWSLambdaRuntime import AsyncHTTPClient import NIO struct Event: Codable { let url: String } struct Response: Codable { let content: String } struct HTTPSLambda: EventLoopLambdaHandler { // MARK: - In & Out typealias In = Event typealias Out = Response // MARK: - Lambda Handler func handle(context: Lambda.Context, event: Event) -> EventLoopFuture<Response> { guard let request = try? HTTPClient.Request(url: event.url) else { return context.eventLoop.makeFailedFuture(LambdaError.invalidRequest) } return httpClient.execute(request: request, deadline: nil) .flatMapThrowing { (response) throws -> String in guard let body: ByteBuffer = response.body, let value: String = body.getString(at: 0, length: body.readableBytes) else { throw LambdaError.invalidContent } return value }.map { content -> Response in return Response(content: content) } } > git clone https://github.com/Andrea-Scuderi/HelloWorldLambda
  • 19. HTTPSLambda Swift NIO + AsyncHTTPClient // MARK: - HTTPClient Configuration let httpClient: HTTPClient static let lambdaRuntimeTimeout: TimeAmount = .seconds(30) static let timeout = HTTPClient.Configuration.Timeout( connect: lambdaRuntimeTimeout, read: lambdaRuntimeTimeout ) static let configuration = HTTPClient.Configuration(timeout: timeout) // MARK: - LambdaError enum LambdaError: Error { case invalidRequest case invalidContent } // MARK: - Init init(context: Lambda.InitializationContext) { // Use HTTPClient on the same EventLoop used by AWSLambda self.httpClient = HTTPClient( eventLoopGroupProvider: .shared(context.eventLoop), configuration: HTTPSLambda.configuration ) } } Lambda.run(HTTPSLambda.init)
  • 20. AWS Lambda Swift Runtime Lambda Architecture & Building pipeline User Lambda Swift Code AWS Lambda Swift Runtime bootstrap Swift Libraries for Runtime swift:5.3-amazonlinux2 ❌ To run the Lambda on AWS we need: - build the binary for Amazon Linux 2 - copy all the Swift runtime libraries required in the zip bundle
  • 21. AWS Lambda in Swift Development Tools Code Build+ Deploy Swift Amazon Linux 2 Swift 5.x
  • 22. Build AWS Lambda in Swift • Requirements: Docker Desktop, Bash > git clone https://github.com/Andrea-Scuderi/HelloWorldLambd a > cd HelloWorldLambd a > ./scripts/build-and-package.sh HelloWorldLambd a > ls .build/lambda/HelloWorldLambda/lambda.zi p swift:5.3-amazonlinux2
  • 23. AWS Lambda Deployment tools Pick your favourite…, mine is Serverless framework • AWS Management Console (manual upload) • AWS CLI - Command line interface (Scripting) • AWS CloudFormation: Infrastructure as code • AWS SAM Serverless Application Model: deployment tool • Serverless: Cloud Agnostic Multiplatform deployment tool • ….
  • 24. Deploy AWS Lambda in Swift After you have created your account on AWS, you need to install: • AWS CLI: https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2- mac.html • Serverless framework: > curl -o- -L https://slss.io/install | bas h > ./scripts/serverless-deploy.s h
  • 27. Introduction to a Serverless REST API in Swift
  • 28. REST API AWS Serverless Architecture • API Gateway • Lambda • Create • Read • Update • Delete • List • DynamoDB
  • 29. AWS Serverless Swift API Template Full working Demo • https://github.com/swift-sprinter/aws-serverless-swift-api-template • `Product` demo API in Swift • Use SOTO Library (AWS SDK for Swift) • YAML template for Serverless • Deployments Scripts
  • 30. Question Time Tanks for listening • Follow me! • Twitter: @andreascuderi13 • Linkedin: https://www.linkedin.com/in/andreascuderi/ • Medium: https://medium.com/@andreascuderi73