Serverless architectures are powered by a cloud service such as AWS Lambda. This cloud service manages the servers on which the application runs, thereby taking the burden of managing infrastructure and scaling off the developer’s shoulders.

Serverless technologies have been increasing in popularity. The absence of server provisioning makes them particularly enticing. In this article, we’ll consider a few dos and don’ts to look out for when building a serverless application, specifically when using the serverless framework.

Limit the scope of your services and functions

Serverless architectures work best with a microservices or service-oriented model. While you could technically build a complete content management system (CMS) as a set of Lambda functions, the serverless approach is best suited for building small, self-contained services that serve a larger application. The serverless framework encourages this approach by using the term “service” rather than “app”.

Lambda functions should be designed as small, focused units of functionality. For instance, suppose we have a web app that works similarly to Google Translate Word Lens. It extracts text in a foreign language from images and translates them to English. A poorly designed service would handle everything, from rendering the page where you upload the image to displaying the translated text. A better approach would be to reduce the scope of the service, so it takes in only the image and returns the translated text. With this structure, our service is free to serve mobile apps as well.

The ability of a Lambda function to invoke another is a useful tool that helps with keeping functions focused. In our image-translation service, we could have a function that extracts text from images and one that translates text to English. We could then expose a third function that takes in an image and calls these two:

    const AWS = require('aws-sdk');
    const lambda = new AWS.Lambda();

    module.exports.extractTextFromImage = (event, callback, context) => {
      ...
    }

    module.exports.translateText = (event, callback, context) => {
      ...
    }

    module.exports.translateTextFromImage = (event, callback, context) => {
      let params = {
        FunctionName: 'extractTextFromImage',
        InvocationType: 'RequestResponse',
        Payload: JSON.parse(event.body).image
      };

      lambda.invoke(params).promise()
        .then(response => {
          params = {
            FunctionName: 'translateText',
            InvocationType: 'RequestResponse',
            Payload: JSON.parse(response).text
          };
          return lambda.invoke(params).promise();
        })
        .then(response => callback(null, response))
        .catch(callback);
    };

For operations with independent results, we can invoke the functions asynchronously by setting the InvocationType to Async.

Make your functions stateless

Your Lambda functions should be stateless. This means they shouldn’t persist any data or session information in the environment beyond the lifetime of a single request.

Why? AWS Lambda typically launches a new instance of your function to serve a new request, with each function running in its own isolated environment. However, as part of its auto-scaling, a function instance might be reused (especially if you have low traffic). In such a situation, only the code in the handler function gets executed in the new run. This means any variables not local to the function retain any changes from previous runs.

This can give rise to some weird bugs. Here’s an example:

    let tweets = [];
    module.exports.handler = (event, callback, context) => {
        for (tweet of getTenRecentTweetsFromTwitterApi()) {
            if (isAboutTech(tweet)) {
                tweets.push(tweet.id);
            }
        }
        callback({ body: tweets});
    }

The first time this function is invoked, ten recent tweets will be fetched and filtered. On subsequent invocations, if the same instance is used, the variable tweets will still hold tweets from the previous run.

We can refactor the function above to avoid this by replacing the loop-and-push operation with an assignment:

    let tweets = [];
    module.exports.handler = (event, callback, context) => {
        tweets = getTenRecentTweetsFromTwitterApi()
          .filter(isAboutTech)
          .map(tweet => tweet.id);
        callback({ body: tweets});
    }

Optimize for reuse

This is on the flip side of the above tip. This involves taking advantage of the fact that Lambda might reuse your function instances to make some performance optimizations.

Let’s continue with the example of our image-translation service. This time, our function translateTextFromImage uses a few packages to do its job, rather than delegating to other functions. It also keeps a log of every translation in a database. Here’s one way we could write it:

    module.exports.translateTextFromImage = (event, callback, context) => {
        let db= require('db');
        let encode = require('some-encoding-package');
        let extractTextFromImage = require('another-package');
        let translate = require('yet-another-package');

        let body = JSON.parse(event.body);
        let image = encode(body.image);
        let text = extractTextFromImage(image);
        let translated = translate(text, body.from, body.to);
        let conn = db.createConnection(process.env.MONGODB_URL);
        conn.model('TranslationLog')
            .create({text, translated}, (err, res) => {
                callback({ body: translated});
            });
    }

However, if we wanted to take advantage of execution context reuse, it would be better to write it like this:

    let db= require('db');
    let encode = require('some-encoding-package');
    let extractTextFromImage = require('another-package');
    let translate = require('yet-another-package');
    let conn = db.createConnection(process.env.MONGODB_URL);

    module.exports.translateTextFromImage = (event, callback, context) => {
        let body = JSON.parse(event.body);
        let image = encode(body.image);
        let text = extractTextFromImage(image);
        let translated = translate(text, body.from, body.to);
        conn.model('TranslationLog')
            .create({text, translated}, (err, res) => {
                callback({ body: translated});
            });
    }

Reduce latency by keeping containers warm

As we mentioned earlier, AWS Lambda runs each function in its own isolated container. Sometimes a container is kept alive and reused on multiple requests. After a period of time with no activity, the container will be destroyed.

This means AWS has to create and launch a new container for the next request. This is called a cold start, and it causes a performance hit by introducing some latency (the time it takes to provision and start up the container). This can cause your function to take several seconds to respond and tie up a large application with other actions waiting for the function’s output.

You can reduce the latency of your Lambda functions by scheduling a CloudWatch event that pings the function every few minutes to keep it alive, as outlined here.

You can also make use of serverless-plugin-warmup, a plugin for the serverless framework that keeps Lambda functions warm. Here’s a guide on how to do that.

Integrate testing into your workflow

Testing is an integral part of developing software, and with serverless, it’s no different. With AWS Lambda, however, things are a bit more involved. Functions are stateless, so testing locally is more difficult.

There are varying schools of thought on how best to test Lambda functions. One useful thing to keep in mind is to use dependency injection to make your functions more easily testable. For instance, the following function is used to add a new user:

    const db = require('db').connect();
    const mailer = require('mailer');

    module.exports.createUser = (event, context, callback) => {
      db.insert('users', JSON.parse(event.body))
        .then((user) => { 
          mailer.sendWelcomeEmail(user.email);
          callback(null, user);
        });
    };

We could extract the logic into a new module that has its dependencies injected:

    // users/create.js
    module.exports.createUser = (db, mailer) => {
      return (data) => {
        db.insert('users', data)
        .then((user) => { 
          mailer.sendWelcomeEmail(user.email);
          return user;
        });
      };
    }

    // handler.js
    const db = require('db').connect();
    const mailer = require('mailer');
    const createUser = require('users/create')(db, mailer);

    module.exports.createUser = (event, context, callback) => {
      createUser(JSON.parse(event.body))
        .then(user => callback(null, user));
    };

Now we can proceed to write traditional unit tests for the createUser function and inject mock database and mailer objects.

It’s also important to test our functions as a whole (integration tests), both locally and on deployments. The serverless framework allows you to invoke your functions locally in a Lambda-like environment with custom event data by running the serverless invoke local command.

For remote tests, we can make use of an AWS API Gateway feature called stages. Stages are specific releases of a service. By default, the serverless framework deploys to the dev stage, which is where we typically run tests. Once a release has passed testing, we can then deploy to a master or production stage. For more resources on testing, see Designing testable Lambda functions and How to Test Serverless Applications.

Conclusion

Serverless computing is a powerful tool that allows you to unleash your inner code ninja by freeing you from the hassle of DevOps. Knowing when to use it and the right things to do can go a long way in improving your experience with it. Here are some more useful resources on building apps for AWS Lambda: