New:Upstash has a remote MCP server

Netlify Redis: Add a Cache and Rate Limits to Netlify Functions with Upstash

Cahid Arda OzCahid Arda Oz
8 min read

A Netlify Function that calls a slow API takes the hit on every request. And anything in memory is local to one running copy of the function, so other copies can’t see it. This means if we want to share a cache, rate limiting counter or session between requests, we need some kind of store outside the function.

Upstash Redis is a good fit for this, because it supports HTTP commands. This means we can use the same client in Netlify Functions (Node.js) and Edge Functions (Deno). This client requires two environment variables, but no connection setup.

Does Netlify have Redis?

Netlify does not have built-in Redis. Its own data products are Netlify Blobs (a key/value store for files and unstructured data) and Netlify Database (managed Postgres). For Redis, you use environment variables to connect to an external provider such as Upstash.

Netlify has no one-click Redis extension at the moment, so the approach below adds the two environment variables by hand, and it works on every Netlify plan.

What Redis adds for caches and counters

Caches, rate limiters and counters need a few things from a store that Redis is built for:

  • Expiry: set a TTL (time to live) on any key and Redis deletes it when it runs out, so a cache cleans itself up.
  • Atomic updates: INCR, sorted sets and Lua scripts let many concurrent requests update the same key without losing writes, which is what a rate limiter or a view counter needs.
  • Read your writes: writes go through one primary, and the SDK reads its own writes automatically.
  • Data types: strings, hashes, lists, sets, sorted sets, streams and JSON.
  • Works anywhere: the same database is reachable from Netlify, local dev, CI or any other host.

Create the database and connect it to your Netlify project

  1. Sign up for Upstash and create a free Redis database. Choose AWS us-east-2 (Ohio) as the region, because new Netlify projects run functions in Ohio by default (check Functions > Region for older projects). If a coding agent is building the site for you, it can also get a scratch database with one POST to start-redis, which you claim in your account to keep; it is deleted after 3 days unless claimed.
  2. Open the database's Details page. In the Connect box, the REST tab shows the REST URL and the REST token. Copy both.
  3. In Netlify, create the project from your Git repository or upload a folder:

Netlify’s new project page with options to import from Git or upload

  1. Go to Project configuration -> Environment variables -> Add a variable -> Add a single variable. Add UPSTASH_REDIS_REST_URL with the value of the REST URL and UPSTASH_REDIS_REST_TOKEN with the value of the token. If your plan offers it, check Contains secret values for the token, so that only code running on Netlify can read the real value (this flag cannot be removed later):

Adding UPSTASH_REDIS_REST_URL in Project configuration -> Environment variables

  1. Redeploy the site to make the new environment variables available to the functions.

Alternatively, you can set the environment variables via command line with netlify env:set or load them from a local file with netlify env:import .env.

Note that on the Free plan, you can only set variables for All scopes. For setting them for specific scopes, you’ll need a Pro plan or higher. Functions are always included in All scopes, though. Also make sure to not set the environment variables in netlify.toml since variables set in this file are only available to the Builds and Post processing scopes. Hence, the value of the variable would be undefined within a function.

Cache a slow call in a Netlify Function

Install the client in your project:

npm install @upstash/redis @netlify/functions

This function checks Redis first. On a miss, it loads the data, stores it for 30 seconds and returns it. Redis.fromEnv() reads the two UPSTASH_REDIS_REST_* variables:

// netlify/functions/products.mts
import type { Config } from "@netlify/functions";
import { Redis } from "@upstash/redis";
 
const redis = Redis.fromEnv();
 
async function loadProducts() {
  // Replace with your real database or API call
  return [{ id: 1, name: "Nordic Wool Throw", price: 89 }];
}
 
export default async () => {
  const cached = await redis.get("products");
  if (cached) {
    return Response.json(cached);
  }
  const products = await loadProducts();
  await redis.set("products", products, { ex: 30 });
  return Response.json(products);
};
 
export const config: Config = { path: "/api/products" };

So the first request populates the cache. Any subsequent request for the next 30 seconds is served from Redis instead of hitting the slow source.

To view what the function cached, check out the Data Browser tab of your database in the Upstash Console. All of the cached keys are displayed, with their corresponding value, and the time remaining for Redis to remove them:

A cached key in the Upstash Data Browser, with its JSON value and remaining TTL

The Usage tab shows hits and misses per second. This helps you track how often requests are finding the key in the cache:

Hits and misses per second on the Usage tab of an Upstash database

Netlify Functions (the non-edge ones) are based on Node.js, so you can use any ordinary Redis client library (such as ioredis) with the rediss:// connection string of your Redis database. You can find this on the TCP tab of the Connect box:

The TCP tab of the Connect box in the Upstash Console

Rate limit every API route with an Edge Function

Edge Functions run on a Deno-based runtime at the edge location closest to the visitor’s location, and before any requests are served from your serverless function. Hence, Edge Functions can be used as a front-line defense against abuse. With @upstash/ratelimit we store the counters in Redis, so they can be accessed from any edge location for the same visitor.

npm install @upstash/ratelimit @upstash/redis @netlify/edge-functions

Edge Functions support npm packages (currently in beta), so you import them by name.

This edge function allows five requests per IP address in any 10-second window on every /api/* path. A request under the limit continues to the function behind it through context.next():

// netlify/edge-functions/rate-limit.ts
import type { Config, Context } from "@netlify/edge-functions";
import { Redis } from "@upstash/redis";
import { Ratelimit } from "@upstash/ratelimit";
 
const ratelimit = new Ratelimit({
  redis: new Redis({
    url: Netlify.env.get("UPSTASH_REDIS_REST_URL")!,
    token: Netlify.env.get("UPSTASH_REDIS_REST_TOKEN")!,
  }),
  limiter: Ratelimit.slidingWindow(5, "10 s"),
  prefix: "netlify-demo:rl",
});
 
export default async (_req: Request, context: Context) => {
  const { success } = await ratelimit.limit(context.ip);
  if (!success) {
    return new Response("Too many requests", { status: 429 });
  }
  return context.next();
};
 
export const config: Config = { path: "/api/*" };

Edge functions access environment variables via Netlify.env (as opposed to process.env). A 429 response is returned on the 6th request from the same IP, within 10 seconds.

Netlify also provides rate limiting rules, configurable in a function’s config on all Netlify plans. These rules allow you to limit requests on a per-IP-address basis over a window of up to 180 seconds, and they may take up to 10 seconds to apply after a client exceeds the limit. @upstash/ratelimit covers the cases those rules don't: limits keyed by user ID or API key, windows of hours or days, and access to the remaining request count so the function can show it to the user.

Put read regions near your Edge Functions

Serverless functions run in one region, and moving them out of Ohio requires a Pro or Enterprise plan. Edge functions, on the other hand, run at the closest edge location to each visitor, so an edge function answering a visitor in Tokyo and reading from a database in Ohio is sending every Redis call across the Pacific and back.

An Upstash Global database can help fix the read side of things. It can have a primary region and one or more read regions, and the client will be routed to the closest region. A setup that would fit Netlify would look like this:

  • Primary region in AWS us-east-2 (Ohio), next to the serverless functions.
  • Read regions where your visitors are, for example eu-central-1 (Frankfurt) and ap-northeast-1 (Tokyo).

The Manage Regions setting on the database's Settings tab allows you to add or remove read regions for a database. This example database has a primary region in N. Virginia, and two read regions, Singapore and Frankfurt:

Manage Regions in the Upstash Console: a primary region and two read regions

Read regions help when an edge function reads from Redis, for example if you move the product cache lookup into an edge function. Those reads are served from the read region nearest the visitor. Writes, including every rate limiter call, still go to the primary region. Writes are also replicated and billed once per region: 100K writes cost $0.40 instead of $0.20 with one primary and one read region. A global database pays off when your edge functions mostly read.

What it costs

Upstash pricing for Redis is per command, with the Free plan offering 500K commands, 250 MB of data and 10 GB of bandwidth per month for one database. Any subsequent costs are pay as you go at $0.2 per 100K commands and the first 1 GB of storage per database is free.

Both examples above issue a known number of commands per request. The cache issues a single GET on hit, and a GET + SET on miss. The sliding window rate limiter issues 4 or 5 commands for an accepted request (5 when it is the first request from that IP in the window), and 3 or 0 for a blocked request depending on its local cache.

A site with 100K API requests a month, all passing the rate limiter and almost all hitting the cache, needs about this many commands:

rate limiter:  100,000 x 4–5 = 400,000–500,000
cache hits:    100,000 x 1   = 100,000
total                        ≈ 500,000–600,000 commands a month

That is around the free limit. Past it, pay as you go costs about $0.20 per extra 100K commands. A fixed window limiter uses 2–3 commands per allowed request instead of 4–5, which brings 100K requests down to roughly 300K–400K commands.