Redis Hosting
Guide to setting up Redis for caching and session storage in production.
Redis Hosting Guide
This guide covers setting up Redis for caching and session storage with various hosting providers.
Overview
Raypx uses Redis for:
- Caching: API response caching, query result caching
- Session storage: Optional session storage (Better Auth uses database by default)
- Rate limiting: API rate limiting (if implemented)
The project includes a Redis client package (@raypx/redis) that works with any Redis-compatible service.
Recommended Providers
1. Upstash (Recommended for Serverless)
Upstash is a serverless Redis platform perfect for serverless applications like Vercel deployments.
Setup Steps
-
Create an Upstash account
- Visit upstash.com
- Sign up with GitHub or email
-
Create a Redis database
- Click "Create Database"
- Choose a database name
- Select region (choose closest to your deployment region)
- Select type: "Regional" (recommended) or "Global"
- Click "Create"
-
Get connection details
- After creation, click on your database
- Copy the following:
UPSTASH_REDIS_REST_URLUPSTASH_REDIS_REST_TOKEN
-
Configure environment variables
UPSTASH_REDIS_REST_URL=https://your-db.upstash.io UPSTASH_REDIS_REST_TOKEN=your-tokenOr use the REST API format:
REDIS_URL=https://your-db.upstash.io REDIS_TOKEN=your-token -
Verify connection
# Test Redis connection pnpm --filter @raypx/redis run test
Upstash Features
- ✅ Serverless (pay per request)
- ✅ Global replication
- ✅ Automatic backups
- ✅ Free tier available (10K commands/day)
- ✅ REST API (no persistent connections needed)
- ✅ Built-in rate limiting
2. Redis Cloud
Redis Cloud (formerly Redis Labs) offers managed Redis with high availability.
Setup Steps
-
Create a Redis Cloud account
- Visit redis.com/cloud
- Sign up for free account
-
Create a subscription
- Choose a plan (free tier available)
- Select cloud provider and region
-
Create a database
- Click "New Database"
- Configure:
- Database name
- Memory limit
- Replication (optional)
- Click "Activate"
-
Get connection string
- Copy the connection string from database details
- Format:
redis://default:password@host:port
-
Configure environment variable
REDIS_URL=redis://default:password@host:port
Redis Cloud Features
- ✅ High availability
- ✅ Automatic failover
- ✅ Backup and restore
- ✅ Free tier available (30MB)
- ✅ Multiple cloud providers
3. Railway
Railway offers simple Redis hosting with easy deployment integration.
Setup Steps
-
Create a Railway account
- Visit railway.app
- Sign up with GitHub
-
Create Redis service
- Click "New Project"
- Add "Redis" service
- Railway will automatically create the Redis instance
-
Get connection string
- Click on the Redis service
- Go to "Variables" tab
- Copy
REDIS_URL
-
Configure environment variable
REDIS_URL=redis://default:password@host:port
4. Vercel KV (Redis)
Vercel KV integrates seamlessly with Vercel deployments using Upstash.
Setup Steps
-
Add KV to Vercel project
- In Vercel dashboard, go to your project
- Navigate to "Storage" tab
- Click "Create Database" → "KV"
-
Get connection details
- Vercel automatically provides environment variables:
KV_REST_API_URLKV_REST_API_TOKENKV_URL(for Redis client)
- Vercel automatically provides environment variables:
-
Configure environment variables
REDIS_URL=$KV_URL # or UPSTASH_REDIS_REST_URL=$KV_REST_API_URL UPSTASH_REDIS_REST_TOKEN=$KV_REST_API_TOKEN
5. Self-Hosted Redis
For self-hosted Redis (Docker, VPS, etc.):
Setup Steps
-
Install Redis
# Using Docker docker run --name redis \ -p 6379:6379 \ -d redis:7-alpine -
Configure connection string
REDIS_URL=redis://localhost:6379With password:
REDIS_URL=redis://:password@localhost:6379 -
Verify connection
redis-cli ping # Should return: PONG
Environment Configuration
Development
For local development, use .env file:
# Option 1: Direct Redis connection
REDIS_URL=redis://localhost:6379
# Option 2: Upstash REST API
UPSTASH_REDIS_REST_URL=https://your-db.upstash.io
UPSTASH_REDIS_REST_TOKEN=your-tokenProduction
For production deployments:
Vercel
- Add
REDIS_URLor Upstash variables in Project Settings → Environment Variables - Use production Redis connection details
Netlify
- Add
REDIS_URLin Site Settings → Environment Variables - Use production Redis connection details
Other Platforms
- Set
REDIS_URLas an environment variable in your hosting platform - Ensure Redis is accessible from your application servers
Connection Types
Standard Redis Connection
For traditional Redis clients:
REDIS_URL=redis://:password@host:portUpstash REST API
For serverless environments (recommended):
UPSTASH_REDIS_REST_URL=https://your-db.upstash.io
UPSTASH_REDIS_REST_TOKEN=your-tokenBenefits:
- No persistent connections
- Works with serverless functions
- Automatic connection pooling
- Better for edge deployments
Using Redis in Code
Cache Operations
import { cache } from "@raypx/redis";
// Set cache
await cache.set("key", "value", { ttl: 3600 }); // 1 hour
// Get cache
const value = await cache.get("key");
// Delete cache
await cache.delete("key");
// Check if exists
const exists = await cache.exists("key");Session Storage
If using Redis for sessions (Better Auth uses database by default):
import { auth } from "@raypx/auth/server";
// Configure Redis session storage in auth config
// See packages/auth/src/server/auth.tsMonitoring
Redis Metrics
Monitor these key metrics:
- Memory usage: Redis memory consumption
- Commands per second: Request rate
- Hit rate: Cache hit/miss ratio
- Connection count: Active connections
- Evictions: Keys evicted due to memory limits
Tools
- Redis CLI:
redis-clifor command-line access - Redis Insight: GUI tool for Redis management
- Provider dashboards: Use hosting provider's monitoring tools
- Application logs: Check application logs for Redis errors
Best Practices
Caching Strategy
-
Set appropriate TTLs
- Short TTL for frequently changing data
- Longer TTL for stable data
- Use cache invalidation for critical updates
-
Key naming conventions
// Good: Namespaced keys cache.set("user:123:profile", data); cache.set("api:users:list", data); // Bad: Generic keys cache.set("data", data); -
Handle cache misses
let data = await cache.get("key"); if (!data) { data = await fetchFromDatabase(); await cache.set("key", data, { ttl: 3600 }); } return data;
Memory Management
- Set memory limits: Configure max memory based on your plan
- Use eviction policies:
allkeys-lrufor cache,noevictionfor critical data - Monitor memory usage: Set up alerts for high memory usage
- Clean up expired keys: Redis automatically removes expired keys
Security
- Use passwords: Always set Redis password in production
- Enable TLS: Use
rediss://for encrypted connections - Restrict access: Use firewall rules to limit access
- Rotate credentials: Regularly rotate Redis passwords
- Use environment variables: Never commit credentials to version control
Troubleshooting
Connection Issues
Error: Connection refused
- Check if Redis is running
- Verify connection string format
- Check firewall/network settings
- Verify Redis is accessible from your application
Error: Authentication failed
- Verify password is correct
- Check if password is URL-encoded in connection string
- Verify Redis ACL configuration
Error: Timeout
- Check network connectivity
- Verify Redis server is responding
- Check for connection pool exhaustion
Performance Issues
Slow operations
- Check Redis server resources (CPU, memory)
- Monitor command execution times
- Consider using pipelining for bulk operations
- Review key sizes (large keys can slow down operations)
Memory issues
- Monitor memory usage
- Review eviction policy
- Consider key expiration
- Upgrade plan if needed
Cache Issues
Cache not working
- Verify Redis connection is established
- Check TTL settings
- Review cache key naming
- Check for cache invalidation logic
Stale data
- Review TTL settings
- Implement cache invalidation
- Use versioned cache keys
- Consider cache warming strategies
Migration Checklist
Before deploying to production:
- Redis provider selected and configured
- Connection string tested
- Environment variables configured securely
- TLS enabled (if supported)
- Password set and secured
- Memory limits configured
- Eviction policy set
- Monitoring set up
- Backup strategy in place (if needed)
- Cache strategy defined
- Error handling implemented
- Connection pooling configured (if needed)
Next Steps
- Review Database Hosting Guide for PostgreSQL setup
- Check Development Workflow for Redis usage in code
- Review
@raypx/redispackage for API documentation
Last updated on
