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.
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.
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.
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}μ")
Take a mock interview on this topic β WIA SOOM AI Interview Β· Start for free