🗄️ Databases

Redis

Remote Dictionary Server

An in-memory key-value store. Used for caching, session management, and message queues. Handles hundreds of thousands of operations per second.

📖 Detailed Explanation

What is Redis?

Redis is an abbreviation of "Remote Dictionary Server" and is an open-source in-memory data structure store developed by Salvatore Sanfilippo in 2009. It stores all data in memory, providing read/write performance tens to hundreds of times faster than disk-based databases.

Core Data Structures

Redis goes beyond a simple key-value store and supports a variety of data structures:

  • String: Basic strings, numeric counters, binary data
  • Hash: A collection of field-value pairs (user profiles, etc.)
  • List: A list of strings that preserves insertion order (queues, stacks)
  • Set: A collection of unique strings with no duplicates (tags, unique visitors)
  • Sorted Set (ZSet): A Set sorted by score (leaderboards, rankings)
  • Stream: A log-style data structure (event sourcing)
  • HyperLogLog: Cardinality estimation for large datasets

Main Use Cases

  • Caching: Caching DB query results, API responses, and session data
  • Session Store: Managing user sessions in distributed environments
  • Rate Limiting: Limiting API call frequency
  • Real-Time Leaderboard: Game rankings, real-time standings
  • Pub/Sub: Real-time messaging, event broker
  • Distributed Lock: Concurrency control based on the Redlock algorithm

Persistence

Although it is in-memory, it provides options for data persistence:

  • RDB (Snapshotting): Saves a full snapshot of the data at a specific point in time
  • AOF (Append Only File): Records every write operation as a log
  • RDB + AOF: Maximizes durability by combining both methods

High Availability and Scalability

  • Redis Sentinel: Automatic failover and monitoring
  • Redis Cluster: Horizontal scaling through data sharding
  • Master-Replica: Read distribution and data replication

💻 Code Example

Basic Usage with Python (redis-py)

Python
import redis
from datetime import timedelta

# Redis 연결
r = redis.Redis(host='localhost', port=6379, db=0, decode_responses=True)

# String 기본 연산
r.set('user:1001:name', 'Alice')
r.set('user:1001:visits', 0)
r.incr('user:1001:visits')  # 원자적 증가

# TTL 설정 (캐싱)
r.setex('session:abc123', timedelta(hours=1), 'user_data_here')

# Hash - 사용자 프로필
r.hset('user:1001', mapping={
    'name': 'Alice',
    'email': 'alice@example.com',
    'plan': 'premium'
})
profile = r.hgetall('user:1001')

# List - 최근 활동 (최근 10개만 유지)
r.lpush('user:1001:activity', 'login')
r.lpush('user:1001:activity', 'view_page')
r.ltrim('user:1001:activity', 0, 9)

# Sorted Set - 리더보드
r.zadd('leaderboard', {'alice': 1500, 'bob': 1200, 'charlie': 1800})
top3 = r.zrevrange('leaderboard', 0, 2, withscores=True)
# [('charlie', 1800), ('alice', 1500), ('bob', 1200)]

Cache Pattern (Cache-Aside)

Python
import redis
import json

r = redis.Redis(host='localhost', port=6379, decode_responses=True)

def get_user(user_id):
    cache_key = f'user:{user_id}'

    # 1. 캐시에서 먼저 조회
    cached = r.get(cache_key)
    if cached:
        return json.loads(cached)

    # 2. 캐시 미스 → DB 조회
    user = db.query(f"SELECT * FROM users WHERE id = {user_id}")

    # 3. 캐시에 저장 (TTL 5분)
    if user:
        r.setex(cache_key, 300, json.dumps(user))

    return user

def update_user(user_id, data):
    # DB 업데이트
    db.update('users', user_id, data)

    # 캐시 무효화
    r.delete(f'user:{user_id}')

Rate Limiting (Sliding Window)

Python
import time

def is_rate_limited(user_id, limit=100, window=60):
    """
    1분에 100회 요청 제한
    """
    key = f'ratelimit:{user_id}'
    now = time.time()

    pipe = r.pipeline()

    # 윈도우 밖의 요청 제거
    pipe.zremrangebyscore(key, 0, now - window)

    # 현재 요청 수 확인
    pipe.zcard(key)

    # 현재 요청 추가
    pipe.zadd(key, {str(now): now})

    # TTL 설정
    pipe.expire(key, window)

    results = pipe.execute()
    request_count = results[1]

    return request_count >= limit

Distributed Lock

Python
import uuid
import time

class RedisLock:
    def __init__(self, redis_client, lock_name, expire_time=10):
        self.redis = redis_client
        self.lock_name = f'lock:{lock_name}'
        self.expire_time = expire_time
        self.lock_id = str(uuid.uuid4())

    def acquire(self, timeout=10):
        end_time = time.time() + timeout
        while time.time() < end_time:
            if self.redis.set(self.lock_name, self.lock_id,
                             ex=self.expire_time, nx=True):
                return True
            time.sleep(0.1)
        return False

    def release(self):
        # Lua 스크립트로 원자적 해제 (자신의 락만)
        script = """
        if redis.call('get', KEYS[1]) == ARGV[1] then
            return redis.call('del', KEYS[1])
        else
            return 0
        end
        """
        return self.redis.eval(script, 1, self.lock_name, self.lock_id)

# 사용 예
lock = RedisLock(r, 'payment:user:1001')
if lock.acquire():
    try:
        process_payment()
    finally:
        lock.release()

Pub/Sub Real-Time Messaging

Python
# Publisher
def publish_event(channel, message):
    r.publish(channel, json.dumps(message))

publish_event('notifications', {
    'user_id': 1001,
    'type': 'order_complete',
    'order_id': 'ORD-12345'
})

# Subscriber
def subscribe_handler():
    pubsub = r.pubsub()
    pubsub.subscribe('notifications')

    for message in pubsub.listen():
        if message['type'] == 'message':
            data = json.loads(message['data'])
            print(f"Received: {data}")

💬 Real-world conversation examples

Backend developer
"The API response is too slow. The DB query is complex and takes as much as 500ms..."
Senior developer
"If the data is queried frequently, let's apply Redis caching. On a cache hit, we can respond within 1ms."
Backend developer
"How do we handle cache invalidation? We'd have to synchronize every time the data changes."
Senior developer
"Let's use the Cache-Aside pattern and keep the TTL short. If consistency is important, consider Write-Through too. We could even synchronize automatically with CDC."
DevOps engineer
"If Redis goes down, the entire service fails. How do we handle that?"
Architect
"Set up automatic failover with Redis Sentinel, and make sure to include DB fallback logic in the application for cache misses. So that it works, even if slowly, without the cache."
Junior Developer
"They say to store sessions in Redis, but how is that different from the existing server memory sessions?"
Senior developer
"With multiple servers, sessions can't be shared. With Redis, all servers can access the same session data, so it works fine even behind a load balancer."

⚠️ Cautions

⚠️ Memory Capacity Management
Redis stores all data in memory. Be sure to configure the maxmemory setting and an eviction policy (LRU, LFU, etc.). When memory runs out, writes may be rejected or unexpected data loss may occur.
⚠️ Cache Consistency Issues
Beware of data inconsistency between the DB and the cache (Cache Inconsistency). Choose TTL-based expiration and Write-Through/Write-Behind patterns appropriately, and implement cache invalidation logic thoroughly for critical data.
⚠️ Key Naming Convention
Define consistent key naming rules (e.g., "service:entity:id:field"). Using keys without namespaces leads to key collisions and management difficulties. The KEYS command must never be used in production (it causes blocking).
⚠️ Verify Persistence Settings
Check whether the default RDB snapshot interval is appropriate. For critical data, enable AOF and adjust the tolerance for data loss with the appendfsync option. If zero data loss is required, use "always" (accounting for performance degradation).

🔗 Related Terms

📚 Learn More