Decorative background gradient
Back to Blog
Redis NextjsUpstash CachingRate Limiting

Redis Caching in Next.js with Upstash — Complete Guide

Add Redis caching to a Next.js app with Upstash's serverless REST API — cache-aside patterns, rate limiting, and cache invalidation on writes.

Redis Caching in Next.js with Upstash — Complete Guide

Redis is still the standard tool for caching expensive queries and rate-limiting APIs, but a traditional Redis client's persistent connections don't fit serverless Next.js deployments well. Upstash solves this with a REST-based Redis that works cleanly in serverless functions and Edge Middleware.

Step 1: Create an Upstash Redis Database and Install the SDK

bash
ts

Every call is a plain HTTPS request under the hood, so this works identically in a Node serverless function, the Edge Runtime, or a long-running server.

Step 2: Implement Cache-Aside Reads

ts

The ex: 300 option sets a 5-minute TTL — this cache will self-expire even if you never explicitly invalidate it, preventing permanently stale data from an edge case you didn't anticipate.

Step 3: Invalidate the Cache on Writes

ts

Redis has no awareness of your database changing — deleting the affected key on every write that could change the cached result is what keeps the cache correct. Forgetting this step, not a flaw in Redis, is the usual source of "stale cache" bugs.

Step 4: Cache Per-User or Per-Parameter Data with Composite Keys

ts

Composite keys (dashboard:${userId}) keep cached entries isolated per user, so invalidating one user's cache never affects another's.

Step 5: Rate Limit an API Route with the Same Redis Instance

bash
ts
ts

The sliding window algorithm here allows 10 requests per 10 seconds per IP, backed by the same Redis instance already used for caching — no separate rate-limiting infrastructure needed.

Step 6: Use Redis in Edge Middleware

ts

Because Upstash's client is REST-based rather than a TCP connection, it runs directly in Edge Middleware — a traditional Redis client cannot.

Key Takeaways

Upstash's REST-based Redis fits serverless and Edge Runtime Next.js apps in a way a traditional TCP Redis client can't, the cache-aside pattern with an explicit TTL and write-time invalidation is what keeps cached data both fast and correct, and the same Redis instance can double as the backing store for API rate limiting via @upstash/ratelimit.

Frequently Asked Questions

Why use Upstash instead of a traditional Redis server for Next.js?

Traditional Redis clients hold a persistent TCP connection, which doesn't fit serverless functions that spin up and down per request — you'd exhaust connection limits quickly. Upstash exposes Redis over a stateless HTTP/REST API instead, so each request is a normal fetch call with no connection pooling to manage.

How do I keep cached data from going stale after a database write?

Explicitly delete or overwrite the relevant cache key immediately after the write that changes the underlying data — Redis has no way to know your database changed unless you tell it. This is usually the actual cause of "stale cache" bugs, not a flaw in the caching library itself.

What TTL should I set on cached keys?

It depends on how tolerant the data is to staleness — a public content listing might tolerate a 5-minute TTL, while a user's own draft data should either have a very short TTL or be invalidated explicitly on every write. Never omit a TTL entirely; an unbounded cache key becomes permanently stale the moment invalidation logic misses an edge case.

Can I use Upstash Redis for rate limiting an API route?

Yes — the @upstash/ratelimit package implements sliding window, fixed window, and token bucket algorithms backed by the same Upstash Redis instance, letting you rate-limit a Route Handler in a few lines without running separate infrastructure.

Working on something similar? Take a look at my services and case studies, or book a free call to talk about your idea.

Related Articles

Caching Strategies and Cache Invalidation — The Complete Guide
CachingSystem DesignPerformance

Caching Strategies and Cache Invalidation — The Complete Guide

A practical guide to caching strategies (cache-aside, write-through, write-behind) and the cache invalidation techniques that keep them from serving stale data.

September 8, 2026Read more →
Database Indexing and Read Replicas — A Practical Guide
DatabasePostgreSQLSystem Design

Database Indexing and Read Replicas — A Practical Guide

How to choose the right database indexes, avoid the ones that quietly hurt write performance, and scale reads with replicas without introducing replication lag bugs.

September 8, 2026Read more →
Load Balancing and Stateless Service Design — A Practical Guide
System DesignLoad BalancingScalability

Load Balancing and Stateless Service Design — A Practical Guide

How load balancers distribute traffic, why stateless services are what actually makes horizontal scaling work, and how to fix the sticky-session traps that quietly reintroduce state.

September 8, 2026Read more →
Session Stores and Database Connection Pooling Explained
BackendRedisDatabase

Session Stores and Database Connection Pooling Explained

Why in-memory sessions break horizontally scaled apps, how to move session state to Redis correctly, and how connection pooling keeps your database from falling over under concurrent load.

September 8, 2026Read more →
Vertical vs Horizontal Scaling: How to Choose and Implement Each
System DesignScalabilityArchitecture

Vertical vs Horizontal Scaling: How to Choose and Implement Each

A practical comparison of vertical and horizontal scaling — what each actually fixes, where each breaks down, and the architecture changes horizontal scaling requires that most guides skip.

September 8, 2026Read more →
AI Agent Guardrails and Safety — Preventing Prompt Injection and Runaway Actions
Ai Agent SafetyPrompt Injection DefenseAgent Guardrails

AI Agent Guardrails and Safety — Preventing Prompt Injection and Runaway Actions

Build practical guardrails for AI agents — prompt injection defenses, destructive-action confirmation, iteration caps, and permission scoping.

September 7, 2026Read more →

Trending Topics