Redis의 TTL 및 만료
Redis가 키 만료를 처리하는 방법을 학습합니다. TTL 설정, EXPIRE 및 SETEX 명령, 지연 만료와 능동 만료의 작동 방식, maxmemory 제거 정책과 TTL의 상호 작용을 다룹니다.
Redis의 TTL 및 만료은(는) CoddyKit의 무료 Caching Strategies: Redis + CDN + Edge Computing 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Caching Strategies: Redis + CDN + Edge Computing 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Caching Strategies: Redis + CDN + Edge Computing 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Why Expire Cache Keys?
Cached data goes stale. Time To Live (TTL) lets Redis automatically remove a key after a set duration, so your cache stays reasonably fresh without manual cleanup.
Setting a TTL with EXPIRE
The EXPIRE command sets a timeout in seconds on an existing key. After that time, Redis deletes the key automatically.
SET user:1 "Alice"
EXPIRE user:1 60
TTL user:1SET with EX in One Step
You can set a value and its TTL together. SET key value EX seconds (or the older SETEX) avoids a race between writing and expiring.
SET session:abc "data" EX 300Checking Remaining TTL
The TTL command returns seconds left. PTTL returns milliseconds. Special return values matter:
-1: key exists but has no expiry-2: key does not exist
def interpret_ttl(value):
if value == -1:
return 'no expiry set'
if value == -2:
return 'key does not exist'
return str(value) + 's remaining'
print(interpret_ttl(-2))
print(interpret_ttl(45))Removing an Expiry
The PERSIST command removes the TTL from a key, making it permanent again. Useful when a value should stop expiring after some condition is met.
PERSIST user:1Lazy Expiration
Redis does not check every key constantly. With lazy expiry, an expired key is only removed when someone tries to access it. Until then it lingers in memory.
Active Expiration
To reclaim memory from keys nobody touches, Redis also runs a background sampler that periodically removes a batch of expired keys. This is active expiry. Together with lazy expiry it keeps memory in check.
TTL vs Eviction
TTL is voluntary removal at a set time. Eviction happens when Redis hits its maxmemory limit and must drop keys to make room. They are different mechanisms that often work together.
volatile vs allkeys Policies
Eviction policies decide what to drop under memory pressure:
volatile-lru: evict least-recently-used keys that have a TTLallkeys-lru: evict LRU among all keys
For a pure cache, allkeys policies are common.
Choosing TTL Values
Pick TTLs from the data's tolerance for staleness: seconds for fast-changing prices, hours for catalogs, days for rarely-changing config. Add jitter to avoid synchronized mass expiry.
import random
base = 3600
print('TTL:', base + random.randint(0, 300), 'seconds')Common Pitfall: No TTL
Forgetting to set a TTL turns a cache into an ever-growing store that eventually exhausts memory. For cache use cases, almost every key should have an expiry or rely on an allkeys eviction policy.
Quick Check
What does the Redis command TTL mykey return if the key exists but has no expiration set?
Recap
You learned TTL and expiration in Redis:
- EXPIRE / SET ... EX set timeouts; TTL/PTTL inspect them; PERSIST removes them.
- Redis uses lazy plus active expiration.
- Eviction policies (volatile vs allkeys) handle memory pressure.
- Always set TTLs (or an allkeys policy) for cache keys.
Good expiration keeps a cache both fresh and bounded.
자주 묻는 질문
“Redis의 TTL 및 만료” 강의는 무료인가요?
네 — “Redis의 TTL 및 만료” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Caching Strategies: Redis + CDN + Edge Computing 강의 전체를 잠금 해제할 수 있습니다. Caching Strategies: Redis + CDN + Edge Computing 강의에는 총 4개의 강의가 포함되어 있습니다.
“Redis의 TTL 및 만료”에서 뭘 배우나요?
Redis가 키 만료를 처리하는 방법을 학습합니다. TTL 설정, EXPIRE 및 SETEX 명령, 지연 만료와 능동 만료의 작동 방식, maxmemory 제거 정책과 TTL의 상호 작용을 다룹니다. 브라우저에서 직접 실행하는 실습 코드로 Caching Strategies: Redis + CDN + Edge Computing을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Caching Strategies: Redis + CDN + Edge Computing을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Caching Strategies: Redis + CDN + Edge Computing은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 4번째 강의입니다.
“Redis의 TTL 및 만료” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Caching Strategies: Redis + CDN + Edge Computing 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Caching Strategies: Redis + CDN + Edge Computing 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- Redis 캐싱 소개
- 캐시를 위한 Redis 데이터 구조
- 기본 Redis 캐시 작업
- Redis의 TTL 및 만료