Skip to main content
This guide demonstrates how to use Upstash Redis in AWS Lambda functions. The HTTP-based connection makes it perfect for serverless environments where traditional TCP connections are problematic.

Why Upstash Redis for Lambda?

  • Connectionless: HTTP-based, no connection pooling needed
  • Fast cold starts: No connection overhead
  • Pay-per-request: Aligned with Lambda’s pricing model
  • Global: Low latency from any AWS region

Prerequisites

1

Create AWS Account

Sign up for an AWS account if you don’t have one
2

Install AWS CLI

Set up and configure AWS CLI with your credentials
3

Create Upstash Redis Database

Create a Redis database using Upstash Console or Upstash CLI

Quick Start

Project Setup

1

Create Project Directory

2

Initialize npm and Install Dependencies

3

Create Lambda Function

Create index.js with your Lambda handler code

Example: Counter Function

This example implements a simple counter that increments on each Lambda invocation.

Deployment

Create Deployment Package

1

Install Dependencies

2

Create ZIP Archive

This creates a ZIP file containing your code and node_modules.

Deploy with AWS CLI

Replace <YOUR_LAMBDA_EXECUTION_ROLE_ARN> with your Lambda execution role ARN. This role must have basic Lambda execution permissions.

Get Your Upstash Credentials

From your Upstash Console:
  1. Select your Redis database
  2. Click on the REST API tab
  3. Copy the UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN

Advanced Examples

Session Storage

Rate Limiting

Caching API Responses

Best Practices

Use Environment Variables

Always use environment variables for credentials, never hardcode them:

Error Handling

Optimize Cold Starts

Initialize the Redis client outside the handler to reuse connections across warm starts:

Infrastructure as Code

AWS SAM

For AWS SAM examples, see the aws-sam example directory.

AWS CDK

For AWS CDK examples (TypeScript and Python), see:

Terraform

For Terraform deployment examples, see the Terraform example directory.

Testing Locally

Invoke Function Locally

Using AWS SAM CLI

Monitoring

CloudWatch Logs

Add logging to track Redis operations:

Troubleshooting

Common Issues

Ensure your Lambda function has internet access. If in a VPC, verify NAT Gateway or VPC endpoints are configured.
Make sure node_modules is included in your deployment package. Run npm install before creating the ZIP file.
Verify environment variables are set in Lambda configuration:

Next Steps

Cloudflare Workers

Deploy with Cloudflare Workers

Next.js

Use Redis in Next.js applications

Basic Usage

Learn more Redis operations

GitHub Examples

Browse all examples on GitHub