The design round is a conversation about trade-offs
System design interviews do not have a single correct architecture; they evaluate whether you can estimate scale, pick components, defend the trade-offs, and anticipate failure. For Python engineers the extra dimension is tool awareness โ knowing when a threaded Flask service with Redis in front is right, and when the problem demands sharded Postgres, a Kafka topic, or an event-sourced core. The strongest candidates open with requirements and back-of-envelope numbers, sketch a request path end to end, then go deep on two or three components the interviewer cares about. This lesson gives you the recurring components โ load balancing, consistent hashing, rate limiting, caching, queues, circuit breakers โ each with the Python sketch and the trade-off conversation that should accompany it.
Prerequisites
- !Dictionaries, threads, and basic networking vocabulary
- !The concurrency and design pattern lessons from this track
What You'll Learn
- 1Frame a design problem with requirements, scale estimates, and a request path
- 2Explain load balancing strategies and implement consistent hashing with virtual nodes
- 3Build token-bucket rate limiting and layered caches with clear eviction policies
- 4Connect queues, event stores, and circuit breakers into a resilient service architecture
Start with requirements and a sketch
Before drawing boxes, nail down what success looks like. Read-heavy or write-heavy? Latency budget โ fifty milliseconds or five hundred? Consistency requirements โ can reads be stale for a second? Scale โ requests per second, storage per day, number of clients? These questions take two minutes and eliminate half the design space. Then sketch the path: client, CDN or edge, load balancer, stateless application tier, cache, database, and any async workers behind a queue. Naming this skeleton first gives every later component a place to attach, and interviewers relax once they see you have a mental map.
Estimate with round numbers. Ten million users, one percent peak concurrent, fifty requests per second each yields something like five hundred thousand requests per second at peak โ obviously beyond one box, so horizontal scaling is assumed. A thousand bytes per record times a hundred million records is a hundred gigabytes, which fits one Postgres node with room to spare but argues for object storage if the records are blobs. Doing arithmetic out loud is itself a signal.
Load balancing and routing
Round-robin distributes requests evenly across healthy backends; weighted round-robin accounts for heterogeneous machines; least-connections favors servers with spare capacity; consistent hashing pins sessions or shards without reshuffling everything on membership change. Implementing a tiny round-robin balancer with a health dictionary is a five-minute whiteboard exercise that grounds the conversation โ and the natural follow-up is what happens when a server dies: health checks must fail fast, and the balancer must skip unhealthy entries without starving the rotation.
Consistent hashing deserves its own explanation. Hash every key and every node onto a virtual ring; a key belongs to the next node clockwise. Adding or removing a node only remaps the keys in its arc โ roughly one over n of the keys โ instead of the remapping catastrophe of modulo hashing. Virtual nodes, a hundred or more per physical server, smooth out uneven arc sizes so load stays balanced. Mention that Redis Cluster and Cassandra both use ring-style placement, and that the same idea appears in CDN cache routing.
import hashlib
from bisect import bisect_right
class ConsistentHashRing:
"""Ring with virtual nodes; remaps only an arc on membership change."""
def __init__(self, nodes, virtual_nodes=150):
self.ring = {}
self.sorted = []
for node in nodes:
self._add(node, virtual_nodes)
def _hash(self, key):
return int(hashlib.md5(key.encode()).hexdigest(), 16)
def _add(self, node, count):
for i in range(count):
point = self._hash(f"{node}:v{i}")
self.ring[point] = node
self.sorted.append(point)
self.sorted.sort()
def node_for(self, key):
if not self.ring:
return None
point = self._hash(key)
index = bisect_right(self.sorted, point) % len(self.sorted)
return self.ring[self.sorted[index]]
ring = ConsistentHashRing(["shard-a", "shard-b", "shard-c"])
print(ring.node_for("user:12345"))
Protecting the service: rate limiting and circuit breakers
Rate limiting sits at the edge and protects both your workers and downstream vendors. The token bucket allows bursts up to a capacity while refilling at a steady rate โ capacity for the burst, refill rate for the sustainable throughput. A fixed-window counter is simpler but admits a burst at window boundaries; a sliding log is accurate but memory-hungry; the sliding window hybrid is the usual production choice. Implementing consume and refill against a monotonic clock, with a lock for thread safety, shows you have shipped one before.
Circuit breakers handle downstream failure without cascading it back to your users. Closed state passes traffic and counts failures; after a threshold the breaker opens and fails fast โ optionally serving a fallback result โ until a recovery timeout elapses; half-open state lets a probe request through, closing on success and re-opening on failure. Combining a breaker with a fallback cache or a default response is the pattern that keeps a payment service usable when the fraud-scoring dependency is down. The conversation to lead: breakers protect the caller and the callee alike, and their thresholds belong in configuration, not hard-coded constants.
import time
import threading
class TokenBucket:
"""Thread-safe token bucket rate limiter."""
def __init__(self, capacity, refill_per_second):
self.capacity = capacity
self.refill_rate = refill_per_second
self.tokens = float(capacity)
self.updated = time.monotonic()
self.lock = threading.Lock()
def allow(self, cost=1.0):
with self.lock:
now = time.monotonic()
self.tokens = min(
self.capacity,
self.tokens + (now - self.updated) * self.refill_rate,
)
self.updated = now
if self.tokens >= cost:
self.tokens -= cost
return True
return False
class CircuitBreaker:
"""Closed, open, half-open state machine."""
def __init__(self, failure_threshold=5, recovery_seconds=30.0):
self.threshold = failure_threshold
self.recovery = recovery_seconds
self.failures = 0
self.opened_at = None
self.state = "closed"
def allow(self):
if self.state == "closed":
return True
if self.state == "open":
if time.monotonic() - self.opened_at >= self.recovery:
self.state = "half-open"
return True
return False
return True # half-open probe
def record_success(self):
self.failures = 0
self.state = "closed"
def record_failure(self):
self.failures += 1
self.opened_at = time.monotonic()
if self.state == "half-open" or self.failures >= self.threshold:
self.state = "open"
Caching, queues, and asynchronous work
Caching decisions dominate user-facing latency. Write-through keeps the cache and store updated together for consistency at the cost of write latency; write-behind acknowledges fast and flushes later for speed at the risk of loss; cache-aside lets the application own invalidation, which is simple to reason about but easy to get subtly wrong. Keys must encode everything that varies the answer โ user, locale, version โ and eviction must be explicit: least-recently-used for general workloads, time-to-live for naturally expiring data, size bounds everywhere. The invalidation question is where interviews go deep; having an answer for stampede protection โ request coalescing or early expiration โ distinguishes seniors.
Queues decouple ingestion from processing, absorb spikes, and provide retry isolation. A producer writes a job; a pool of workers pulls, processes with idempotency keys, and dead-letters failures after a bounded number of retries. Ordering, at-least-once versus exactly-once delivery, and poison-message handling are the follow-ups. Beyond queues, event sourcing stores an append-only log of state changes and derives projections for reads, giving a complete audit trail and time-travel debugging at the cost of schema-evolution complexity. Mention that event sourcing is a specialized tool โ most systems succeed with ordinary CRUD plus a queue.
Microservices edges and the Python stack
An API gateway centralizes routing, authentication, and rate limiting in front of many services; a service registry with health checks lets services find each other without hard-coded hosts. For Python teams, the concrete stack often looks like FastAPI or Django for the edge, Celery or RQ with Redis or RabbitMQ for workers, Postgres for truth, Redis for cache and locks, and Kubernetes for placement. Saying why you chose each piece โ FastAPI for async throughput, Postgres for transactions, Redis for sub-millisecond cache โ beats naming tools without reasons.
Distributed locks deserve honesty: a Redis lock with a TTL is advisory, not a guarantee, unless you accept the failure modes and design idempotency anyway. The mature statement is that locks reduce the frequency of concurrent mistakes but correctness should come from idempotent operations and database-level constraints. That answer reliably impresses because it reflects production reality rather than textbook certainty.
| Component | Failure it addresses | Trade-off you must voice |
|---|---|---|
| Load balancer | Hot spots, single point of failure | Health-check lag versus churn |
| Consistent hash ring | Reshuffling on topology change | Uneven arcs without virtual nodes |
| Token bucket | Burst overload, vendor limits | Burst size versus sustained fairness |
| Circuit breaker | Cascading downstream failure | False opens versus prolonged outages |
| Cache with LRU/TTL | Read latency, database load | Staleness versus hit rate |
| Queue | Spike absorption, decoupling | Delivery guarantees versus throughput |
| Event store | Audit, rebuildable state | Complexity, schema evolution |
Presenting the design end to end
Close the loop the way strong candidates do. Restate requirements. Show the request path. Go deep on two components with sketches and numbers. Walk through failure scenarios โ a node dies, the database saturates, a dependency times out โ and explain what your design does in each. Name what you would monitor: latency percentiles, error rates, queue depth, cache hit rate, breaker state. Offer an evolution path: start with one Postgres and Redis, shard by user when writes demand it, extract the worker tier behind a queue, then split services along the seams that actually hurt. That arc demonstrates engineering judgment, which is the real thing being measured.
Common Mistakes
Drawing architecture before asking about scale and consistency requirements
Fix: Spend the first two minutes on numbers, latency budgets, and read-versus-write balance
Promising exactly-once delivery without explaining the mechanism
Fix: Default to at-least-once plus idempotent consumers; use transactions or idempotency keys
Treating a distributed lock as a correctness guarantee
Fix: Use locks for contention reduction; enforce correctness with constraints and idempotency
Caching without an eviction and invalidation story
Fix: State key structure, TTL or LRU bounds, and stampede protection up front
Best Practices
- Estimate scale with arithmetic out loud before choosing components
- Walk the request path end to end, then deepen the two pieces the interviewer cares about
- Always name the trade-off your choice accepts โ availability versus consistency, speed versus durability
- Close with monitoring metrics and an evolution plan from single-node to sharded
Interview Questions
Q1: Explain the CAP theorem and its practical implications.
A partitioned distributed system cannot simultaneously guarantee linearizable consistency and full availability. In practice you choose per operation: strong consistency with downtime risk, or availability with stale or conflicting reads that need reconciliation.
Q2: How would you design a URL shortener?
A base-62 counter or hash generates keys; a lookup table maps key to URL; a cache holds hot keys; a click log streams analytics asynchronously. Discuss key collision handling and the read-heavy ratio shaping the cache-first design.
Q3: Compare write-through and cache-aside caching.
Write-through updates cache and store atomically on every write โ stronger consistency, higher write latency. Cache-aside lets the application populate the cache on miss โ simpler writes, but invalidation becomes the application's job and staleness is possible.
Q4: How do you keep microservices consistent?
Prefer sagas โ sequences of local transactions with compensating actions โ over distributed two-phase commit. Model each step as an idempotent message, track saga state, and design the UI for eventual consistency.
Q5: What would you monitor in this system?
Latency percentiles at each tier, error and timeout rates by dependency, queue depth and consumer lag, cache hit rate, circuit breaker transitions, saturation metrics like CPU and connection pools, and business-level success rates.
Key Takeaways
- Open with requirements, numbers, and a request-path sketch
- Consistent hashing with virtual nodes limits reshuffling to a single arc
- Token buckets and circuit breakers protect services from bursts and cascades
- Caches need key structure, eviction bounds, and invalidation answers before code
- Queues and event stores decouple and audit; idempotency beats distributed locks
- Close with failure scenarios, monitoring, and an evolution path from simple to sharded