Serverless solutions for client-side apps with Lambda and Chalice

What do you do when you’ve built a client-side web application and suddenly find yourself in need of a server? The usual approach is to spin up a server through a service like Amazon EC2 or Heroku, but in a lot of cases, this can be overkill.

Enter: Lambda

In a nutshell, Lambda is a service that runs your code only when it’s needed: for example, in response to an event or an HTTP request. A process gets started and the function is executed. Once the function has run, the process gets shut down. You only pay for the CPU time used.

Currently, these Lambda functions can be written in Python, Java or Node. Usually, you’d have to set this up and configure it yourself. However, if you’re into Python, you now have another option.

Chalice is a nifty tool that Amazon released recently that does all the boring leg work for you. Chalice gives you a framework for creating Lambda functions written in Python, with a Rest API. It also comes with a command line tool to create and connect the various AWS resources required (CloudFront, API Gateway, the Lambda function, CloudWatch).

Here is an example

At RBMA Radio we are using micro-services to perform various tasks. One of them determines the duration of an MP3 file.

Here’s how we set that up:

1. Install Chalice

$ pip install chalice

2. Create a new project with Chalice

$ chalice new-project mp3duration

This creates a sample app:

At this point you are ready to deploy:

$ cd mp3demo
$ chalice deploy
Initial creation of lambda function.
Creating role
Creating deployment package.
Lambda deploy done.
Initiating first time deployment…
Deploying to: dev
https://some-random-app-id.execute-api.us-east-1.amazonaws.com/dev/

If you hit that URL, you can see, as expected:

{
"hello": "world"
}

Now we’re ready to write our little Python app to determine the duration of any given MP3 file. We use Mutagen which gives us exact results. The code just looks like any other Python code you would usually write. If you have ever used Flask you should feel right at home as Chalice’s API is modelled after Flask’s.

Let’s update app.py to the following.

We can then redeploy the app from the command line again, and we’re ready to go. Requests to our Chalice app with a url parameter providing the URL of the MP3 file we want to analyse will return a JSON object with the duration of the MP3 file in seconds. That’s really all there is to it.

Lambda + Chalice is a great solution for these types of problems. Amazingly, the first million requests per month are free and more than 3 million seconds of CPU time are included. That number goes down a little bit if you need more RAM, but hey!

Authors: Philipp Bosch and Alice Rose for A Color Bright.