How to use feature flags with AWS Lambda
Tags: featuremanagement, featureflags, aws, howto
Published: 2023-10-25 22:34:09

One of the most important technological breakthroughs of the century has been the internet — a digital network that makes the rest of the world feel like our next-door neighbor. Within the realm of the Internet, a recent technology known as cloud computing has paved the way for software developers to rent and manage remote servers in the cloud for hosting their applications. A smaller component of this technology is called Function as a Service, abbreviated as FaaS. FaaS removes the complexity of managing a full-blown backend server, enabling developers to focus solely on writing and executing the necessary functions required to run their applications.

When FaaS and feature flags are combined, you can toggle individual functions or code blocks in those functions on or off without touching its code. Let's take a closer look.

## What are feature flags?

A feature flag is a boolean value linked to a feature that enables you to toggle the feature on or off by changing its value. Feature flags can be used with many programming languages and technologies including cloud platforms like [AWS Lambda](https://aws.amazon.com/lambda/). Today, I'll demonstrate how to use a feature flag to control the response of a [Node.js](https://nodejs.org/en) API endpoint in AWS Lambda. Let's get started.

Before we begin, let's review the essential prerequisites you'll need:

### Prerequisites

- [A verified AWS account](https://portal.aws.amazon.com/billing/signup)
- Basic [Node.js](https://nodejs.org/en/) and AWS knowledge

## Using feature flags with AWS Lambda

[AWS Lambda](https://aws.amazon.com/lambda/) is described on [AWS's Website](https://aws.amazon.com/lambda/) as: "Run code without thinking about servers or clusters". This means, rather than setting up a full-blown backend server to handle requests from your app, you can define functions in the language or runtime of your choice to be executed via a trigger (more on this shortly).

To demonstrate how to use feature flags with AWS Lambda I'll use [ConfigCat's hosted feature flag service](https://configcat.com). They offer a [free tier account](https://app.configcat.com/signup) for experimentation, and there's no limit to the number of feature flags you can implement. ConfigCat also provides an extensive [list of SDKs](https://configcat.com/docs/sdk-reference/overview/) for easy integration.

### Up and running with AWS Lambda

To make this demo fun, I'll create a music search app that returns a JSON object of songs produced by a specific artist. I'll use "Eminem" for example. To get up and running with AWS Lambda, you'll need to do the following:

1. Sign up for a [Free Tier AWS account](https://aws.amazon.com/free/)

2. In the console, click the services menu at the top left, select **compute** > **Lambda** then create a new function:

![Getting started - create a function](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o1rxw2n9bj60075hsvq6.png)

3. Create a new function with the following details (starting from top to bottom):

- Select the first option - Author from scratch

- Function name: `myMusicSearchFunction`

- Runtime: `Node.js 18.x`

- Architecture: `x86_64`

- Permissions: - Leave the default option

Then click **Create function**.

![Creating a Lambda function](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n0gupxidzpizn1j05jd1.png)

4. Add a trigger for executing the function. I've selected an API Gateway trigger. As a result, when a GET request is sent to the function endpoint it will trigger the execution of the function.

![Creating an API Gateway trigger](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oqe2mhexwh1zys5mg18z.png)

If all went correctly you should be able to see the following response by sending a GET request to the endpoint generated by the trigger:

![API Gateway trigger created](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qzlvg599x3cvccb5mqq9.png)

Response:

```json
"Hello from Lambda!"
```

### Coding the sample app

Let's change the default code to create a simple music search endpoint that returns a list of songs produced by Eminem.

If you prefer to follow along, I've included a sample Node.js app [here](https://github.com/configcat-labs/feature-flags-aws-lambda-sample/). Feel free to clone it to your computer.

#### Setting up the sample app

Because my function will be executed in a node runtime environment, I've included [ConfigCat's Node SDK](https://configcat.com/docs/sdk-reference/node/) as a dependency. With this SDK, the app will be able to access my [ConfigCat dashboard](https://app.configcat.com) and probe the feature flag value. I'll use the `node-fetch` package to fetch the list of songs. The `package.json` contains everything the app needs:

Contents of `package.json`:

```json
{
  "name": "feature-flags-aws-lambda-sample",
  "type": "module",
  "version": "1.0.0",
  "description": "A companion repo for How to use feature flags with AWS Lambda",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Chavez Harris",
  "license": "ISC",
  "dependencies": {
    "configcat-node": "^9.1.1",
    "node-fetch": "^3.3.1"
  }
} 
```

1. Run `npm install` to install the packages.

2. Open the `index.mjs` file. At the top, import the ConfigCat node and fetch package, then create the ConfigCat client using your SDK key (More on this in the next section):

```js
import * as configcat from "configcat-node";
import fetch from "node-fetch";

let configCatClient = configcat.getClient(
  "YOUR-CONFIGCAT-SDK-KEY"
);
```

3. Below the above code block, I'll create a [handler function](https://docs.aws.amazon.com/lambda/latest/dg/nodejs-handler.html) to be executed with the following code in the body:

```js
export const handler = async(event) => {
  // Query the value of the feature flag and assign it to a constant
  const isSearchByArtisteEnabled = await configCatClient.getValueAsync(
    "searchbyartiste",
    false
  );

  let response_message = "";

  // If the feature flag is enabled
  if (isSearchByArtisteEnabled) {
    // Fetch a list of songs by eminem
    const myData = await fetch(`https://api.deezer.com/search?q=eminem`);
    const myDataAsJson = await myData.json();
    response_message = myDataAsJson;
  } else {
    // If the feature flag is disabled
    response_message = "Sorry, this feature is not available";
  }

  // Construct and return a response
  const response = {
      statusCode: 200,
      body: JSON.stringify(response_message),
  };
  return response;
};
```

Using a feature flag, I will control how the API responds. When the feature flag is on, it will return the list of songs by Eminem and when it is off the response will be "Sorry, this feature is not available". To do this, I'll use [ConfigCat's feature flag service](https://configcat.com).

### Integrating with ConfigCat

1. First, you'll need to [sign up for a free account](https://app.configcat.com/signup).

2. In your [dashboard](https://app.configcat.com), create a feature flag with the following details.

![Creating a feature flag](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ckydyp8b63h0lpm4bnn1.png)

Ensure that you update the code in `index.mjs` with your **ConfigCat SDK key and feature key**.

### Uploading the code to AWS

To update the code of the AWS Lambda function with the code I wrote, I'll zip all the files, including the `node_modules` folder, and upload it to AWS.

1. In the root folder, run the following command to zip all the files:

```sh
zip function.zip *
```

This will create a `function.zip` file.

2. On the function page, with the code tab selected, upload your `function.zip` file

![Uploading the zip file](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lud0theldn9smgwy5siv.png)

3. Deploy the function.

By visiting the API endpoint in your browser, you should get the following response:

![Getting an API response in the Browser](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1h815d5m50s77f73koyd.png)

## Did it work?

1. Head over to the [ConfigCat dashboard](https://app.configcat.com) and **turn off** the feature flag.

2. Refresh the page, and you should see:

![App - feature flag turned off](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l025mgl23dcwd7u2tuh9.png)

Congrats! You did it!

## Conclusion

The flexibility of feature flags lends itself to many technologies and we've explored how to use them in AWS Lambda without any difficulties.
Combining feature flags with cloud functions can unlock a world of many possibilities because you can extend your cloud functions' capabilities. ConfigCat makes it easy to integrate feature flags in [many languages and frameworks](https://configcat.com/docs/sdk-reference/overview/).

In addition to adding feature flags, you can set up user targeting rules for releasing features to specific user groups. This is most useful when setting up and doing A/B testing. With an account, you get a generous [free tier](https://app.configcat.com/signup) for low-volume use cases which is ideal for getting started with feature flags.

## Stay connected

For more posts and other announcements, follow ConfigCat on [Twitter](https://twitter.com/configcat), [Facebook](https://www.facebook.com/configcat), [LinkedIn](https://www.linkedin.com/company/configcat/), and [GitHub](https://github.com/configcat). The most lovable feature flag service ever.