Redis & Caching - Replov Docs
Skip to main content

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.

TierResourcesPrice
Micro1 vCPU · 1 GBSame as a Micro service
Small2 vCPU · 2 GBSame as a Small service
Medium4 vCPU · 4 GBSame as a Medium service
Large8 vCPU · 8 GBSame 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.

Add Redis with your AI agent
Ask your agent to add Redis to an application. Replov will show the exact price and ask for approval before creating the paid resource. The application then receives 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

1

Create Database

Go to console.upstash.com and create a new Redis database

2

Copy Connection URL

Get the UPSTASH_REDIS_REST_URL and token

3

Add to Environment

Add credentials to Replov environment variables

bash
# Add to environment variables
UPSTASH_REDIS_REST_URL=https://your-db.upstash.io
UPSTASH_REDIS_REST_TOKEN=your-token-here

Basic Caching

Cache expensive database queries or API calls:

Node.js with ioredis

bash
npm install ioredis
cache.jsjavascript
const Redis = require('ioredis');
const redis = new Redis(process.env.REDIS_URL);
// Cache a value
async function cacheData(key, data, ttl = 3600) {
await redis.setex(key, ttl, JSON.stringify(data));
}
// Get cached value
async function getCachedData(key) {
const data = await redis.get(key);
return data ? JSON.parse(data) : null;
}
// Example: Cache database query
async function getUser(userId) {
const cacheKey = `user:${userId}`;
// Try cache first
let user = await getCachedData(cacheKey);
if (user) return user;
// Cache miss - fetch from database
user = await db.query('SELECT * FROM users WHERE id = $1', [userId]);
// Store in cache for 1 hour
await cacheData(cacheKey, user, 3600);
return user;
}
module.exports = { cacheData, getCachedData, getUser };

Python with redis-py

bash
pip install redis
cache.pypython
import redis
import json
import os
r = 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 None
def get_user(user_id):
"""Get user with caching"""
cache_key = f"user:{user_id}"
# Try cache first
user = get_cached_data(cache_key)
if user:
return user
# Cache miss - fetch from database
user = db.query("SELECT * FROM users WHERE id = %s", [user_id])
# Store in cache for 1 hour
cache_data(cache_key, user, 3600)
return user
Cache Invalidation
Always invalidate cache when data changes. Use cache keys like user:123 for easy deletion.

Session Storage

Store user sessions in Redis for scalability across multiple instances:

Express.js Sessions

bash
npm install express-session connect-redis ioredis
server.jsjavascript
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 only
httpOnly: true,
maxAge: 24 * 60 * 60 * 1000 // 24 hours
}
}));
// Use sessions
app.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

bash
pip install django-redis
settings.pypython
# Django settings
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": os.environ['REDIS_URL'],
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
}
}
}
# Use Redis for sessions
SESSION_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

rateLimiter.jsjavascript
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 counter
const current = await redis.incr(key);
// Set expiry on first request
if (current === 1) {
await redis.expire(key, window);
}
// Check if limit exceeded
if (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 middleware
function 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:

pubsub.jsjavascript
const Redis = require('ioredis');
// Create separate connections for pub and sub
const publisher = new Redis(process.env.REDIS_URL);
const subscriber = new Redis(process.env.REDIS_URL);
// Subscribe to channel
subscriber.subscribe('notifications', (err, count) => {
console.log(`Subscribed to ${count} channel(s)`);
});
// Handle messages
subscriber.on('message', (channel, message) => {
console.log(`Received from ${channel}:`, message);
// Broadcast to WebSocket clients
io.emit('notification', JSON.parse(message));
});
// Publish message
function 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:

bash
npm install bull
queue.jsjavascript
const Queue = require('bull');
// Create queue
const emailQueue = new Queue('email', process.env.REDIS_URL);
// Add job to queue
async function sendEmail(to, subject, body) {
await emailQueue.add({
to,
subject,
body
}, {
attempts: 3,
backoff: {
type: 'exponential',
delay: 2000
}
});
}
// Process jobs
emailQueue.process(async (job) => {
const { to, subject, body } = job.data;
console.log(`Sending email to ${to}`);
// Send email using your email service
await emailService.send({ to, subject, body });
return { sent: true };
});
// Handle job events
emailQueue.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.

Next Steps