πŸ—„οΈ Databases

Key-Value Store

Key-Value Store

A NoSQL database that stores and retrieves values through unique keys, with Redis, DynamoDB, and etcd as typical examples, used for caching, session management, configuration storage, and more.

πŸ“– Detailed Explanation

Key-Value Store is the simplest form of NoSQL database, storing data as pairs of a unique key and the value linked to that key. With a structure similar to a hash table, it can read and write data in O(1) time complexity, providing extremely fast performance.

Representative Key-Value Stores include Redis (in-memory, supports various data structures), Amazon DynamoDB (fully managed, serverless), etcd (stores configuration for distributed systems), and Memcached (pure cache). Each has a specialized purpose, so you must choose according to your requirements.

Major use cases include caching (database query results, API response caches), session management (storing web application user sessions), real-time data (leaderboards, view counts, like counters), distributed locks (concurrency control), and message queues (Redis Pub/Sub, Streams).

Key-Value Stores also have limitations. Because data can only be looked up by key, complex queries and range searches are difficult (DynamoDB partly addresses this with Sort Keys). Expressing relationships between data is not possible, and transaction support is limited. Therefore, they are often used as a supplementary store alongside an RDBMS.

πŸ’» Code Example

Python Redis Usage Example

import redis
import json
from datetime import timedelta
from typing import Optional, Any

# Redis ν΄λΌμ΄μ–ΈνŠΈ μ΄ˆκΈ°ν™”
redis_client = redis.Redis(
    host='localhost',
    port=6379,
    db=0,
    decode_responses=True  # λ¬Έμžμ—΄ μžλ™ λ””μ½”λ”©
)

# ================================
# 1. κΈ°λ³Έ Key-Value μ—°μ‚°
# ================================
def cache_user(user_id: int, user_data: dict, ttl_seconds: int = 3600):
    """μ‚¬μš©μž 정보λ₯Ό μΊμ‹œμ— μ €μž₯"""
    key = f"user:{user_id}"
    redis_client.setex(key, ttl_seconds, json.dumps(user_data))

def get_cached_user(user_id: int) -> Optional[dict]:
    """μΊμ‹œμ—μ„œ μ‚¬μš©μž 정보 쑰회"""
    key = f"user:{user_id}"
    data = redis_client.get(key)
    return json.loads(data) if data else None

# μ‚¬μš©
cache_user(123, {"name": "홍길동", "email": "hong@example.com"})
user = get_cached_user(123)
print(user)  # {'name': '홍길동', 'email': 'hong@example.com'}


# ================================
# 2. μΊμ‹œ νŒ¨ν„΄: Cache-Aside
# ================================
def get_user_with_cache(user_id: int, db_session) -> dict:
    """μΊμ‹œ μš°μ„  쑰회, μ—†μœΌλ©΄ DBμ—μ„œ λ‘œλ“œ"""
    cache_key = f"user:{user_id}"

    # 1. μΊμ‹œ 확인
    cached = redis_client.get(cache_key)
    if cached:
        print("Cache HIT")
        return json.loads(cached)

    # 2. μΊμ‹œ 미슀 -> DB 쑰회
    print("Cache MISS")
    user = db_session.query(User).get(user_id)
    if user:
        user_dict = {"id": user.id, "name": user.name, "email": user.email}
        # 3. μΊμ‹œμ— μ €μž₯ (1μ‹œκ°„ TTL)
        redis_client.setex(cache_key, 3600, json.dumps(user_dict))
        return user_dict
    return None


# ================================
# 3. λΆ„μ‚° 락 κ΅¬ν˜„
# ================================
import uuid

def acquire_lock(lock_name: str, timeout: int = 10) -> Optional[str]:
    """λΆ„μ‚° 락 νšλ“"""
    lock_key = f"lock:{lock_name}"
    lock_id = str(uuid.uuid4())

    # SET NX (Not eXists) - ν‚€κ°€ 없을 λ•Œλ§Œ μ„€μ •
    acquired = redis_client.set(lock_key, lock_id, nx=True, ex=timeout)
    return lock_id if acquired else None

def release_lock(lock_name: str, lock_id: str) -> bool:
    """λΆ„μ‚° 락 ν•΄μ œ (Lua 슀크립트둜 μ›μžμ  처리)"""
    lock_key = f"lock:{lock_name}"

    # Lua 슀크립트: 본인이 νšλ“ν•œ 락인지 확인 ν›„ μ‚­μ œ
    script = """
    if redis.call("get", KEYS[1]) == ARGV[1] then
        return redis.call("del", KEYS[1])
    else
        return 0
    end
    """
    result = redis_client.eval(script, 1, lock_key, lock_id)
    return result == 1

# μ‚¬μš©
lock_id = acquire_lock("payment:order:123")
if lock_id:
    try:
        # 결제 처리 (λ™μ‹œμ— ν•˜λ‚˜λ§Œ 싀행됨)
        process_payment(order_id=123)
    finally:
        release_lock("payment:order:123", lock_id)


# ================================
# 4. 쑰회수/μΉ΄μš΄ν„° (Atomic Operations)
# ================================
def increment_view_count(article_id: int) -> int:
    """κ²Œμ‹œκΈ€ 쑰회수 증가 (μ›μžμ  μ—°μ‚°)"""
    key = f"article:{article_id}:views"
    return redis_client.incr(key)

def get_view_count(article_id: int) -> int:
    """쑰회수 쑰회"""
    key = f"article:{article_id}:views"
    count = redis_client.get(key)
    return int(count) if count else 0


# ================================
# 5. λ¦¬λ”λ³΄λ“œ (Sorted Set ν™œμš©)
# ================================
def update_leaderboard(game_id: str, user_id: str, score: float):
    """λ¦¬λ”λ³΄λ“œ 점수 μ—…λ°μ΄νŠΈ"""
    key = f"leaderboard:{game_id}"
    redis_client.zadd(key, {user_id: score})

def get_top_players(game_id: str, count: int = 10) -> list:
    """μƒμœ„ Nλͺ… 쑰회 (점수 λ‚΄λ¦Όμ°¨μˆœ)"""
    key = f"leaderboard:{game_id}"
    # ZREVRANGE: 점수 높은 순으둜 쑰회
    return redis_client.zrevrange(key, 0, count - 1, withscores=True)

def get_user_rank(game_id: str, user_id: str) -> Optional[int]:
    """νŠΉμ • μ‚¬μš©μžμ˜ μˆœμœ„ 쑰회 (0λΆ€ν„° μ‹œμž‘)"""
    key = f"leaderboard:{game_id}"
    rank = redis_client.zrevrank(key, user_id)
    return rank + 1 if rank is not None else None  # 1λΆ€ν„° μ‹œμž‘ν•˜λ„λ‘

# μ‚¬μš©
update_leaderboard("game1", "user:123", 1500)
update_leaderboard("game1", "user:456", 2200)
top_10 = get_top_players("game1", 10)
my_rank = get_user_rank("game1", "user:123")
print(f"λ‚΄ μˆœμœ„: {my_rank}μœ„")

πŸ—£οΈ How It's Said in Practice

Backend Developer "The product detail API response takes over 200ms. The DB query is heavy, so how about introducing a Redis cache?"
Architect "Sounds good. Implement it with the Cache-Aside pattern and set the TTL to about 5 minutes. And don't forget to invalidate the cache when product information is updated."
Infrastructure Engineer "I'll set up a Redis Cluster to ensure high availability and configure memory monitoring as well. I'll set maxmemory-policy to allkeys-lru."
Interviewer "What is the difference between Redis and Memcached?"
Candidate "Both are in-memory Key-Value Stores, but Redis supports various data structures such as List, Set, Hash, and Sorted Set in addition to String, and also provides data persistence (RDB, AOF). Memcached is specialized for simple caching, with good memory efficiency and multithreading support. For simple caching, I choose Memcached; if complex data structures or persistence are needed, I choose Redis."

Take a mock interview on this topic β†’ WIA SOOM AI Interview Β· Start for free

Reviewer "Here you get and then set if it's missing, and a race condition can occur in between."
Author "Right. I'll handle it atomically with SETNX (SET if Not eXists) or a Lua script. In distributed environments, this kind of thing is important."

⚠️ Cautions

  • Cache Consistency: If you forget to invalidate the cache when the source data changes, stale data will be returned. Clearly define a consistency strategy such as Write-through or Cache-aside.
  • Memory Management: In-memory stores have memory limits. Configure the maxmemory setting and eviction policy (LRU, LFU, etc.) appropriately, and monitor them.
  • Key Naming Convention: Establish a consistent key naming rule (e.g., `entity:id:field`) to improve manageability and prevent key collisions.

πŸ“š Learn More