Cache
Cache
Temporarily keeping frequently used data in fast storage. Redis, Memcached. Reduces response time.
Cache
Temporarily keeping frequently used data in fast storage. Redis, Memcached. Reduces response time.
Cache is a technology that temporarily stores frequently accessed data in fast storage to reduce response time. It stores database query results, API responses, session information, and the like in memory to reduce repetitive computation and I/O.
Representative cache solutions include Redis (in-memory data structure server), Memcached (distributed memory cache), and Varnish (HTTP accelerator). Cache strategies include Cache-Aside (load on demand), Write-Through (update simultaneously on write), and Write-Behind (asynchronous write).
The higher the cache hit rate (Hit Rate), the greater the performance improvement, and expiration policy (TTL) and invalidation (Invalidation) strategy are the key to maintaining data consistency.
import redis
import json
# Redis 연결
cache = redis.Redis(host='localhost', port=6379, db=0)
def get_user_profile(user_id: int) -> dict:
cache_key = f"user:profile:{user_id}"
# 1. 캐시 확인
cached = cache.get(cache_key)
if cached:
print("Cache HIT")
return json.loads(cached)
# 2. 캐시 미스 - DB 조회
print("Cache MISS")
profile = db.query(f"SELECT * FROM users WHERE id = {user_id}")
# 3. 캐시에 저장 (TTL 300초)
cache.setex(cache_key, 300, json.dumps(profile))
return profile
def update_user_profile(user_id: int, data: dict):
# DB 업데이트
db.update("users", user_id, data)
# 캐시 무효화 (삭제)
cache.delete(f"user:profile:{user_id}")
# 패턴: 캐시 데코레이터
from functools import wraps
def cached(ttl=60):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
key = f"{func.__name__}:{args}:{kwargs}"
result = cache.get(key)
if result:
return json.loads(result)
result = func(*args, **kwargs)
cache.setex(key, ttl, json.dumps(result))
return result
return wrapper
return decorator
PM: "We're getting a lot of complaints that the product list API response takes as long as 2 seconds."
Backend Developer: "If we introduce a Redis cache, we can bring it down to within 50ms. Product information doesn't change often."
PM: "What about inventory or price changes?"
Backend Developer: "We invalidate the cache when product information is updated, and for inventory we can set a short TTL of 30 seconds."
Interviewer: "Please explain the problems that can occur with caching and how to resolve them."
Candidate: "Cache Stampede is a problem where concurrent requests surge when a TTL expires, and it is resolved with locks or probabilistic early refresh. Cache Penetration is when repeated lookups of nonexistent keys put load on the DB, and it is handled by caching empty values or using a Bloom Filter."
Interviewer: "How do you ensure cache consistency?"
Candidate: "Cache-Aside, which deletes the cache when data changes and refreshes it on the next lookup, is common, and for critical data, event-based invalidation is used."
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free
Reviewer: "This API only uses user_id for the cache key?"
Developer: "Because it's per-user data."
Reviewer: "But this response contains different text depending on the language setting. The cache key should include locale too."
Developer: "Ah, you're right. I'll change it to the form `user:{user_id}:locale:{locale}`."