Thread-Safe Config Registry with Stale-While-Revalidate
System DesignModel answerLast updated
Design a ConfigRegistry class that serves configuration to thousands of concurrent threads with lazy loading, stale fallback on failure, and no thundering herd.
Background
You are building a ConfigRegistry component for a high-throughput streaming service. Thousands of worker threads run simultaneously, and each one must retrieve the current configuration before it can process an event. The configuration lives in a remote database that is slow to query and occasionally unreachable.
Your Task
Design and implement a thread-safe ConfigRegistry class in Python (or Java) that satisfies the following requirements:
1. Read performance under high concurrency Reads should not block each other. Lock contention on the hot path must be negligible.
2. Lazy initialization The registry should not contact the remote database until a caller actually asks for the configuration. Fetching it eagerly on startup is not acceptable.
3. Graceful degradation during outages If the remote database cannot be reached, the registry must return the most recently fetched configuration rather than raising an error. It should also schedule a background refresh attempt rather than letting the stale value sit forever.
Assume a function fetch_remote_config() already exists. It is slow and may time out.
class ConfigRegistry:
def get_config(self) -> Config:
# your implementation here
Discussion Questions
After presenting your implementation, be ready to discuss:
- What concurrency primitive makes lazy initialization correct here, and why does a naive single-checked approach fail?
- How does your design balance returning a stale value (availability) against returning a consistent value (accuracy)? When would you choose stronger consistency instead?
- If
fetch_remote_config()calls start saturating the network or database connection pool, what mechanism limits the damage?
Edge Cases to Address
- Two threads both call
get_config()for the very first time, simultaneously, before any configuration has been loaded. What happens? - The configuration TTL expires at the same moment for many threads across many service instances. How do you prevent every thread — or every node — from issuing a refresh at once?
Hints
Hint 1
The hot read path should touch zero locks. Think about what you can store as a single immutable reference so that reading it is atomic by definition.
Hint 2
For the cold-start race, double-checked locking is the classical solution — but in Java it only works correctly if the shared field is declared volatile. In Python, assignment of a single attribute is atomic in CPython, but you still need an explicit lock to prevent two threads from both deciding to fetch.
Hint 3
To prevent thundering herd on TTL expiry, only one thread should schedule the background refresh. A non-blocking lock acquire (acquire(blocking=False)) is a clean single-flight guard: the thread that wins schedules the work, everyone else skips and returns the stale value immediately. Add jitter to backoff delays to desynchronize retries across a fleet.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The central insight is that different operations have very different frequency and coordination requirements:
| Operation | Frequency | Strategy |
|---|---|---|
| Read a valid, non-expired snapshot | ~99.99 % of calls | Lock-free: read one reference |
| Cold start (no snapshot yet) | Once per process lifetime | Double-checked locking, one fetch |
| Snapshot expired | Once per TTL period | Non-blocking single-flight, async refresh |
| Remote fetch fails | During outages | Keep last known good, exponential backoff with jitter |
This is the stale-while-revalidate pattern. After the first successful load, callers never wait on the network.
Why Each Piece Is Necessary
Immutable snapshot. Wrapping the config and its timestamp in a frozen dataclass means the object is fully constructed before any reference to it is published. A reader sees either the old snapshot or the new one — never a half-initialized object. In Python, assigning a single attribute is atomic in CPython. In Java you would use a volatile field or AtomicReference to get the same happens-before guarantee.
Double-checked locking for cold start. The first check (if snap is None) runs without a lock, so steady-state reads pay no contention cost. Only when the snapshot is truly absent do threads contend on _init_lock. The second check inside the lock handles the race where two threads both passed the first check: the losing thread sees the snapshot published by the winner and returns it without re-fetching.
Single-flight refresh. When the TTL expires, acquire(blocking=False) lets exactly one thread schedule a background refresh. Every other concurrent caller skips, gets the stale value, and returns immediately — no pile-up. The lock is released by the worker thread when the refresh completes (or fails).
Circuit-breaker / backoff. After each failed fetch, the next attempt is gated behind an exponentially growing delay with ±50 % jitter. This stops the service from hammering an already-struggling database. Across a fleet, add per-node TTL jitter to prevent synchronized expiry storms.
Implementation
import random
import threading
import time
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass
from typing import Any, Callable, Optional
@dataclass(frozen=True)
class Snapshot:
config: Any
fetched_at: float # monotonic seconds
class ConfigUnavailableError(RuntimeError):
"""Only raised when no successful fetch has ever completed."""
class ConfigRegistry:
def __init__(
self,
fetch: Callable[[], Any], # wraps fetch_remote_config(); owns its timeout
ttl: float = 30.0,
base_backoff: float = 1.0,
max_backoff: float = 60.0,
clock: Callable[[], float] = time.monotonic,
):
self._fetch = fetch
self._ttl = ttl
self._base_backoff = base_backoff
self._max_backoff = max_backoff
self._clock = clock
self._snapshot: Optional[Snapshot] = None # published atomically
self._init_lock = threading.Lock()
self._refresh_lock = threading.Lock() # single-flight guard
self._failures = 0
self._next_attempt_at = 0.0
self._executor = ThreadPoolExecutor(
max_workers=1, thread_name_prefix="config-refresh"
)
# ── public API ────────────────────────────────────────────────────────────
def get_config(self) -> Any:
snap = self._snapshot # lock-free fast path
if snap is None:
snap = self._initialize() # cold start
elif self._clock() - snap.fetched_at > self._ttl:
self._maybe_schedule_refresh() # never blocks the caller
return snap.config
def staleness_seconds(self) -> Optional[float]:
snap = self._snapshot
return None if snap is None else self._clock() - snap.fetched_at
def close(self) -> None:
self._executor.shutdown(wait=False)
# ── cold start ────────────────────────────────────────────────────────────
def _initialize(self) -> Snapshot:
with self._init_lock:
snap = self._snapshot
if snap is not None: # another thread already fetched
return snap
if self._clock() < self._next_attempt_at:
raise ConfigUnavailableError("still in backoff after failed initial fetch")
try:
config = self._fetch()
except Exception as exc:
self._record_failure()
raise ConfigUnavailableError("initial fetch failed") from exc
snap = Snapshot(config, self._clock())
self._record_success()
self._snapshot = snap
return snap
# ── background refresh ────────────────────────────────────────────────────
def _maybe_schedule_refresh(self) -> None:
if self._clock() < self._next_attempt_at: # circuit open
return
if not self._refresh_lock.acquire(blocking=False):
return # refresh already in flight
try:
self._executor.submit(self._do_refresh)
except Exception:
self._refresh_lock.release()
raise
def _do_refresh(self) -> None:
try:
config = self._fetch()
self._snapshot = Snapshot(config, self._clock())
self._record_success()
except Exception:
self._record_failure() # keep last known good snapshot
finally:
self._refresh_lock.release()
# ── backoff bookkeeping ───────────────────────────────────────────────────
def _record_success(self) -> None:
self._failures = 0
self._next_attempt_at = 0.0
def _record_failure(self) -> None:
self._failures += 1
delay = min(self._max_backoff,
self._base_backoff * 2 ** (self._failures - 1))
self._next_attempt_at = self._clock() + delay * random.uniform(0.5, 1.0)
Edge Cases
Two threads race to cold-start. Both pass the outer if snap is None check. One acquires _init_lock and fetches. The second blocks on the lock, re-checks inside, finds the snapshot already published, and returns it — no duplicate fetch.
Thundering herd on TTL expiry. Only the thread that wins acquire(blocking=False) schedules a refresh. All others return the stale value immediately. Across a fleet, initialize each node's TTL with a small random offset (e.g., ttl + random.uniform(-5, 5)) so expiry doesn't happen simultaneously cluster-wide.
Database is down at cold start. There is no previous value to fall back to, so ConfigUnavailableError is raised. If the business requires availability before the remote database is ready, you can seed the registry with a bundled default config that is overwritten on the first successful fetch.
Slow fetch saturates connections. _maybe_schedule_refresh only schedules work if the single-flight lock is free, and the executor has max_workers=1. At most one outbound refresh connection is ever in flight from this instance. Backoff with jitter prevents repeated storms after failures.
Complexity
- Time:
get_configis O(1) with no lock on the steady-state path. Cold start and refresh are each O(1) local work plus one remote call, amortized over the TTL. - Space: O(1) — one snapshot reference, one background thread.
Availability vs. Consistency Tradeoff
This design heavily favors availability: callers always get a value (possibly stale) rather than blocking on network I/O. The right choice depends on how sensitive the system is to using an outdated configuration. If a stale config could cause data loss or security issues, you would flip to a read-through model (block all callers until a fresh value is confirmed) and accept the latency penalty. For most operational configuration — feature flags, rate limits, routing weights — staleness of a few TTL periods is acceptable.