1. Introduction & use cases
Redis is an in-memory data store that keeps data in RAM for sub-millisecond reads and writes. Beyond simple strings it offers data structures – hashes, lists, sets, sorted sets, streams – plus key expiry (TTL), pub/sub and atomic operations.
It is most often used as a cache in front of a slower database, for sessions, rate limiting, queues (BullMQ, Sidekiq) and real-time leaderboards. Data can be persisted to disk (RDB snapshots, AOF log), but treat Redis as a fast layer, not your only copy of important data. Valkey is a compatible open-source fork offered by several cloud providers.
Where it is used
- Caching API and database results
- User sessions and login tokens
- Rate limiting and counters
- Job queues, pub/sub and Socket.IO scaling
2. Prerequisites
| You need | Version / notes |
|---|---|
| Docker (recommended) | Docker Desktop or Docker Engine to run the database locally – see the Docker guide |
| Or native install | apt on Ubuntu, Homebrew on macOS; on Windows use Docker or WSL |
| redis-cli / Redis Insight | Command-line and GUI clients |
| Node.js LTS | For the sample app |
3. Local setup
1Run Redis
Docker works the same on every OS. On Ubuntu you can also install the package.
BASHdocker run -d --name redis -p 6379:6379 redis:7 # or Ubuntu sudo apt install -y redis-server sudo systemctl enable --now redis-server2Try the CLI
Strings with expiry, counters and hashes.
BASHredis-cli PING redis-cli SET greeting "hello" EX 30 redis-cli GET greeting redis-cli INCR page:views redis-cli HSET user:1 name Asha city Pune redis-cli HGETALL user:1
4. Create & run a project
1Create a Node.js project
Install the official client
redis(node-redis).BASHmkdir redis-cache && cd redis-cache npm init -y && npm pkg set type=module npm install redis express2Cache an API response (cache-aside)
Check Redis first; on a miss, fetch the data, store it with a TTL and return it.
server.jsimport express from 'express'; import { createClient } from 'redis'; const redis = createClient({ url: process.env.REDIS_URL ?? 'redis://localhost:6379' }); redis.on('error', (e) => console.error('Redis error', e)); await redis.connect(); const app = express(); app.get('/users', async (req, res) => { const key = 'cache:users'; const cached = await redis.get(key); if (cached) return res.set('X-Cache', 'HIT').json(JSON.parse(cached)); const data = await (await fetch('https://jsonplaceholder.typicode.com/users')).json(); await redis.set(key, JSON.stringify(data), { EX: 60 }); // 60 seconds res.set('X-Cache', 'MISS').json(data); }); app.listen(3000, () => console.log('http://localhost:3000/users'));3Add a simple rate limit
Allow 100 requests per IP per minute using
INCRandEXPIRE.JSapp.use(async (req, res, next) => { const key = `rate:${req.ip}`; const n = await redis.incr(key); if (n === 1) await redis.expire(key, 60); if (n > 100) return res.status(429).json({ error: 'Too many requests' }); next(); });4Run and compare
The second call is served from Redis.
BASHnode --env-file=.env server.js curl -sI localhost:3000/users | grep X-Cache # MISS curl -sI localhost:3000/users | grep X-Cache # HIT
✅ When it works you should see output like Figure 1.
5. Development configuration
Environment variables
Use redis:// for plain connections and rediss:// (two s) for TLS. Put the password in the URL or use ACL users.
REDIS_URL=redis://localhost:6379
# production with TLS and ACL user:
# REDIS_URL=rediss://app:STRONG_PASSWORD@cache.example.com:6379Key dependencies
| Package / tool | Used for |
|---|---|
redis (node-redis) / ioredis | Node.js clients |
redis-py | Python client |
connect-redis | Express sessions in Redis |
bullmq | Job queues on Redis |
Redis Insight | GUI to browse keys and memory |
Folder structure
redis-cache/
├── src/
│ ├── redis.js # one shared client
│ ├── cache.js # get/set helpers with TTL
│ └── server.js
├── docker-compose.yml
└── .envEssential commands
| Command | What it does |
|---|---|
redis-cli PING | Check the server |
SET key value EX 60 | Store with a 60 s expiry |
TTL key | Seconds left before expiry |
INFO memory | Memory usage |
SCAN 0 MATCH cache:* COUNT 100 | Find keys safely (never KEYS * in production) |
redis-cli --latency | Measure latency |
6. Production deployment
For production, a managed service (Amazon ElastiCache, Azure Cache, Redis Cloud, Upstash) removes most of the operations work. If you self-host, Redis must never be reachable from the internet without authentication.
Server & hosting requirements
| Requirement | Recommendation |
|---|---|
| Memory | RAM larger than your data set + 30–50 % headroom |
| Network | Private network only; bind to 127.0.0.1 or a private IP |
| Security | Password/ACL user, TLS for traffic between servers |
| Persistence | AOF or RDB if data must survive restarts |
| Eviction | maxmemory + a policy such as allkeys-lru for caches |
Deployment steps
1Prepare an Ubuntu server
Create a VPS (AWS EC2, DigitalOcean, Hostinger VPS, Linode …) with Ubuntu 24.04 LTS, at least 1 vCPU and 1–2 GB RAM. Log in with SSH, update the system and create a non-root user for the app.
BASHssh root@YOUR_SERVER_IP apt update && apt upgrade -y adduser deploy usermod -aG sudo deploy # copy your SSH key to the new user, then log in as deploy rsync --archive --chown=deploy:deploy ~/.ssh /home/deploy exit ssh deploy@YOUR_SERVER_IP2Install Redis
Ubuntu’s package runs Redis as a systemd service.
BASHsudo apt install -y redis-server redis-server --version3Secure and tune the config
Bind locally (or to a private IP), require a password, limit memory and choose an eviction policy.
/etc/redis/redis.confbind 127.0.0.1 -::1 protected-mode yes port 6379 requirepass CHANGE_TO_A_LONG_RANDOM_PASSWORD maxmemory 512mb maxmemory-policy allkeys-lru appendonly yes # persistence (AOF) supervised systemd4Restart and test
Use
-a(orAUTH) with the password.BASHsudo systemctl restart redis-server redis-cli -a 'YOUR_PASSWORD' PING5Point the app at it
Set
REDIS_URLin the app’s environment; restart the app.OUTPUTREDIS_URL=redis://:YOUR_PASSWORD@127.0.0.1:63796Managed option (AWS ElastiCache)
Create a Valkey/Redis OSS cache in the same VPC as your app, enable encryption in transit and an auth token/ACL, and allow port 6379 only from the app’s security group. Connect with
rediss://.
🗺 The whole path from your code to the live site is drawn in the deployment diagram.
7. Images & screenshots
Illustrations drawn for this guide from the commands above. Product dashboards change often, so for screens such as cloud consoles follow the step text and the official documentation.
8. Common errors & solutions
Error: connect ECONNREFUSED 127.0.0.1:6379
Redis is not running or listens on another address. Start it and check bind/port.
NOAUTH Authentication required
The server has requirepass/ACL enabled. Put the password in the URL: redis://:password@host:6379.
OOM command not allowed when used memory > 'maxmemory'
Memory is full and the policy is noeviction. Use allkeys-lru for caches or add memory.
Stale data after updates
Delete or update the cache key whenever the source data changes, and keep TTLs short for data that changes often.
Redis freezes briefly
KEYS * or huge values block the single-threaded server. Use SCAN and keep values small.
Best practices
- Always set a TTL on cache keys.
- Use clear key names:
app:entity:id:field. - Never use Redis as the only copy of important data.
- Never expose port 6379 to the internet.
- Watch memory, evictions and hit rate (
INFO stats).