Build a Real-Time Configuration Management System
System DesignModel answerLast updated
Design a service that stores configuration data and notifies subscribed clients when values change, covering APIs, consistency, scaling, and failure handling.
You need to architect a configuration management system that serves application settings and alerts connected clients whenever configurations are modified.
Your system should support:
- Storing and retrieving configuration key-value pairs
- Allowing clients to watch specific keys or entire prefixes (e.g.,
database/*) - Sending updates to watchers immediately when values change
- Handling thousands of concurrent client connections
Design the complete system including:
- API surface: What methods do clients use? What about bulk operations?
- Update delivery: How do you guarantee subscribers receive changes? What about ordering and duplicates?
- Consistency model: How do you handle concurrent writes, versioning, and the ability to revert changes?
- Failure scenarios: What happens when connections drop, servers crash, or callbacks fail?
- Scalability: How does your design handle 10,000+ clients subscribing to overlapping key prefixes?
- Performance analysis: What are the time and space complexities of critical operations?
Be specific about trade-offs, implementation details, and how you'd validate correctness.
Hints
Hint 1
Think about how a monotonically increasing version number can solve multiple problems at once: ordering, deduplication, and resumption after reconnects
Hint 2
Separate the consensus layer (small, strongly consistent) from the notification layer (horizontally scalable, eventually consistent) to handle large fan-out
Hint 3
Client SDKs should cache config locally and persist to disk so applications can start even when the config service is unavailable
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Real-Time Configuration Management System
1. Requirements and Scale Assumptions
Begin by establishing the workload characteristics, which fundamentally shape architectural decisions.
A configuration system has an asymmetric traffic pattern: predominantly reads and watches, with infrequent writes. Typical assumptions:
- Client count: 10,000 application instances
- Key space: 100,000 configuration keys, each value up to 64 KB
- Write rate: 10 writes/second steady-state, higher during deployments
- Read rate: effectively unlimited due to client-side caching
- Notification latency target: sub-second p99 from write commit to client notification
- Durability: must survive server failures without data loss
- Availability pattern: clients should continue operating on cached config even during control plane outages ("static stability")
2. API Design
# Core operations
write(key, value, compare_version=None, request_id) -> version_number
write_atomic([(key, value), ...], expected_versions) -> global_version
read(key, at_version=None) -> (value, version_number)
read_prefix(prefix) -> {key: (value, version), ...}, snapshot_version
# Subscription
watch(key_or_prefix, starting_from_version, callback_or_stream) -> subscription_handle
unwatch(subscription_handle)
# History and audit
get_history(key, max_entries) -> [(version, value, timestamp, author), ...]
restore_previous(key, target_version) -> new_version
For network protocols, watch maps to persistent connections: gRPC bidirectional streams, WebSockets, or HTTP/2 Server-Sent Events, with long-polling as a compatibility fallback.
3. Core Data Model
Use a global monotonic version counter that increments with every write operation. This single sequence number is the foundation for ordering, deduplication, and resumption.
Storage schema:
- Primary store:
key → {value, modification_version, creation_version, last_writer, timestamp} - Change stream: append-only log of
(version, key, operation, new_value)entries - Retention: keep recent changes (e.g., 7 days) plus periodic full snapshots for compaction
Key insights:
- The global version establishes a total order across all keys
- Clients can resume watching from any version: "give me all changes since version N"
- Atomic multi-key updates share a single version, preserving transaction boundaries
- Point-in-time reads are trivial: "show me key X as of version N"
4. Architecture Overview
┌─────────────┐
│ Clients │
│ (with SDK) │
└──────┬──────┘
│ gRPC streams
↓
┌──────────────────┐
│ Notification │ ← stateless, horizontally scaled
│ Fan-out Tier │ (matches subscriptions, pushes updates)
└────────┬─────────┘
│ tail log
↓
┌────────────────────┐
│ Storage Cluster │ ← small, strongly consistent
│ (Raft consensus) │ (3-5 nodes, handles writes)
│ + Change Log │
└────────────────────┘
Write path:
- Client sends write request
- Gateway authenticates and validates against schema
- Storage cluster performs Raft consensus write
- After quorum acknowledgment, return version to client
- Committed changes flow to change log
Watch path:
- Fan-out nodes continuously tail the change log
- Each node maintains in-memory subscription index (prefix tree)
- When a change appears, match it against registered subscriptions
- Push matching changes to relevant client connections
- Clients apply changes to local cache
Why separate fan-out from storage? Consensus algorithms like Raft work best with small, stable membership. Notification delivery benefits from horizontal scaling and stateless operation. This separation allows the system to scale to millions of clients without burdening the consistency layer.
5. Update Delivery Semantics
Delivery guarantee: at-least-once with client-side deduplication
Why not exactly-once? It's impossible to achieve in distributed systems. Why not at-most-once? Missing a config update silently is more dangerous than processing a duplicate.
Implementation:
- Server may send duplicates after reconnections or failover
- Client SDK tracks
last_applied_versionand ignores any event withversion ≤ last_applied_version - Result: exactly-once effect from at-least-once delivery
Ordering:
- Per-key ordering is guaranteed by the global version sequence
- Cross-key ordering within atomic batches is preserved (they share one version)
- Different keys written separately have causal order only if coordinated by the client
Optimization - coalescing: For slow consumers, buffer multiple rapid updates to the same key and deliver only the latest. Include the version range: "key X changed, versions 100-105, current value Y, current version 105." This prevents thundering herds during rapid config changes.
Compaction handling:
If a client requests starting_from_version=50 but the log only retains from version=1000, return a LOG_COMPACTED error. Client must:
- Perform full snapshot read via
read_prefix - Get snapshot version
- Resume watching from that version
6. Consistency and Versioning
Concurrent write control:
- Optimistic concurrency:
write(key, value, compare_version=expected)fails if current version doesn't match - Writers can retry with updated expectation
- Alternative: advisory locks for complex multi-step operations
Rollback mechanism: Never delete history. A rollback is a forward write of a previous value:
version 100: timeout_ms = 5000
version 101: timeout_ms = 500 (bad deployment)
version 102: timeout_ms = 5000 (rollback as new write)
Benefits:
- Complete audit trail preserved
- Watchers receive the rollback as a normal update
- No special-case logic
Safe deployment pattern:
- Schema validation on write
- Gradual rollout: route 1% of clients to new value first
- Monitor health metrics
- Auto-rollback if error rates spike
- Gradually increase percentage if healthy
7. Failure Handling
Writer timeout:
Client retries with same request_id. Server deduplicates based on ID, ensuring idempotent writes.
Storage node failure: Raft automatically elects new leader. In-flight writes that weren't acknowledged are lost, but that's correct—client never received confirmation.
Fan-out node crash:
Clients detect disconnect, reconnect to a different node with since=last_applied_version. New node replays from its buffered change log.
Client callback failure: Each subscription runs on an isolated thread/queue. If a callback throws or hangs:
- Log the error with metrics
- Retry with exponential backoff
- Never block other subscribers or writers
- Provide circuit breaker to disable misbehaving watchers
Complete outage: Client SDK design principle: persist last-known-good config to local disk. Applications can boot and run degraded using cached values. Once service recovers, clients reconnect and catch up.
8. Scalability Analysis
Fan-out strategy:
- Each fan-out node maintains an in-memory prefix trie:
prefix → set(connection_id) - Matching a key against subscriptions: O(key_depth × log(subscriptions))
- Typical: O(5) for key depth, negligible compared to network I/O
- Scale horizontally by adding nodes; client connections distribute via load balancer
Caching layers:
- Client SDK: immediate reads, zero network calls
- Edge cache tier (optional): for clients without SDK, CDN-style TTL-based cache
- Storage cluster: only handles writes and initial watch registration
Connection management:
- Use connection pooling and multiplexing
- One gRPC stream handles multiple key watches
- Heartbeat/keepalive to detect dead connections
- Exponential backoff on reconnect to avoid thundering herd
9. Complexity Analysis
| Operation | Time | Space |
|---|---|---|
write | O(log N) consensus + O(1) storage | O(value_size) |
read (local SDK) | O(1) | - |
read (cold) | O(1) key lookup | - |
watch registration | O(prefix_length) trie insert | O(1) per subscription |
| Change matching | O(key_depth × active_prefixes) | - |
| Fan-out | O(matched_subscribers) | O(window_size × changes) |
Storage: O(keys × value_size) + O(retained_history)
10. Common Mistakes
- Forgetting static stability: If the service is down, apps should keep running on cached config, not crash
- Synchronous callbacks under lock: Causes deadlocks and blocks writers
- TCP-only without reconnect logic: Connections drop; clients must resume gracefully
- No request deduplication: Network retries create duplicate writes
- Per-key version instead of global: Loses cross-key ordering and atomic batch semantics
- Exactly-once delivery claims: Impossible in distributed systems; design for idempotent application instead
- Notification fan-out on storage nodes: Doesn't scale; separate read/write concerns
11. Implementation Sketch (Simplified)
import threading
from collections import defaultdict
from dataclasses import dataclass
@dataclass
class Entry:
value: str
version: int
class ConfigStore:
def __init__(self):
self._lock = threading.RLock()
self._data = {} # key -> Entry
self._version = 0
self._watchers = defaultdict(list) # prefix -> [callback, ...]
def read(self, key):
# Lock-free read of immutable entry
return self._data.get(key)
def write(self, key, value):
with self._lock:
self._version += 1
new_entry = Entry(value, self._version)
self._data = {**self._data, key: new_entry} # copy-on-write
version = self._version
matched = self._find_watchers(key)
# Notify outside lock
for callback in matched:
try:
callback(key, value, version)
except Exception:
pass # log and continue
return version
def _find_watchers(self, key):
result = []
parts = key.split('/')
for i in range(len(parts) + 1):
prefix = '/'.join(parts[:i])
result.extend(self._watchers.get(prefix, []))
return result
def watch(self, prefix, callback):
with self._lock:
self._watchers[prefix].append(callback)
This simplified version demonstrates copy-on-write for lock-free reads and callback execution outside the critical section.