Redis & Caching
High-performance caching and session storage with Redis
Add Redis to your application for caching, session storage, rate limiting, and real-time features. Use Replov Redis, or connect Upstash Redis and other providers.
Caching
Speed up responses
Sessions
Store user sessions
Rate Limiting
Control API usage
Queues
Background jobs
Replov Redis
Replov runs a persistent Redis datastore next to your apps, reachable only on your project's private network. Redis uses the same tiers and prices as every other Replov service, and starts at Micro — there is no Nano Redis.
| Tier | Resources | Price |
|---|---|---|
| Micro | 1 vCPU · 1 GB | Same as a Micro service |
| Small | 2 vCPU · 2 GB | Same as a Small service |
| Medium | 4 vCPU · 4 GB | Same as a Medium service |
| Large | 8 vCPU · 8 GB | Same as a Large service |
Current prices are on the pricing page. Like other paid tiers, a new Redis starts with a 3-day trial and is then billed from your Replov wallet until you delete it.
REDIS_URL on its next deploy — managed by Replov, and never shown to the agent.Upstash Redis (external)
Upstash offers serverless Redis with per-request pricing and generous free tier:
Setup
Create Database
Go to console.upstash.com and create a new Redis database
Copy Connection URL
Get the UPSTASH_REDIS_REST_URL and token
Add to Environment
Add credentials to Replov environment variables
# Add to environment variablesUPSTASH_REDIS_REST_URL=https://your-db.upstash.ioUPSTASH_REDIS_REST_TOKEN=your-token-here
Basic Caching
Cache expensive database queries or API calls:
Node.js with ioredis
npm install ioredis
const Redis = require('ioredis');const redis = new Redis(process.env.REDIS_URL);// Cache a valueasync function cacheData(key, data, ttl = 3600) {await redis.setex(key, ttl, JSON.stringify(data));}// Get cached valueasync function getCachedData(key) {const data = await redis.get(key);return data ? JSON.parse(data) : null;}// Example: Cache database queryasync function getUser(userId) {const cacheKey = `user:${userId}`;// Try cache firstlet user = await getCachedData(cacheKey);if (user) return user;// Cache miss - fetch from databaseuser = await db.query('SELECT * FROM users WHERE id = $1', [userId]);// Store in cache for 1 hourawait cacheData(cacheKey, user, 3600);return user;}module.exports = { cacheData, getCachedData, getUser };
Python with redis-py
pip install redis
import redisimport jsonimport osr = redis.from_url(os.environ['REDIS_URL'])def cache_data(key, data, ttl=3600):"""Cache data with TTL in seconds"""r.setex(key, ttl, json.dumps(data))def get_cached_data(key):"""Get cached data"""data = r.get(key)return json.loads(data) if data else Nonedef get_user(user_id):"""Get user with caching"""cache_key = f"user:{user_id}"# Try cache firstuser = get_cached_data(cache_key)if user:return user# Cache miss - fetch from databaseuser = db.query("SELECT * FROM users WHERE id = %s", [user_id])# Store in cache for 1 hourcache_data(cache_key, user, 3600)return user
Session Storage
Store user sessions in Redis for scalability across multiple instances:
Express.js Sessions
npm install express-session connect-redis ioredis
const express = require('express');const session = require('express-session');const RedisStore = require('connect-redis').default;const Redis = require('ioredis');const app = express();const redis = new Redis(process.env.REDIS_URL);app.use(session({store: new RedisStore({ client: redis }),secret: process.env.SESSION_SECRET,resave: false,saveUninitialized: false,cookie: {secure: true, // HTTPS onlyhttpOnly: true,maxAge: 24 * 60 * 60 * 1000 // 24 hours}}));// Use sessionsapp.post('/login', (req, res) => {req.session.userId = user.id;res.json({ success: true });});app.get('/profile', (req, res) => {if (!req.session.userId) {return res.status(401).json({ error: 'Not authenticated' });}res.json({ userId: req.session.userId });});
Django Sessions
pip install django-redis
# Django settingsCACHES = {"default": {"BACKEND": "django_redis.cache.RedisCache","LOCATION": os.environ['REDIS_URL'],"OPTIONS": {"CLIENT_CLASS": "django_redis.client.DefaultClient",}}}# Use Redis for sessionsSESSION_ENGINE = "django.contrib.sessions.backends.cache"SESSION_CACHE_ALIAS = "default"
Rate Limiting
Protect your API from abuse with Redis-based rate limiting:
Simple Rate Limiter
const Redis = require('ioredis');const redis = new Redis(process.env.REDIS_URL);async function checkRateLimit(userId, limit = 100, window = 3600) {const key = `ratelimit:${userId}`;// Increment counterconst current = await redis.incr(key);// Set expiry on first requestif (current === 1) {await redis.expire(key, window);}// Check if limit exceededif (current > limit) {const ttl = await redis.ttl(key);throw new Error(`Rate limit exceeded. Try again in ${ttl} seconds`);}return {allowed: true,remaining: limit - current,resetIn: await redis.ttl(key)};}// Express middlewarefunction rateLimitMiddleware(req, res, next) {const userId = req.user?.id || req.ip;checkRateLimit(userId, 100, 3600).then(result => {res.set({'X-RateLimit-Limit': 100,'X-RateLimit-Remaining': result.remaining,'X-RateLimit-Reset': result.resetIn});next();}).catch(err => {res.status(429).json({ error: err.message });});}module.exports = { checkRateLimit, rateLimitMiddleware };
Pub/Sub for Real-Time Features
Use Redis pub/sub for real-time notifications and chat:
const Redis = require('ioredis');// Create separate connections for pub and subconst publisher = new Redis(process.env.REDIS_URL);const subscriber = new Redis(process.env.REDIS_URL);// Subscribe to channelsubscriber.subscribe('notifications', (err, count) => {console.log(`Subscribed to ${count} channel(s)`);});// Handle messagessubscriber.on('message', (channel, message) => {console.log(`Received from ${channel}:`, message);// Broadcast to WebSocket clientsio.emit('notification', JSON.parse(message));});// Publish messagefunction sendNotification(userId, message) {const data = {userId,message,timestamp: Date.now()};publisher.publish('notifications', JSON.stringify(data));}module.exports = { sendNotification };
Job Queues with Bull
Process background jobs with Bull queue:
npm install bull
const Queue = require('bull');// Create queueconst emailQueue = new Queue('email', process.env.REDIS_URL);// Add job to queueasync function sendEmail(to, subject, body) {await emailQueue.add({to,subject,body}, {attempts: 3,backoff: {type: 'exponential',delay: 2000}});}// Process jobsemailQueue.process(async (job) => {const { to, subject, body } = job.data;console.log(`Sending email to ${to}`);// Send email using your email serviceawait emailService.send({ to, subject, body });return { sent: true };});// Handle job eventsemailQueue.on('completed', (job, result) => {console.log(`Job ${job.id} completed:`, result);});emailQueue.on('failed', (job, err) => {console.error(`Job ${job.id} failed:`, err);});module.exports = { sendEmail };
Caching Strategies
1. Cache-Aside (Lazy Loading)
Check cache first, load from database on miss, then cache the result.
Best for: Read-heavy workloads, infrequently changing data
2. Write-Through
Write to cache and database simultaneously.
Best for: Data consistency, write-heavy workloads
3. Write-Behind
Write to cache immediately, sync to database asynchronously.
Best for: High write throughput, eventual consistency acceptable
4. Time-Based Expiration
Set TTL on cached items to auto-expire stale data.
Best for: Data that changes predictably, reducing cache size
Best Practices
Use Namespaced Keys
Prefix keys with namespace: user:123, product:456, session:abc
Set Appropriate TTLs
Always set expiration times to prevent memory bloat. Use shorter TTLs for frequently changing data.
Handle Cache Failures Gracefully
Your app should work even if Redis is down. Catch errors and fall back to database.
Monitor Memory Usage
Track Redis memory usage and set maxmemory policies (allkeys-lru recommended).
Troubleshooting
Connection Timeout
Solution: Check Redis URL, ensure Redis is running, verify network connectivity.
Memory Limit Exceeded
Solution: Set maxmemory-policy to allkeys-lru, reduce TTLs, or upgrade Redis plan.
Slow Performance
Check: Use pipelining for multiple commands, avoid KEYS command in production, use SCAN instead.