Databases & Caching

Redis Setup & Deployment Guide

In-memory key-value store for caching, sessions, queues and rate limits – run it locally, use it from Node.js and secure it in production.

Updated Official documentation ↗

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 needVersion / notes
Docker (recommended)Docker Desktop or Docker Engine to run the database locally – see the Docker guide
Or native installapt on Ubuntu, Homebrew on macOS; on Windows use Docker or WSL
redis-cli / Redis InsightCommand-line and GUI clients
Node.js LTSFor the sample app

3. Local setup

  1. 1Run Redis

    Docker works the same on every OS. On Ubuntu you can also install the package.

    BASH
    docker run -d --name redis -p 6379:6379 redis:7
    
    # or Ubuntu
    sudo apt install -y redis-server
    sudo systemctl enable --now redis-server
  2. 2Try the CLI

    Strings with expiry, counters and hashes.

    BASH
    redis-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

  1. 1Create a Node.js project

    Install the official client redis (node-redis).

    BASH
    mkdir redis-cache && cd redis-cache
    npm init -y && npm pkg set type=module
    npm install redis express
  2. 2Cache an API response (cache-aside)

    Check Redis first; on a miss, fetch the data, store it with a TTL and return it.

    server.js
    import 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'));
  3. 3Add a simple rate limit

    Allow 100 requests per IP per minute using INCR and EXPIRE.

    JS
    app.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();
    });
  4. 4Run and compare

    The second call is served from Redis.

    BASH
    node --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.

.env
REDIS_URL=redis://localhost:6379
# production with TLS and ACL user:
# REDIS_URL=rediss://app:STRONG_PASSWORD@cache.example.com:6379

Key dependencies

Package / toolUsed for
redis (node-redis) / ioredisNode.js clients
redis-pyPython client
connect-redisExpress sessions in Redis
bullmqJob queues on Redis
Redis InsightGUI to browse keys and memory

Folder structure

project structure
redis-cache/
├── src/
│   ├── redis.js       # one shared client
│   ├── cache.js       # get/set helpers with TTL
│   └── server.js
├── docker-compose.yml
└── .env

Essential commands

CommandWhat it does
redis-cli PINGCheck the server
SET key value EX 60Store with a 60 s expiry
TTL keySeconds left before expiry
INFO memoryMemory usage
SCAN 0 MATCH cache:* COUNT 100Find keys safely (never KEYS * in production)
redis-cli --latencyMeasure 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

RequirementRecommendation
MemoryRAM larger than your data set + 30–50 % headroom
NetworkPrivate network only; bind to 127.0.0.1 or a private IP
SecurityPassword/ACL user, TLS for traffic between servers
PersistenceAOF or RDB if data must survive restarts
Evictionmaxmemory + a policy such as allkeys-lru for caches

Deployment steps

  1. 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.

    BASH
    ssh 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_IP
  2. 2Install Redis

    Ubuntu’s package runs Redis as a systemd service.

    BASH
    sudo apt install -y redis-server
    redis-server --version
  3. 3Secure and tune the config

    Bind locally (or to a private IP), require a password, limit memory and choose an eviction policy.

    /etc/redis/redis.conf
    bind 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 systemd
  4. 4Restart and test

    Use -a (or AUTH) with the password.

    BASH
    sudo systemctl restart redis-server
    redis-cli -a 'YOUR_PASSWORD' PING
  5. 5Point the app at it

    Set REDIS_URL in the app’s environment; restart the app.

    OUTPUT
    REDIS_URL=redis://:YOUR_PASSWORD@127.0.0.1:6379
  6. 6Managed 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.

terminal$ redis-cli PINGPONG$ node --env-file=.env server.jshttp://localhost:3000/users$ curl -sI localhost:3000/users | grep X-CacheX-Cache: MISS$ curl -sI localhost:3000/users | grep X-CacheX-Cache: HIT
Figure 1: terminal output of the sample Redis project (section 4).
1Cache-aside code2Redis on privatenetwork3Password / ACL +TLS4maxmemory +eviction5App via REDIS_URL
Figure 2: production deployment flow (section 6).
redis-cache/├── src/│ ├── redis.js # one shared client│ ├── cache.js # get/set helpers with TTL│ └── server.js├── docker-compose.yml└── .env
Figure 3: project folder structure (section 5).

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).