SlideShare a Scribd company logo
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.
Serverless APIs with JavaScript - Matt Searle - ChocPanda
Serverless APIs with JavaScript - Matt Searle - ChocPanda
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

PDF
Building serverless apps with MongoDB Atlas and AWS Lambda
PDF
aws lambda & api gateway
PDF
BUILDING Serverless apps with MongoDB AtLAS, AWS Lambda and Step Functions
PDF
Skillenza Build with Serverless Challenge - Advanced Serverless Concepts
PDF
What is AWS lambda?
PPTX
Getting Started with Serverless PHP
PDF
Microservices with AWS Lambda and the Serverless Framework
PDF
Communication tool & Environment for Remote Worker
Building serverless apps with MongoDB Atlas and AWS Lambda
aws lambda & api gateway
BUILDING Serverless apps with MongoDB AtLAS, AWS Lambda and Step Functions
Skillenza Build with Serverless Challenge - Advanced Serverless Concepts
What is AWS lambda?
Getting Started with Serverless PHP
Microservices with AWS Lambda and the Serverless Framework
Communication tool & Environment for Remote Worker

What's hot (19)

PDF
Aws Lambda in Swift - NSLondon - 3rd December 2020
PPTX
AWS Lambda
PPTX
Serverless by examples and case studies
PDF
AWS Lambda and Serverless framework: lessons learned while building a serverl...
PDF
Continuous Deployment in AWS Lambda
ODP
A Step to programming with Apache Spark
PDF
Serverless Architectures on AWS Lambda
PPTX
2016 - Serverless Microservices on AWS with API Gateway and Lambda
PDF
Serverless Framework Workshop - Tyler Hendrickson, Chicago/burbs
PDF
How to Use AWS Lambda Layers and Lambda Runtime
PPTX
AWS Jungle - Lambda
PPTX
Aws serverless architecture
PPTX
Serverless design considerations for Cloud Native workloads
PDF
locize tech stack
PPTX
ServerlessPresentation
PDF
AWS Lambda Tutorial
PPTX
Introduce AWS Lambda for newbie and Non-IT
PDF
AWS Step Functions를 이용한 마이크로서비스 개발하기 - 김현민 (4CSoft)
PPTX
AWS - Lambda Fundamentals
Aws Lambda in Swift - NSLondon - 3rd December 2020
AWS Lambda
Serverless by examples and case studies
AWS Lambda and Serverless framework: lessons learned while building a serverl...
Continuous Deployment in AWS Lambda
A Step to programming with Apache Spark
Serverless Architectures on AWS Lambda
2016 - Serverless Microservices on AWS with API Gateway and Lambda
Serverless Framework Workshop - Tyler Hendrickson, Chicago/burbs
How to Use AWS Lambda Layers and Lambda Runtime
AWS Jungle - Lambda
Aws serverless architecture
Serverless design considerations for Cloud Native workloads
locize tech stack
ServerlessPresentation
AWS Lambda Tutorial
Introduce AWS Lambda for newbie and Non-IT
AWS Step Functions를 이용한 마이크로서비스 개발하기 - 김현민 (4CSoft)
AWS - Lambda Fundamentals
Ad

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

PDF
10 Tips For Serverless Backends With NodeJS and AWS Lambda
PPTX
AWS Lambda, Step Functions & MongoDB Atlas Tutorial
PDF
locize tech talk
PDF
Serverless Computing
PDF
AWS Lambda Functions A Comprehensive Guide
PDF
Deploying Serverless Cloud Optical Character Recognition in Support of NASA A...
PDF
Serverless OCR for NASA EVA: AWS Meetup DC 2017-12-12
PDF
Serverless Optical Character Recognition in support of Astronaut Safety AWS M...
PPTX
Serverless
PDF
Jumpstart your idea with AWS Serverless [Oct 2020]
PDF
Serverless Architectural Patterns & Best Practices
PDF
AWS Lambda Documentation
PDF
GreatLearning Webinar - Microservices and Event-Driven Architecture.pdf
PDF
Into The Box | Alexa and ColdBox Api's
PDF
Serverless architectures-with-aws-lambda
ODP
DPD:AWS Developer Training
PDF
Building a serverless company on AWS lambda and Serverless framework
PDF
Running R on AWS Lambda by Ana-Maria Niculescu
PPTX
AWS Accelerated Program - Session 3 - Serverless Services.pptx
PPTX
Building Cross-Cloud Platform Cognitive Microservices Using Serverless Archit...
10 Tips For Serverless Backends With NodeJS and AWS Lambda
AWS Lambda, Step Functions & MongoDB Atlas Tutorial
locize tech talk
Serverless Computing
AWS Lambda Functions A Comprehensive Guide
Deploying Serverless Cloud Optical Character Recognition in Support of NASA A...
Serverless OCR for NASA EVA: AWS Meetup DC 2017-12-12
Serverless Optical Character Recognition in support of Astronaut Safety AWS M...
Serverless
Jumpstart your idea with AWS Serverless [Oct 2020]
Serverless Architectural Patterns & Best Practices
AWS Lambda Documentation
GreatLearning Webinar - Microservices and Event-Driven Architecture.pdf
Into The Box | Alexa and ColdBox Api's
Serverless architectures-with-aws-lambda
DPD:AWS Developer Training
Building a serverless company on AWS lambda and Serverless framework
Running R on AWS Lambda by Ana-Maria Niculescu
AWS Accelerated Program - Session 3 - Serverless Services.pptx
Building Cross-Cloud Platform Cognitive Microservices Using Serverless Archit...
Ad

Recently uploaded (20)

PDF
Electronic commerce courselecture one. Pdf
PDF
Machine learning based COVID-19 study performance prediction
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Spectral efficient network and resource selection model in 5G networks
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPTX
sap open course for s4hana steps from ECC to s4
PPTX
Big Data Technologies - Introduction.pptx
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
KodekX | Application Modernization Development
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Empathic Computing: Creating Shared Understanding
PDF
Network Security Unit 5.pdf for BCA BBA.
Electronic commerce courselecture one. Pdf
Machine learning based COVID-19 study performance prediction
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Spectral efficient network and resource selection model in 5G networks
Digital-Transformation-Roadmap-for-Companies.pptx
Advanced methodologies resolving dimensionality complications for autism neur...
sap open course for s4hana steps from ECC to s4
Big Data Technologies - Introduction.pptx
MYSQL Presentation for SQL database connectivity
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Chapter 3 Spatial Domain Image Processing.pdf
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
NewMind AI Weekly Chronicles - August'25 Week I
Diabetes mellitus diagnosis method based random forest with bat algorithm
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
KodekX | Application Modernization Development
Encapsulation_ Review paper, used for researhc scholars
Empathic Computing: Creating Shared Understanding
Network Security Unit 5.pdf for BCA BBA.

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.
  • 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...)