70 %
Chris Biscardi

The Quick Guide to Serverless

There are two main products that I would recommend to anyone looking to use serverless architectures: Netlify Functions and AWS Lambda.

Netlify Functions

The option I suggest using first is Netlify Functions because it will allow you to get the hang of what a serverless function is and how it works while avoiding a lot of the complexity that comes with AWS accounts, IAM roles, etc.

Netlify's serverless functions look exactly like a regular function, exported in CommonJS format as handler. Note that this example also uses async functions which means we can return an object with an http status code (200) and some content.

functions/hello-world.js
JS
exports.handler = async (event, context) => {
return {
statusCode: 200,
body: "Hello World!"
}
}

Netlify will take the function in this file and deploy it to an endpoint for you. It will look something like https://my-site.netlify.app/.netlify/functions/hello-world, which you can then visit in the browser, call via curl, or use any other method you'd like.

Using JavaScript is the easiest way to get a function running on Netlify (since there is no build step required) but they also support Golang (which will require a build configuration).

hello-world.go
go
func handler(ctx context.Context, request events.APIGatewayProxyRequest) (*events.APIGatewayProxyResponse, error) {
return &events.APIGatewayProxyResponse{
StatusCode: 200,
Body: "Hello, World",
}, nil
}

Types of functions

Netlify's functions support offers sync (or request-response) functions and async (or background) functions. The difference between these two types is in the way the client calls them and how long they're allowed to run.

Sync functions will return a response to the client (while the client waits for the response) and can run for a maximum of 10 seconds. Use cases for these can include API responses, rendering HTML, and redirecting users.

Async functions return immediately to the client and can then run for up to 15 minutes after the response is sent. These can be used for background jobs such as optimizing images or doing some data processing and then sending an email to the user with the data results.

AWS Lambda

Once you reach the limits of Netlify Functions, you'll end up wanting something that can support patterns like Change Data Capture on your database, react to