Moving Static Assets Out of Lambda Functions

Here, you'll learn how to write code to move static assets out of Lambda functions.

Fetching static assets #

Traditional web applications bundle code and assets, and web servers are responsible for sending both to client devices. Translated to the Lambda world, that would mean including client-side JavaScript and web assets in a Lambda function, and creating at least another API endpoint and a new function to send those files to clients on demand.

Serving application contents such as images, style sheets, client-side JavaScript and HTML files through a Lambda function is a bad idea. Those files are typically public and require no authorisation. They do not change depending on individual users or requests. Paying for a Lambda function and an API call for every file request would increase operational costs significantly and introduce two unnecessary intermediaries between the user and file contents, increasing latency and degrading the user experience.

With serverless applications, it’s much more usual to put static assets somewhere for clients to fetch them directly, for example on S3. In fact, this is so common that S3 can pretend to be a web server. It even offers some basic web serving features out of the box, such as redirects and customising response headers. Browsers can directly load files from S3 using HTTPS.

In the previous chapters, you uploaded private files to S3 and generated temporary security grants for browsers to download them. You can also upload public files, and client devices will be able to access them without a particular temporary grant. There will be no need to involve a Lambda function in the process at all. That way, you only need to pay for data transfer for static assets. This is significantly cheaper than adding another API call and a function execution. Users will also get faster responses. It will be better for everyone.

Use a content distribution network #

For high-traffic applications, it’s usual to put a content distribution network (CDN) between users and S3 files, making the application even faster. AWS has a CDN called CloudFront, which can cache static files from S3 all over the world and even compress them automatically before sending them to users. CloudFront can also run Lambda functions to perform some quick business logic such as transforming responses or modifying incoming or outgoing headers. For your simple application, this would be unnecessary, so you’ll just use S3 directly.

Let’s restructure the application to look as in the figure given below. The client can load static assets directly from S3 without going through Lambda. A single API operation should send back both upload and download signatures, and client code can take over the remaining coordination tasks.

Get hands-on with 1000+ tech skills courses.