Database

Redis

Overview

Redis is a high-performance in-memory data structure store. Used as a key-value store, cache, and message broker, it is designed for real-time data-driven applications. Standing for "Remote Dictionary Server," it is known for exceptional performance and rich data type support.

Details

Redis was developed by Salvatore Sanfilippo in 2009. By keeping all data in memory, it achieves extremely fast read and write operations. Beyond a simple key-value store, it supports diverse data structures including lists, sets, hashes, and streams.

Key features of Redis:

  • In-memory data storage
  • Rich data structures (strings, lists, sets, hashes, streams, etc.)
  • Persistence capabilities (RDB/AOF)
  • Replication
  • High availability (Redis Sentinel)
  • Clustering
  • Pub/Sub messaging
  • Lua script execution
  • Transactions
  • Geospatial data support

Advantages and Disadvantages

Advantages

  • Ultra-fast: Memory-based with extremely high performance
  • Versatile: Used as cache, database, and message broker
  • Rich data types: Direct support for various data structures
  • Lightweight: Simple and lightweight design
  • Scalability: Replication and clustering support
  • Ecosystem: Rich client libraries and tools
  • Open source: Free to use under BSD license

Disadvantages

  • Memory limitation: Available memory limits data size
  • Persistence: Memory-based requires proper persistence configuration
  • Single-threaded: Basically single-threaded command processing
  • Complex queries: Limited SQL-like complex query capabilities
  • Data type constraints: Limitations for relational data modeling

Key Links

Code Examples

Installation & Setup

# Ubuntu/Debian
sudo apt update
sudo apt install redis-server

# Red Hat/CentOS
sudo yum install epel-release
sudo yum install redis

# macOS (Homebrew)
brew install redis

# Docker
docker run --name redis-db -p 6379:6379 -d redis:latest

# Start Redis
sudo systemctl start redis
sudo systemctl enable redis

# Connect Redis client
redis-cli

Basic Operations (CRUD)

# String operations
SET user:1:name "John Doe"
GET user:1:name
SET user:1:age 30
INCR user:1:age
EXPIRE user:1:name 3600  # Delete after 1 hour

# Multiple key operations
MSET user:1:email "[email protected]" user:1:city "New York"
MGET user:1:name user:1:email user:1:city

# Key management
KEYS user:*
EXISTS user:1:name
DEL user:1:name
TTL user:1:email  # Check remaining expiration time

Data Structure Operations

# List operations
LPUSH shopping:list "milk" "bread" "eggs"
RPUSH shopping:list "apples"
LRANGE shopping:list 0 -1
LPOP shopping:list
LLEN shopping:list

# Set operations
SADD tags:user:1 "engineer" "javascript" "nodejs"
SMEMBERS tags:user:1
SISMEMBER tags:user:1 "javascript"
SCARD tags:user:1

# Hash operations
HSET user:1 name "John Doe" age 30 email "[email protected]"
HGET user:1 name
HGETALL user:1
HINCRBY user:1 age 1
HDEL user:1 email

# Sorted set operations
ZADD leaderboard 100 "player1" 200 "player2" 150 "player3"
ZRANGE leaderboard 0 -1 WITHSCORES
ZREVRANGE leaderboard 0 2 WITHSCORES  # Top 3
ZRANK leaderboard "player1"

Indexing & Optimization

# Check memory usage
INFO memory
MEMORY USAGE user:1

# Check key count
DBSIZE

# Benchmark
redis-benchmark -h localhost -p 6379 -c 100 -n 100000

# Set log level
CONFIG SET loglevel notice

# Performance settings
CONFIG SET maxmemory 2gb
CONFIG SET maxmemory-policy allkeys-lru

Practical Examples

# Session management
SETEX session:abc123 1800 '{"userId": 1, "username": "john"}'
GET session:abc123

# Counters
INCR page:views:home
INCRBY api:calls:today 1
GET page:views:home

# Pub/Sub messaging
# Subscriber
SUBSCRIBE notifications user:updates

# Publisher (in separate connection)
PUBLISH notifications "New message received"
PUBLISH user:updates "User information updated"

# Geospatial data
GEOADD cities -74.0059 40.7128 "New York" -118.2437 34.0522 "Los Angeles"
GEODIST cities "New York" "Los Angeles" km
GEORADIUS cities -74.0059 40.7128 100 km

Best Practices

# Pipeline processing
redis-cli --pipe < commands.txt

# Transactions
MULTI
SET user:1:name "John Doe"
INCR user:1:login_count
EXEC

# Lua scripts
EVAL "
local key = KEYS[1]
local value = redis.call('GET', key)
if value then
  return redis.call('INCR', key)
else
  redis.call('SET', key, 1)
  return 1
end
" 1 counter:visits

# Persistence configuration
# redis.conf
save 900 1      # Save if at least 1 key changed in 900 seconds
save 300 10     # Save if at least 10 keys changed in 300 seconds
save 60 10000   # Save if at least 10000 keys changed in 60 seconds

# Enable AOF
appendonly yes
appendfsync everysec

# Replication setup (slave side)
# redis.conf
replicaof 192.168.1.100 6379

Node.js Usage Example

const redis = require('redis')

// Create client
const client = redis.createClient({
  host: 'localhost',
  port: 6379
})

client.on('error', (err) => {
  console.log('Redis Client Error', err)
})

async function redisOperations() {
  await client.connect()
  
  // Basic operations
  await client.set('user:1:name', 'John Doe')
  const name = await client.get('user:1:name')
  console.log(name)
  
  // Hash operations
  await client.hSet('user:1', {
    name: 'John Doe',
    age: 30,
    email: '[email protected]'
  })
  
  const userData = await client.hGetAll('user:1')
  console.log(userData)
  
  // List operations
  await client.lPush('tasks', 'shopping', 'laundry', 'cleaning')
  const tasks = await client.lRange('tasks', 0, -1)
  console.log(tasks)
  
  await client.quit()
}

redisOperations()

Configuration and Tuning

# Key redis.conf settings
maxmemory 2gb
maxmemory-policy allkeys-lru
timeout 300
tcp-keepalive 300
databases 16

# Security settings
requirepass your_password_here
bind 127.0.0.1

# Network settings
port 6379
tcp-backlog 511