Skip to main content
Back to Category

Redis and Memcached Setup: Cache Layer Guide

Redis and Memcached installation on Ubuntu/Debian, basic commands, persistence settings, TTL configuration, Redis vs Memcached comparison, and application integration.

Read time: 15 min Database
redismemcachedcacheinstallationubuntudebianlinuxperformance

Table of Contents

Redis and Memcached Setup: Cache Layer Guide

A cache layer is a critical infrastructure component that dramatically improves web application performance. By storing database queries, API responses, and computation results in memory, it enables millisecond responses to repeated requests. This guide covers the installation, configuration, and application integration of Redis and Memcached — the two most widely used cache systems.

Redis vs Memcached

Both systems offer high-performance in-memory data storage, but they target different use cases:

FeatureRedisMemcached
Data structuresString, Hash, List, Set, ZSetString only
PersistenceRDB + AOFNone
ReplicationMaster-Replica + ClusterNone
Pub/SubYesNo
Lua scriptingYesNo
Multi-threadingPartial (I/O)Full
Memory efficiencyMediumHigh

Redis is recommended for new projects. With rich data structures, persistence, and replication support, it covers far more use cases. Memcached is preferred only when you need simple string caching and maximum multi-threaded performance.

Redis Installation (Ubuntu/Debian)

Install from Package Repository

hljs bash
# Update package list
apt update

# Install Redis
apt install -y redis-server

# Check service status
systemctl status redis-server

# Enable auto-start
systemctl enable redis-server

Install from Official Redis Repository (Latest Version)

hljs bash
# Install required tools
apt install -y curl gpg

# Add Redis GPG key
curl -fsSL https://packages.redis.io/gpg | gpg --dearmor -o /usr/share/keyrings/redis-archive-keyring.gpg

# Add repository
echo 'deb [signed-by=/usr/share/keyrings/redis-archive-keyring.gpg] https://packages.redis.io/deb '$(lsb_release -cs)' main' | tee /etc/apt/sources.list.d/redis.list

# Update and install
apt update
apt install -y redis

Verify Redis Version

hljs bash
redis-server --version
# Output: Redis server v=7.x.x ...

redis-cli --version
# Output: redis-cli 7.x.x

Redis Installation (CentOS/AlmaLinux/Rocky Linux)

hljs bash
# Enable EPEL repository
dnf install -y epel-release

# Install Redis
dnf install -y redis

# Start and enable service
systemctl start redis
systemctl enable redis

# Check status
systemctl status redis

Redis Configuration

Basic Configuration File

hljs bash
# Edit configuration file
nano /etc/redis/redis.conf
hljs ini
# Listening address (localhost only)
bind 127.0.0.1

# Port (default 6379)
port 6379

# Password protection
requirepass StrongRedisPassword123!

# Maximum memory usage
maxmemory 512mb

# Eviction policy when memory is full
maxmemory-policy allkeys-lru

# Run as daemon
daemonize yes

# Log file
logfile /var/log/redis/redis-server.log

# Number of databases
databases 16

Apply Configuration

hljs bash
systemctl restart redis-server

# Verify configuration
redis-cli -a StrongRedisPassword123! ping
# Output: PONG

Redis Basic Commands

Connection and Basic Operations

hljs bash
# Connect to Redis CLI
redis-cli

# Connect with password
redis-cli -a StrongRedisPassword123!

# Connect to remote server
redis-cli -h 192.168.1.100 -p 6379 -a password
hljs redis
# Connection test
PING
# Response: PONG

# Set a string value
SET user:1:name 'John Doe'

# Read value
GET user:1:name

# Set value with TTL (in seconds)
SETEX session:abc123 3600 'user_data'

# Check remaining time
TTL session:abc123

# Delete value
DEL user:1:name

# Check if key exists
EXISTS user:1:name

# List all keys (use carefully in production)
KEYS *

# Search with pattern
KEYS user:*

Hash Commands

hljs redis
# Set hash
HSET user:1 name 'John' email 'john@example.com' age 30

# Read hash field
HGET user:1 name

# Read all hash fields
HGETALL user:1

# Delete hash field
HDEL user:1 age

# Check if hash field exists
HEXISTS user:1 email

List Commands

hljs redis
# Add element to list (left)
LPUSH tasks 'task1' 'task2'

# Add element to list (right)
RPUSH tasks 'task3'

# Get element from list (left)
LPOP tasks

# List length
LLEN tasks

# List range
LRANGE tasks 0 -1

Set and Sorted Set Commands

hljs redis
# Add element to set
SADD tags 'redis' 'cache' 'nosql'

# List set members
SMEMBERS tags

# Add to sorted set with score
ZADD leaderboard 1500 'player1' 2300 'player2' 800 'player3'

# List sorted (ascending)
ZRANGE leaderboard 0 -1 WITHSCORES

# List sorted (descending)
ZREVRANGE leaderboard 0 2 WITHSCORES

Redis Persistence Settings

RDB (Redis Database) Snapshot

RDB writes a snapshot of the entire dataset to disk at specified intervals:

hljs ini
# /etc/redis/redis.conf

# Save if 1 change in 900 seconds
save 900 1

# Save if 10 changes in 300 seconds
save 300 10

# Save if 10000 changes in 60 seconds
save 60 10000

# RDB filename
dbfilename dump.rdb

# RDB directory
dir /var/lib/redis

AOF (Append Only File)

AOF appends every write operation to a log file, providing more reliable persistence:

hljs ini
# Enable AOF
appendonlyfile yes

# AOF filename
appendfilename 'appendonly.aof'

# Sync policy
# always: On every write (safest, slowest)
# everysec: Every second (recommended)
# no: Leave to OS (fastest, least safe)
appendsync everysec

# AOF rewrite threshold
auto-aof-rewrite-percentage 100
auto-aof-rewrite-min-size 64mb

Using both RDB and AOF in production is recommended. RDB provides fast restarts, while AOF minimizes data loss.

Memcached Installation

Installation on Ubuntu/Debian

hljs bash
# Update package list
apt update

# Install Memcached
apt install -y memcached libmemcached-tools

# Check service status
systemctl status memcached

# Enable auto-start
systemctl enable memcached

Installation on CentOS/AlmaLinux

hljs bash
# Install Memcached
dnf install -y memcached

# Start and enable service
systemctl start memcached
systemctl enable memcached

Memcached Configuration

hljs bash
# Edit configuration file
nano /etc/memcached.conf
hljs ini
# Memory limit (MB)
-m 256

# Listening address
-l 127.0.0.1

# Port
-p 11211

# Maximum connections
-c 1024

# Thread count (based on CPU cores)
-t 4

# Maximum object size (bytes)
-I 1m
hljs bash
# Restart service
systemctl restart memcached

# Test connection
echo 'stats' | nc 127.0.0.1 11211

Memcached Basic Commands

hljs bash
# Connect via telnet
telnet 127.0.0.1 11211
# Set value (key, flag, TTL seconds, size bytes)
set session:xyz 0 3600 12
user_data

# Get value
get session:xyz

# Delete value
delete session:xyz

# View statistics
stats

# Clear all data
flush_all

Application Integration

PHP with Redis

hljs bash
# Install PHP Redis extension
apt install -y php-redis
systemctl restart php8.x-fpm
hljs php
<?php
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$redis->auth('StrongRedisPassword123!');

// Write to cache
$redis->setex('user:1', 3600, json_encode(['name' => 'John', 'email' => 'john@example.com']));

// Read from cache
$data = $redis->get('user:1');
if ($data) {
    $user = json_decode($data, true);
} else {
    // Fetch from database and cache
    $user = fetch_from_database(1);
    $redis->setex('user:1', 3600, json_encode($user));
}

Node.js with Redis

hljs bash
# Install ioredis package
npm install ioredis
hljs javascript
const Redis = require('ioredis');

const redis = new Redis({
  host: '127.0.0.1',
  port: 6379,
  password: 'StrongRedisPassword123!'
});

// Write to cache
await redis.setex('product:42', 1800, JSON.stringify({ name: 'Laptop', price: 999 }));

// Read from cache
const data = await redis.get('product:42');
if (data) {
  const product = JSON.parse(data);
  console.log(product);
}

// Clear cache
await redis.del('product:42');

Python with Redis

hljs bash
# Install redis-py package
pip install redis
hljs python
import redis
import json

r = redis.Redis(
    host='127.0.0.1',
    port=6379,
    password='StrongRedisPassword123!',
    decode_responses=True
)

# Write to cache
r.setex('article:5', 7200, json.dumps({'title': 'Redis Guide', 'content': '...'}))

# Read from cache
data = r.get('article:5')
if data:
    article = json.loads(data)

Service Management

hljs bash
# Redis service management
systemctl start redis-server
systemctl stop redis-server
systemctl restart redis-server
systemctl status redis-server

# View Redis logs
journalctl -u redis-server -f
tail -f /var/log/redis/redis-server.log

# Get Redis info via CLI
redis-cli INFO server
redis-cli INFO memory
redis-cli INFO stats

# Memcached service management
systemctl start memcached
systemctl stop memcached
systemctl restart memcached
systemctl status memcached

Conclusion

Redis and Memcached are powerful cache solutions that significantly improve application performance. Redis's rich data structures and persistence features make it ideal for most scenarios, while Memcached can be preferred for simple, high-performance string caching needs. Both systems run smoothly on REXE servers.