Back
+30 XP
Concept

Gauntlet 01: Mini Redis In-Memory KV Server

Redis delivers microsecond key-value caching using in-memory hash tables and time-to-live (TTL) expiration. Keys expire through passive checks on access and proactive background evictions. Implementing Redis primitives requires managing atomic dictionary states and timestamp expiration counters.

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

# Gauntlet 01: Mini Redis In-Memory KV Server Welcome to **The Grand Master Gauntlet**. Over the next 15 drills, you are no longer writing small helper scripts. You are engineering complete, production-grade micro-engines from scratch. 🏆⚡ Your first challenge: **Mini Redis**. Redis is an in-memory key-value data structure store used by millions of applications for caching and session state. - **`SET key value [EX seconds]`**: Associates a string value with a key, with an optional TTL expiration in seconds. - **`GET key`**: Returns the value, or `None` if the key does not exist or has expired. - **`EXPIRE key seconds`**: Sets or updates the TTL on an existing key. - **`TTL key`**: Returns remaining seconds until expiration, `-1` if the key exists without expiration, or `-2` if missing/expired. - **`DEL key`**: Removes the key and returns `1` if deleted, `0` otherwise. ```python import time # Passive expiration: check before returning ``` ## Pop Quiz What is passive expiration in Redis key-value storage engines? - [ ] Keys are only checked for expiration and deleted at the exact moment a client attempts to read them. - [ ] Keys are purged from memory when server CPU temperatures exceed 80 degrees Celsius. - [ ] Expired keys are moved to Linux swap partitions rather than deleted. - [ ] Because Redis automatically converts string values to integer lists after 5 minutes. ## Real-World Challenge Implement `MiniRedis`: - `set(key: str, value: str, ex: float = None)` - `get(key: str) -> str | None` (passively purges expired keys) - `expire(key: str, seconds: float) -> int` (returns 1 on success, 0 if key missing/expired) - `ttl(key: str) -> int` (returns remaining seconds, -1 if no TTL, -2 if missing) - `delete(key: str) -> int` (returns 1 if key was present, 0 otherwise) <details> <summary>Solution</summary> ```python import time class MiniRedis: def __init__(self): self._data = {} self._expires = {} def _is_expired(self, key: str) -> bool: if key in self._expires: if time.time() >= self._expires[key]: del self._data[key] del self._expires[key] return True return False def set(self, key: str, value: str, ex: float = None): self._data[key] = str(value) if ex is not None: self._expires[key] = time.time() + float(ex) elif key in self._expires: del self._expires[key] def get(self, key: str) -> str | None: if self._is_expired(key) or key not in self._data: return None return self._data[key] def expire(self, key: str, seconds: float) -> int: if self._is_expired(key) or key not in self._data: return 0 self._expires[key] = time.time() + float(seconds) return 1 def ttl(self, key: str) -> int: if self._is_expired(key) or key not in self._data: return -2 if key not in self._expires: return -1 remaining = int(self._expires[key] - time.time()) return max(0, remaining) def delete(self, key: str) -> int: existed = (key in self._data) and not self._is_expired(key) self._data.pop(key, None) self._expires.pop(key, None) return 1 if existed else 0 # Verification r = MiniRedis() # 1. Basic SET and GET r.set("user:101", "Alice") assert r.get("user:101") == "Alice" assert r.ttl("user:101") == -1 # 2. TTL Expiration r.set("temp_session", "TOKEN_ABC", ex=0.04) assert r.get("temp_session") == "TOKEN_ABC" assert r.ttl("temp_session") >= 0 time.sleep(0.05) assert r.get("temp_session") is None assert r.ttl("temp_session") == -2 # 3. EXPIRE update r.set("flag", "1") assert r.expire("flag", 100) == 1 assert r.ttl("flag") >= 90 assert r.delete("flag") == 1 assert r.delete("flag") == 0 ``` </details>