SlideShare a Scribd company logo
1 of 25
Download to read offline
Serverless APIs with JavaScript
Matt Searle
ChocPanda
● Brief intro to serverless
● AWS Serverless technologies
● API Gateway
● Lambda Functions
● Best Practices
● Mambda
● Example
Road map
What is Serverless?
THERE IS A SERVER!
When discussing serverless technologies, what
we’re really talking about is shifting more of
your operational responsibilities to a cloud
provider.
Serverless simply means that you the developer
or your friend the infrastructure engineer are no
longer responsible for grunt work like
provisioning and patching operating systems of
servers and scheduling downtime/failover.
There is a person somewhere in a data
centre managing that server for you
and you don’t need to know about it
Responsibilities
Managing/patching the
server
Scaling resources with
demand Load balancing
Configuring high
availability
What can I do with this?
Some of the Serverless tech on AWS
Lambda
Fargate
SNS
EFSAppSync
AuroraAthena
Kinesis
What is the gateway?
The gateway is an entry point for your
application, allowing you to create,
publish, maintain, monitor, and
secure APIs at any scale.
Client applications can use the
gateway to access backend services,
data or business logic by accessing a
RESTful or WebSocket API in Gateway.
API Gateway
Lambda
What is Lambda and what’s cool about it?
Lambdas are small independent units of code that literally are a single function.
They’re executed in an entirely managed runtime, meaning you simply upload the
executable and trigger them.
Mobile backend
Best practices
When writing code for lambda
● Separate the core logic of your function
from the boilerplate and other
dependencies
● Take advantage of Execution Context
reuse, limit the re-initialisation of
variables/objects on every invocation
● Minimise your package size
Additional reading:
DZONE Article
AWS Whitepaper
● Control the dependencies in your
function's deployment package. AWS
provides some, but updates them
periodically which could subtly change
your code
● Minimise the complexity of your
dependencies. Prefer simpler frameworks
that load quickly on Execution Context
startup
● There are concurrency limits to be aware
of and by default these are global in your
AWS account. Prefer function-specific
reserved resources
A few best practices when writing lambdas
● Cold start versus warm start execution
performance
● Improving cold start performance is
looking at the runtime environment. JS
and other interpreted languages have
the advantage here
● Small executables for v8 optimisations.
Minify and uglify your code, removing
comments and anything unnecessary
Considerations
Shameless self-promotion
Other tools and libraries do exist
I have created a small lightweight tool
which leverages a middleware pattern
to abstract out boilerplate code from
your Lambdas.
Inspired by MiddyJS
Mambda
ChocPanda
Finally, the code
const lambda = require('mambda');
const jsonBodyParser = require('mambda/middlewares/json-body-parser');
const httpErrorHandler = require('mambda/middlewares/http-error-handler');
async function myAsyncHandler(event, context, callback) {
// try {
// const body = headers['Content-Type'] === 'application/json')
// ? JSON.parse(event.body)
// : {}
// } catch (error) {
// other error handling...
// return { statusCode: 422, body: 'Unprocessable entity, invalid json in request body' }
// }
const body = event.body; // A javascript object from the deserialized json in the original event
const foo = await bar();
//... function code
return someOperation(foo);
}
exports.handler = lambda(myAsyncHandler)
.use(jsonBodyParser())
.use(httpErrorHandler())
The life of a Mambda function
const lambda = require('mambda');
const AWS = require('aws-sdk')
const myHandler = s3 => (event, context, callback) => {
var params = { Bucket: process.env.BUCKET_NAME, Key: process.env.BUCKET_KEY, Body: process.env.BODY };
// function code...
s3.putObject(params, function(err, data) {
if (err) {
callback(err)
} else {
callback(null, 'Put the body into the bucket! YAY!')
}
});
}
exports.handler = lambda({ init: () => new AWS.S3(), handler: myHandler });
Simple Recruitment tool
● 2 Javascript front ends hosted as
static websites within S3 buckets
● Uses a lambda to create signed
urls to upload CVs to another s3
bucket
● Uses lambda to send an SNS
notification to the hiring manager
when a new candidate applies for
a role
● Store the candidate’s name and
any other information in a
DynamoDb database
const mambda = require('mambda');
const { jsonBodyParser, httpErrorHandler, httpHeaderNormalizer } = require('mambda/middlewares');
const optionsRequestInterceptor = require('./options-request-interceptor');
module.exports = fn => {
const { init, handler = fn } = fn;
return mambda({
init,
handler,
middlewares: [httpHeaderNormalizer(), jsonBodyParser(), httpErrorHandler(), optionsRequestInterceptor()]
});
};
Preconfigure your middlewares
const generateUrls = ({ s3Instance }) => ({ body }) => {
const applicationId = uuid.v4();
const urls = body.reduce(
(accumulated, fileName) => ({
...accumulated,
[fileName]: s3Instance.getSignedUrl('putObject', {
Bucket: process.env.S3_BUCKET,
Key: `${applicationId}/${fileName}`,
Expires: 120
})
}),
{}
);
return { statusCode: 200, body: JSON.stringify({ applicationId, urls }) };
};
exports.post = lambdaWrapper({
init: () => ({
s3Instance: new S3({
signatureVersion: 'v4'
})
}),
handler: generateUrls
});
● Initialised connection to the s3 API
● Deserialised request body
● Cold start initialisation
Some things I haven’t discussed
● Using swagger annotations in the JS code to
describe the handler functions and configure
the API gateway
● Setting up development stages and using
blue-green deployments API Gateway
● Increased testability of the modules for
lambda written with Mambda
● Infrastructure as code (Terraform, AWS CDK,
Cloudformation, etc...)
Any questions?

More Related Content

What's hot

Aws Lambda in Swift - NSLondon - 3rd December 2020
Aws Lambda in Swift - NSLondon - 3rd December 2020Aws Lambda in Swift - NSLondon - 3rd December 2020
Aws Lambda in Swift - NSLondon - 3rd December 2020Andrea Scuderi
 
AWS Lambda and Serverless framework: lessons learned while building a serverl...
AWS Lambda and Serverless framework: lessons learned while building a serverl...AWS Lambda and Serverless framework: lessons learned while building a serverl...
AWS Lambda and Serverless framework: lessons learned while building a serverl...Luciano Mammino
 
Continuous Deployment in AWS Lambda
Continuous Deployment in AWS LambdaContinuous Deployment in AWS Lambda
Continuous Deployment in AWS LambdaShu Ting Tseng
 
A Step to programming with Apache Spark
A Step to programming with Apache SparkA Step to programming with Apache Spark
A Step to programming with Apache SparkKnoldus Inc.
 
Serverless Architectures on AWS Lambda
Serverless Architectures on AWS LambdaServerless Architectures on AWS Lambda
Serverless Architectures on AWS LambdaSerhat Can
 
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 Lambdadevopsdaysaustin
 
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/burbsAWS Chicago
 
How to Use AWS Lambda Layers and Lambda Runtime
How to Use AWS Lambda Layers and Lambda RuntimeHow to Use AWS Lambda Layers and Lambda Runtime
How to Use AWS Lambda Layers and Lambda RuntimeDonnie Prakoso
 
Aws serverless architecture
Aws serverless architectureAws serverless architecture
Aws serverless architecturegenesesoftware
 
Serverless design considerations for Cloud Native workloads
Serverless design considerations for Cloud Native workloadsServerless design considerations for Cloud Native workloads
Serverless design considerations for Cloud Native workloadsTensult
 
ServerlessPresentation
ServerlessPresentationServerlessPresentation
ServerlessPresentationRohit Kumar
 
Building Automated Control Systems for Your AWS Infrastructure
Building Automated Control Systems for Your AWS InfrastructureBuilding Automated Control Systems for Your AWS Infrastructure
Building Automated Control Systems for Your AWS InfrastructureAmazon Web Services
 
Getting Started with Serverless Architectures
Getting Started with Serverless ArchitecturesGetting Started with Serverless Architectures
Getting Started with Serverless ArchitecturesAmazon Web Services
 
AWS Lambda Tutorial
AWS Lambda TutorialAWS Lambda Tutorial
AWS Lambda TutorialWhizlabs
 
Introduce AWS Lambda for newbie and Non-IT
Introduce AWS Lambda for newbie and Non-ITIntroduce AWS Lambda for newbie and Non-IT
Introduce AWS Lambda for newbie and Non-ITChitpong Wuttanan
 
AWS Step Functions를 이용한 마이크로서비스 개발하기 - 김현민 (4CSoft)
AWS Step Functions를 이용한 마이크로서비스 개발하기 - 김현민 (4CSoft)AWS Step Functions를 이용한 마이크로서비스 개발하기 - 김현민 (4CSoft)
AWS Step Functions를 이용한 마이크로서비스 개발하기 - 김현민 (4CSoft)AWSKRUG - AWS한국사용자모임
 

What's hot (20)

Aws Lambda in Swift - NSLondon - 3rd December 2020
Aws Lambda in Swift - NSLondon - 3rd December 2020Aws Lambda in Swift - NSLondon - 3rd December 2020
Aws Lambda in Swift - NSLondon - 3rd December 2020
 
AWS Lambda
AWS LambdaAWS Lambda
AWS Lambda
 
Serverless by examples and case studies
Serverless by examples and case studiesServerless by examples and case studies
Serverless by examples and case studies
 
AWS Lambda and Serverless framework: lessons learned while building a serverl...
AWS Lambda and Serverless framework: lessons learned while building a serverl...AWS Lambda and Serverless framework: lessons learned while building a serverl...
AWS Lambda and Serverless framework: lessons learned while building a serverl...
 
Continuous Deployment in AWS Lambda
Continuous Deployment in AWS LambdaContinuous Deployment in AWS Lambda
Continuous Deployment in AWS Lambda
 
A Step to programming with Apache Spark
A Step to programming with Apache SparkA Step to programming with Apache Spark
A Step to programming with Apache Spark
 
Serverless Architectures on AWS Lambda
Serverless Architectures on AWS LambdaServerless Architectures on AWS Lambda
Serverless Architectures on AWS Lambda
 
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
 
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
 
How to Use AWS Lambda Layers and Lambda Runtime
How to Use AWS Lambda Layers and Lambda RuntimeHow to Use AWS Lambda Layers and Lambda Runtime
How to Use AWS Lambda Layers and Lambda Runtime
 
AWS Jungle - Lambda
AWS Jungle - LambdaAWS Jungle - Lambda
AWS Jungle - Lambda
 
Aws serverless architecture
Aws serverless architectureAws serverless architecture
Aws serverless architecture
 
Serverless design considerations for Cloud Native workloads
Serverless design considerations for Cloud Native workloadsServerless design considerations for Cloud Native workloads
Serverless design considerations for Cloud Native workloads
 
locize tech stack
locize tech stacklocize tech stack
locize tech stack
 
ServerlessPresentation
ServerlessPresentationServerlessPresentation
ServerlessPresentation
 
Building Automated Control Systems for Your AWS Infrastructure
Building Automated Control Systems for Your AWS InfrastructureBuilding Automated Control Systems for Your AWS Infrastructure
Building Automated Control Systems for Your AWS Infrastructure
 
Getting Started with Serverless Architectures
Getting Started with Serverless ArchitecturesGetting Started with Serverless Architectures
Getting Started with Serverless Architectures
 
AWS Lambda Tutorial
AWS Lambda TutorialAWS Lambda Tutorial
AWS Lambda Tutorial
 
Introduce AWS Lambda for newbie and Non-IT
Introduce AWS Lambda for newbie and Non-ITIntroduce AWS Lambda for newbie and Non-IT
Introduce AWS Lambda for newbie and Non-IT
 
AWS Step Functions를 이용한 마이크로서비스 개발하기 - 김현민 (4CSoft)
AWS Step Functions를 이용한 마이크로서비스 개발하기 - 김현민 (4CSoft)AWS Step Functions를 이용한 마이크로서비스 개발하기 - 김현민 (4CSoft)
AWS Step Functions를 이용한 마이크로서비스 개발하기 - 김현민 (4CSoft)
 

Similar to Serverless APIs with JavaScript - Matt Searle - ChocPanda

10 Tips For Serverless Backends With NodeJS and AWS Lambda
10 Tips For Serverless Backends With NodeJS and AWS Lambda10 Tips For Serverless Backends With NodeJS and AWS Lambda
10 Tips For Serverless Backends With NodeJS and AWS LambdaJim Lynch
 
AWS Lambda, Step Functions & MongoDB Atlas Tutorial
AWS Lambda, Step Functions & MongoDB Atlas TutorialAWS Lambda, Step Functions & MongoDB Atlas Tutorial
AWS Lambda, Step Functions & MongoDB Atlas TutorialMongoDB
 
Serverless Computing
Serverless ComputingServerless Computing
Serverless ComputingAnand Gupta
 
AWS Lambda Functions A Comprehensive Guide
AWS Lambda Functions A Comprehensive GuideAWS Lambda Functions A Comprehensive Guide
AWS Lambda Functions A Comprehensive GuideInexture Solutions
 
Deploying Serverless Cloud Optical Character Recognition in Support of NASA A...
Deploying Serverless Cloud Optical Character Recognition in Support of NASA A...Deploying Serverless Cloud Optical Character Recognition in Support of NASA A...
Deploying Serverless Cloud Optical Character Recognition in Support of NASA A...Chris Shenton
 
Serverless OCR for NASA EVA: AWS Meetup DC 2017-12-12
Serverless OCR for NASA EVA: AWS Meetup DC 2017-12-12Serverless OCR for NASA EVA: AWS Meetup DC 2017-12-12
Serverless OCR for NASA EVA: AWS Meetup DC 2017-12-12Chris Shenton
 
Serverless Optical Character Recognition in support of Astronaut Safety AWS M...
Serverless Optical Character Recognition in support of Astronaut Safety AWS M...Serverless Optical Character Recognition in support of Astronaut Safety AWS M...
Serverless Optical Character Recognition in support of Astronaut Safety AWS M...Chris Shenton
 
(CMP403) AWS Lambda: Simplifying Big Data Workloads
(CMP403) AWS Lambda: Simplifying Big Data Workloads(CMP403) AWS Lambda: Simplifying Big Data Workloads
(CMP403) AWS Lambda: Simplifying Big Data WorkloadsAmazon Web Services
 
Serverless Architectural Patterns & Best Practices
Serverless Architectural Patterns & Best PracticesServerless Architectural Patterns & Best Practices
Serverless Architectural Patterns & Best PracticesDaniel Zivkovic
 
AWS Lambda Documentation
AWS Lambda DocumentationAWS Lambda Documentation
AWS Lambda DocumentationWhizlabs
 
Into The Box | Alexa and ColdBox Api's
Into The Box | Alexa and ColdBox Api'sInto The Box | Alexa and ColdBox Api's
Into The Box | Alexa and ColdBox Api'sOrtus Solutions, Corp
 
Raleigh DevDay 2017: Building serverless web applications
Raleigh DevDay 2017: Building serverless web applicationsRaleigh DevDay 2017: Building serverless web applications
Raleigh DevDay 2017: Building serverless web applicationsAmazon Web Services
 
Serverless architectures-with-aws-lambda
Serverless architectures-with-aws-lambdaServerless architectures-with-aws-lambda
Serverless architectures-with-aws-lambdasaifam
 
Migrating your .NET Applications to the AWS Serverless Platform
Migrating your .NET Applications to the AWS Serverless PlatformMigrating your .NET Applications to the AWS Serverless Platform
Migrating your .NET Applications to the AWS Serverless PlatformAmazon Web Services
 
DPD:AWS Developer Training
DPD:AWS Developer TrainingDPD:AWS Developer Training
DPD:AWS Developer TrainingJosh Curtis
 
Building a serverless company on AWS lambda and Serverless framework
Building a serverless company on AWS lambda and Serverless frameworkBuilding a serverless company on AWS lambda and Serverless framework
Building a serverless company on AWS lambda and Serverless frameworkLuciano Mammino
 
AWS re:Invent 2016: ↑↑↓↓←→←→ BA Lambda Start (SVR305)
AWS re:Invent 2016: ↑↑↓↓←→←→ BA Lambda Start (SVR305)AWS re:Invent 2016: ↑↑↓↓←→←→ BA Lambda Start (SVR305)
AWS re:Invent 2016: ↑↑↓↓←→←→ BA Lambda Start (SVR305)Amazon Web Services
 

Similar to Serverless APIs with JavaScript - Matt Searle - ChocPanda (20)

10 Tips For Serverless Backends With NodeJS and AWS Lambda
10 Tips For Serverless Backends With NodeJS and AWS Lambda10 Tips For Serverless Backends With NodeJS and AWS Lambda
10 Tips For Serverless Backends With NodeJS and AWS Lambda
 
AWS Lambda, Step Functions & MongoDB Atlas Tutorial
AWS Lambda, Step Functions & MongoDB Atlas TutorialAWS Lambda, Step Functions & MongoDB Atlas Tutorial
AWS Lambda, Step Functions & MongoDB Atlas Tutorial
 
locize tech talk
locize tech talklocize tech talk
locize tech talk
 
Serverless Computing
Serverless ComputingServerless Computing
Serverless Computing
 
AWS Lambda Functions A Comprehensive Guide
AWS Lambda Functions A Comprehensive GuideAWS Lambda Functions A Comprehensive Guide
AWS Lambda Functions A Comprehensive Guide
 
Deploying Serverless Cloud Optical Character Recognition in Support of NASA A...
Deploying Serverless Cloud Optical Character Recognition in Support of NASA A...Deploying Serverless Cloud Optical Character Recognition in Support of NASA A...
Deploying Serverless Cloud Optical Character Recognition in Support of NASA A...
 
Serverless OCR for NASA EVA: AWS Meetup DC 2017-12-12
Serverless OCR for NASA EVA: AWS Meetup DC 2017-12-12Serverless OCR for NASA EVA: AWS Meetup DC 2017-12-12
Serverless OCR for NASA EVA: AWS Meetup DC 2017-12-12
 
Serverless Optical Character Recognition in support of Astronaut Safety AWS M...
Serverless Optical Character Recognition in support of Astronaut Safety AWS M...Serverless Optical Character Recognition in support of Astronaut Safety AWS M...
Serverless Optical Character Recognition in support of Astronaut Safety AWS M...
 
Serverless
ServerlessServerless
Serverless
 
(CMP403) AWS Lambda: Simplifying Big Data Workloads
(CMP403) AWS Lambda: Simplifying Big Data Workloads(CMP403) AWS Lambda: Simplifying Big Data Workloads
(CMP403) AWS Lambda: Simplifying Big Data Workloads
 
Serverless Architectural Patterns & Best Practices
Serverless Architectural Patterns & Best PracticesServerless Architectural Patterns & Best Practices
Serverless Architectural Patterns & Best Practices
 
AWS Lambda Documentation
AWS Lambda DocumentationAWS Lambda Documentation
AWS Lambda Documentation
 
Into The Box | Alexa and ColdBox Api's
Into The Box | Alexa and ColdBox Api'sInto The Box | Alexa and ColdBox Api's
Into The Box | Alexa and ColdBox Api's
 
Raleigh DevDay 2017: Building serverless web applications
Raleigh DevDay 2017: Building serverless web applicationsRaleigh DevDay 2017: Building serverless web applications
Raleigh DevDay 2017: Building serverless web applications
 
Serverless architectures-with-aws-lambda
Serverless architectures-with-aws-lambdaServerless architectures-with-aws-lambda
Serverless architectures-with-aws-lambda
 
Migrating your .NET Applications to the AWS Serverless Platform
Migrating your .NET Applications to the AWS Serverless PlatformMigrating your .NET Applications to the AWS Serverless Platform
Migrating your .NET Applications to the AWS Serverless Platform
 
DPD:AWS Developer Training
DPD:AWS Developer TrainingDPD:AWS Developer Training
DPD:AWS Developer Training
 
Building a serverless company on AWS lambda and Serverless framework
Building a serverless company on AWS lambda and Serverless frameworkBuilding a serverless company on AWS lambda and Serverless framework
Building a serverless company on AWS lambda and Serverless framework
 
AWS re:Invent 2016: ↑↑↓↓←→←→ BA Lambda Start (SVR305)
AWS re:Invent 2016: ↑↑↓↓←→←→ BA Lambda Start (SVR305)AWS re:Invent 2016: ↑↑↓↓←→←→ BA Lambda Start (SVR305)
AWS re:Invent 2016: ↑↑↓↓←→←→ BA Lambda Start (SVR305)
 
Running R on AWS Lambda by Ana-Maria Niculescu
Running R on AWS Lambda by Ana-Maria NiculescuRunning R on AWS Lambda by Ana-Maria Niculescu
Running R on AWS Lambda by Ana-Maria Niculescu
 

Recently uploaded

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 

Recently uploaded (20)

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 

Serverless APIs with JavaScript - Matt Searle - ChocPanda

  • 1. Serverless APIs with JavaScript Matt Searle ChocPanda
  • 2. ● Brief intro to serverless ● AWS Serverless technologies ● API Gateway ● Lambda Functions ● Best Practices ● Mambda ● Example Road map
  • 4. THERE IS A SERVER! When discussing serverless technologies, what we’re really talking about is shifting more of your operational responsibilities to a cloud provider. Serverless simply means that you the developer or your friend the infrastructure engineer are no longer responsible for grunt work like provisioning and patching operating systems of servers and scheduling downtime/failover. There is a person somewhere in a data centre managing that server for you and you don’t need to know about it
  • 5. Responsibilities Managing/patching the server Scaling resources with demand Load balancing Configuring high availability
  • 6. What can I do with this?
  • 7. Some of the Serverless tech on AWS Lambda Fargate SNS EFSAppSync AuroraAthena Kinesis
  • 8. What is the gateway? The gateway is an entry point for your application, allowing you to create, publish, maintain, monitor, and secure APIs at any scale. Client applications can use the gateway to access backend services, data or business logic by accessing a RESTful or WebSocket API in Gateway. API Gateway
  • 9. Lambda What is Lambda and what’s cool about it? Lambdas are small independent units of code that literally are a single function. They’re executed in an entirely managed runtime, meaning you simply upload the executable and trigger them.
  • 10.
  • 11.
  • 13. Best practices When writing code for lambda
  • 14. ● Separate the core logic of your function from the boilerplate and other dependencies ● Take advantage of Execution Context reuse, limit the re-initialisation of variables/objects on every invocation ● Minimise your package size Additional reading: DZONE Article AWS Whitepaper ● Control the dependencies in your function's deployment package. AWS provides some, but updates them periodically which could subtly change your code ● Minimise the complexity of your dependencies. Prefer simpler frameworks that load quickly on Execution Context startup ● There are concurrency limits to be aware of and by default these are global in your AWS account. Prefer function-specific reserved resources A few best practices when writing lambdas
  • 15. ● Cold start versus warm start execution performance ● Improving cold start performance is looking at the runtime environment. JS and other interpreted languages have the advantage here ● Small executables for v8 optimisations. Minify and uglify your code, removing comments and anything unnecessary Considerations
  • 16. Shameless self-promotion Other tools and libraries do exist I have created a small lightweight tool which leverages a middleware pattern to abstract out boilerplate code from your Lambdas. Inspired by MiddyJS Mambda ChocPanda
  • 18. const lambda = require('mambda'); const jsonBodyParser = require('mambda/middlewares/json-body-parser'); const httpErrorHandler = require('mambda/middlewares/http-error-handler'); async function myAsyncHandler(event, context, callback) { // try { // const body = headers['Content-Type'] === 'application/json') // ? JSON.parse(event.body) // : {} // } catch (error) { // other error handling... // return { statusCode: 422, body: 'Unprocessable entity, invalid json in request body' } // } const body = event.body; // A javascript object from the deserialized json in the original event const foo = await bar(); //... function code return someOperation(foo); } exports.handler = lambda(myAsyncHandler) .use(jsonBodyParser()) .use(httpErrorHandler())
  • 19. The life of a Mambda function
  • 20. const lambda = require('mambda'); const AWS = require('aws-sdk') const myHandler = s3 => (event, context, callback) => { var params = { Bucket: process.env.BUCKET_NAME, Key: process.env.BUCKET_KEY, Body: process.env.BODY }; // function code... s3.putObject(params, function(err, data) { if (err) { callback(err) } else { callback(null, 'Put the body into the bucket! YAY!') } }); } exports.handler = lambda({ init: () => new AWS.S3(), handler: myHandler });
  • 21. Simple Recruitment tool ● 2 Javascript front ends hosted as static websites within S3 buckets ● Uses a lambda to create signed urls to upload CVs to another s3 bucket ● Uses lambda to send an SNS notification to the hiring manager when a new candidate applies for a role ● Store the candidate’s name and any other information in a DynamoDb database
  • 22. const mambda = require('mambda'); const { jsonBodyParser, httpErrorHandler, httpHeaderNormalizer } = require('mambda/middlewares'); const optionsRequestInterceptor = require('./options-request-interceptor'); module.exports = fn => { const { init, handler = fn } = fn; return mambda({ init, handler, middlewares: [httpHeaderNormalizer(), jsonBodyParser(), httpErrorHandler(), optionsRequestInterceptor()] }); }; Preconfigure your middlewares
  • 23. const generateUrls = ({ s3Instance }) => ({ body }) => { const applicationId = uuid.v4(); const urls = body.reduce( (accumulated, fileName) => ({ ...accumulated, [fileName]: s3Instance.getSignedUrl('putObject', { Bucket: process.env.S3_BUCKET, Key: `${applicationId}/${fileName}`, Expires: 120 }) }), {} ); return { statusCode: 200, body: JSON.stringify({ applicationId, urls }) }; }; exports.post = lambdaWrapper({ init: () => ({ s3Instance: new S3({ signatureVersion: 'v4' }) }), handler: generateUrls }); ● Initialised connection to the s3 API ● Deserialised request body ● Cold start initialisation
  • 24. Some things I haven’t discussed ● Using swagger annotations in the JS code to describe the handler functions and configure the API gateway ● Setting up development stages and using blue-green deployments API Gateway ● Increased testability of the modules for lambda written with Mambda ● Infrastructure as code (Terraform, AWS CDK, Cloudformation, etc...)