Skip to main content

Upstash Redis in AWS Lambda

note

This tutorial uses @upstash/redis which is designed for serverless runtimes for efficient connection handling. You can use your favorite Redis client, but you may have to deal with connection issues as described here.

Database Setup

Create a Redis database using Upstash Console or Upstash CLI. Select the same region with your AWS Lambda to minimize the latency. Copy the UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN for the next steps.

Project Setup

We will use Serverless Framework but you can use AWS SAM or others.

Run sls and select the AWS - Node.js - HTTP API

โžœ  dev sls

Creating a new serverless project

> What do you want to make? AWS - Node.js - HTTP API
> What do you want to call this project? quickstart-aws-lambda

โœ” Project successfully created in quickstart-aws-lambda folder

> What org do you want to add this service to? [Skip]

> Do you want to deploy now? No

Install dependencies: npm install @upstash/redis

The Code

Update handler.js as below and replace REST_URL and REST_TOKEN:

const { Redis } = require("@upstash/redis/with-fetch");

module.exports.hello = async (event) => {
const redis = new Redis({
url: 'UPSTASH_REDIS_REST_URL',
token: 'UPSTASH_REDIS_REST_TOKEN',
})

const data = await redis.incr('counter');
return {
statusCode: 200,
body: JSON.stringify(
{
view_count: data,
}
),
};
};

Deploy

Deploy your function with sls deploy

The endpoint of the AWS Lambda function will be printed.

Repo

https://github.com/upstash/upstash-redis/tree/main/examples/aws-lambda