Back
+20 XP
Concept

Redis Clone Part 2: Key-Value Engine with TTL Eviction

An in-memory store must purge expired keys to conserve memory. Redis pairs passive expiration (checking expiry when a key is queried) with active background random sampling to prune untouched dead keys ⏱️.

python
import time

class RedisEngine:
    def __init__(self):
        self.data = {}
        self.expires = {}

    def set(self, key, val, ttl=None):
        self.data[key] = val
        if ttl:
            self.expires[key] = time.time() + ttl

    def get(self, key):
        # Passive expiration check:
        if key in self.expires and time.time() >= self.expires[key]:
            del self.data[key]
            del self.expires[key]
            return None
        return self.data.get(key)

engine = RedisEngine()
engine.set("auth_token", "secret123", ttl=0.1)
print(f"Value: {engine.get('auth_token')} ⏱️")

# 108. Redis Clone Part 2: Key-Value Engine with TTL Eviction An in-memory store must purge expired keys to conserve memory. Redis pairs passive expiration (checking expiry when a key is queried) with active background random sampling to prune untouched dead keys ⏱️. ```python import time class RedisEngine: def __init__(self): self.data = {} self.expires = {} def set(self, key, val, ttl=None): self.data[key] = val if ttl: self.expires[key] = time.time() + ttl def get(self, key): # Passive expiration check: if key in self.expires and time.time() >= self.expires[key]: del self.data[key] del self.expires[key] return None return self.data.get(key) engine = RedisEngine() engine.set("auth_token", "secret123", ttl=0.1) print(f"Value: {engine.get('auth_token')} ⏱️") ``` If keys are written with TTLs but never queried again, passive expiration alone would leak memory. Redis runs an active cycle 10 times per second, randomly testing 20 keys with expiries and deleting expired ones ⚡! --- ### Question What is 'passive expiration' in an in-memory key-value database? 🧠 - [ ] a. Keys are checked for expiry and pruned lazily only when accessed by a query ⏱️ - [ ] b. A separate background OS thread scans all RAM addresses every microsecond - [ ] c. Keys are never purged from memory until an OOM crash occurs - [ ] d. Keys are automatically compressed into gzip streams on timeout --- ### Challenge Build `RedisEngine` with `set(key, val, ttl)` and `get(key)`. Store `'token'` with `ttl = 0.05`. Sleep `0.06`, query `get('token')`, and print the returned value (`None`). 🎯 <details> <summary>Solution</summary> ```python import time class RedisEngine: def __init__(self): self.kv = {} self.exp = {} def set(self, k, v, ttl=None): self.kv[k] = v if ttl: self.exp[k] = time.time() + ttl def get(self, k): if k in self.exp and time.time() >= self.exp[k]: del self.kv[k] del self.exp[k] return None return self.kv.get(k) e = RedisEngine() e.set('token', 'abc', ttl=0.05) time.sleep(0.06) print(e.get('token')) ``` </details>

Checkpoint

What is 'passive expiration' in an in-memory key-value database? 🧠

Practice

Build `RedisEngine` with `set(key, val, ttl)` and `get(key)`. Store `'token'` with `ttl = 0.05`. Sleep `0.06`, query `get('token')`, and print the returned value (`None`). 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks