System Design Interview Questions
5 questions for junior, mid-level and senior System Design interviews, with model answers, code examples and common mistakes. Answer each one out loud first, then reveal the answer.
DNS Resolution When You Type a URL
// interview question
Walk me through what happens when you type a URL and press Enter, focusing specifically on the DNS resolution process.
Sample answer
When you type 'example.com' and press Enter, the browser first checks its own DNS cache. If there is no cached result, it asks the operating system's stub resolver, which checks the OS-level cache (and on Linux, potentially systemd-resolved or nscd). If still unresolved, the query goes to your configured recursive resolver, usually provided by your ISP or a public resolver like 8.8.8.8 or 1.1.1.1. The recursive resolver checks its own cache, and if it has nothing, it starts the iterative resolution process: first it asks a root name server (one of 13 root server clusters, like a.root-servers.net) which responds with the TLD name servers for '.com'. Then it asks a '.com' TLD server, which responds with the authoritative name servers for 'example.com'. Finally, it asks the authoritative server, which returns the actual IP address (e.g., 93.184.216.34). The recursive resolver caches the answer according to the TTL and returns it to your machine. The entire process, when fully uncached, involves 4 network round-trips but typically completes in 20-120ms. Most queries hit a cache at some level and resolve in under 5ms.
Why this matters
DNS is the entry point for virtually every internet interaction, yet many developers treat it as a black box. This question separates candidates who understand the layered architecture of the internet from those who just know 'DNS translates names to IPs.' It also opens the door to discussions about caching behavior, TTLs, security (DNS spoofing, DNSSEC), and how DNS-based load balancing and failover work. For a junior candidate, the interviewer wants to see awareness of the recursive vs. iterative resolution distinction and the caching hierarchy.
Code examples
Tracing DNS resolution step by step
# Full iterative trace from root servers down
# This shows every step the recursive resolver takes
dig +trace example.com
# Output (simplified):
# . IN NS a.root-servers.net. <- Step 1: Root
# com. IN NS a.gtld-servers.net. <- Step 2: TLD
# example.com. IN NS ns1.example.com. <- Step 3: Authoritative
# example.com. IN A 93.184.216.34 <- Step 4: Answer
# Check which resolver you are using
dig whoami.akamai.net
# See the TTL (time-to-live) for a domain
# The TTL tells caches how long to keep this answer
dig example.com | grep -E 'ANSWER SECTION' -A 2
# example.com. 3600 IN A 93.184.216.34
# ^^ TTL = 3600 seconds (1 hour)
# Query a specific DNS server directly
dig @8.8.8.8 example.com
# Check all the DNS record types for a domain
dig example.com ANY +noall +answerSimulating the DNS resolution hierarchy
import dns.resolver # pip install dnspython
import time
def trace_dns(domain: str):
"""Walk through DNS resolution and measure timing."""
print(f"Resolving: {domain}\n")
# Step 1: Check what the default resolver returns
start = time.time()
answers = dns.resolver.resolve(domain, 'A')
elapsed = (time.time() - start) * 1000
for rdata in answers:
print(f"IP Address: {rdata.address}")
print(f"Resolution time: {elapsed:.1f}ms")
print(f"TTL: {answers.rrset.ttl} seconds")
# Step 2: Check NS records (who is authoritative)
ns_answers = dns.resolver.resolve(domain, 'NS')
print(f"\nAuthoritative name servers:")
for ns in ns_answers:
print(f" {ns.target}")
# Step 3: Resolve again to show caching effect
start = time.time()
dns.resolver.resolve(domain, 'A')
cached_elapsed = (time.time() - start) * 1000
print(f"\nSecond query (cached): {cached_elapsed:.1f}ms")
trace_dns("example.com")
# Typical output:
# IP Address: 93.184.216.34
# Resolution time: 45.2ms
# TTL: 3600 seconds
#
# Authoritative name servers:
# ns1.example.com.
# ns2.example.com.
#
# Second query (cached): 0.3msDNS resolution flow diagram
Browser Cache -> OS Cache -> Recursive Resolver Cache -> [Full Resolution]
Full Resolution (iterative, only when all caches miss):
Your Machine Recursive Resolver Root Server
----------- ------------------ -----------
"example.com?" -----> checks cache... MISS
"example.com?" ---------> "Go ask .com TLD"
(referral)
.com TLD Server
---------------
"example.com?" ---------> "Go ask ns1.example.com"
(referral)
Authoritative Server
--------------------
"example.com?" ---------> "93.184.216.34, TTL=3600"
(final answer)
Caches answer (TTL=3600)
<---- 93.184.216.34 --
Caches answer
Connects to 93.184.216.34Common mistakes to avoid
- Describing DNS as a single lookup rather than a multi-step hierarchical process
- Not mentioning caching at any level, which is what makes DNS fast in practice
- Confusing the recursive resolver with the authoritative server
- Forgetting that DNS uses UDP by default (port 53), not TCP, for standard queries
- Skipping the root server step and jumping straight to the authoritative server
- Not knowing that there are 13 root server clusters (not 13 individual machines)
Likely follow-ups
- What happens if the authoritative DNS server is down? How does redundancy work in DNS?
- How does DNS-based load balancing work, and what are its limitations?
- What is a TTL, and what are the tradeoffs of setting it very low vs. very high?
- What is DNSSEC, and what problem does it solve?
- How does DNS prefetching in browsers improve page load performance?
Answer out loud first, then check yourself against the model answer.
Instant Credit Card Validation
// interview question
How does a credit card form validate numbers instantly, before even contacting the bank?
Sample answer
Credit card numbers follow a mathematical pattern called the Luhn algorithm (also known as the mod-10 check). The form runs this algorithm entirely on the client side, in the browser, with zero network calls. Starting from the rightmost digit, you double every second digit. If doubling produces a number greater than 9, subtract 9. Then sum all the digits. If the total is divisible by 10, the number is structurally valid. This catches roughly 99% of accidental typos instantly. The first 1-6 digits (the BIN or IIN range) also identify the card network: Visa starts with 4, Mastercard with 51-55 or 2221-2720, Amex with 34 or 37. So the form can show the correct card logo before the user finishes typing.
Why this matters
This question tests whether candidates understand that not every validation requires a server round-trip. The Luhn check is a classic example of a checksum that provides instant feedback at minimal cost. It also opens the door to discussing client-side vs. server-side validation, UX responsiveness, and the layered approach to input validation (format check, then network check, then authorization). Interviewers want to see that you think about reducing latency by doing cheap checks first before expensive ones.
Code examples
Luhn algorithm implementation
function isValidCardNumber(number) {
const digits = number.replace(/\s/g, '').split('').reverse();
let sum = 0;
for (let i = 0; i < digits.length; i++) {
let digit = parseInt(digits[i], 10);
// Double every second digit (odd index in reversed array)
if (i % 2 === 1) {
digit *= 2;
if (digit > 9) digit -= 9;
}
sum += digit;
}
return sum % 10 === 0;
}
// Identify card network from first digits
function getCardNetwork(number) {
const cleaned = number.replace(/\s/g, '');
if (/^4/.test(cleaned)) return 'Visa';
if (/^5[1-5]/.test(cleaned)) return 'Mastercard';
if (/^3[47]/.test(cleaned)) return 'Amex';
if (/^6011/.test(cleaned)) return 'Discover';
return 'Unknown';
}
console.log(isValidCardNumber('4539 1488 0343 6467')); // true
console.log(getCardNetwork('4539 1488 0343 6467')); // VisaLuhn check in Python
def luhn_check(card_number: str) -> bool:
digits = [int(d) for d in card_number.replace(' ', '')][::-1]
total = 0
for i, digit in enumerate(digits):
if i % 2 == 1:
digit *= 2
if digit > 9:
digit -= 9
total += digit
return total % 10 == 0
# Valid test number
print(luhn_check('4539 1488 0343 6467')) # True
# One digit off
print(luhn_check('4539 1488 0343 6468')) # FalseCommon mistakes to avoid
- Saying the form contacts the bank or payment processor for every keystroke
- Not knowing that the card number format itself carries information like the network and issuer
- Forgetting to mention that client-side validation is a UX optimization, not a security measure, and server-side checks are still required
- Overlooking that the Luhn algorithm only catches accidental errors, not intentional fraud
Likely follow-ups
- What happens after the Luhn check passes and the user submits the form? Walk me through the full authorization flow.
- Why is client-side validation alone never sufficient for security?
- How would you validate an email address instantly without sending a verification email?
- What other checksums or check digits are used in everyday systems (ISBNs, routing numbers, etc.)?
Answer out loud first, then check yourself against the model answer.
Username Availability with Bloom Filters
// interview question
Explain how you'd check username availability for a service with billions of users without hitting the database on every keystroke.
Sample answer
Use a Bloom filter as the first layer. A Bloom filter is a space-efficient probabilistic data structure that can tell you with certainty that a username is available (not in the set) or with high probability that it is taken. You load all existing usernames into the filter at startup. When a user types a username, you check the Bloom filter first. If the filter says 'not present,' the username is definitely available and you skip the database entirely. If the filter says 'possibly present,' you then query the database to confirm. For billions of usernames, a Bloom filter with a 1% false positive rate needs roughly 1.2 GB of memory, which fits comfortably on a single server. This eliminates the vast majority of database lookups.
Why this matters
This question tests whether candidates can identify the right data structure for a probabilistic membership check at scale. Bloom filters appear in many production systems: Chrome uses one to check malicious URLs, databases use them to skip unnecessary disk reads, and CDNs use them for cache filtering. The interviewer wants to see that you understand the false-positive tradeoff, can reason about memory usage, and know when an approximate answer is good enough to avoid an expensive exact lookup.
Code examples
Simple Bloom filter implementation
import hashlib
import math
class BloomFilter:
def __init__(self, expected_items, false_positive_rate=0.01):
# Calculate optimal size and hash count
self.size = self._optimal_size(expected_items, false_positive_rate)
self.hash_count = self._optimal_hashes(self.size, expected_items)
self.bit_array = bytearray(self.size // 8 + 1)
print(f"Filter size: {self.size / 8 / 1024 / 1024:.1f} MB")
print(f"Hash functions: {self.hash_count}")
def _optimal_size(self, n, p):
return int(-n * math.log(p) / (math.log(2) ** 2))
def _optimal_hashes(self, m, n):
return int((m / n) * math.log(2))
def _get_hashes(self, item):
hashes = []
for i in range(self.hash_count):
h = hashlib.sha256(f"{item}:{i}".encode()).hexdigest()
hashes.append(int(h, 16) % self.size)
return hashes
def add(self, item):
for pos in self._get_hashes(item):
self.bit_array[pos // 8] |= (1 << (pos % 8))
def might_contain(self, item):
return all(
self.bit_array[pos // 8] & (1 << (pos % 8))
for pos in self._get_hashes(item)
)
# For 1 billion usernames at 1% false positive rate
bf = BloomFilter(expected_items=1_000_000_000, false_positive_rate=0.01)
# Output: Filter size: ~1144.5 MB, Hash functions: 7
bf.add("alice")
bf.add("bob")
print(bf.might_contain("alice")) # True (definitely added)
print(bf.might_contain("charlie")) # False (definitely NOT added)
print(bf.might_contain("bob")) # True (definitely added)Username availability API with Bloom filter layer
from fastapi import FastAPI
import redis
app = FastAPI()
r = redis.Redis()
# Redis has built-in Bloom filter support via RedisBloom module
# BF.RESERVE usernames 0.01 1000000000
# BF.ADD usernames "alice"
@app.get("/check-username/{username}")
async def check_username(username: str):
username = username.lower().strip()
# Layer 1: format validation (instant, no I/O)
if len(username) < 3 or len(username) > 30:
return {"available": False, "reason": "invalid_length"}
# Layer 2: Bloom filter check (sub-millisecond, in-memory)
possibly_taken = r.execute_command("BF.EXISTS", "usernames", username)
if not possibly_taken:
# Bloom filter says NO -> definitely available
return {"available": True}
# Layer 3: database confirmation (only for Bloom positives)
# This path is hit for ~1% false positives + actual taken names
taken = await db.check_username_exists(username)
return {"available": not taken}Common mistakes to avoid
- Saying you would query the database on every keystroke for real-time feedback
- Confusing false positives and false negatives: Bloom filters never produce false negatives, only false positives
- Not knowing how to estimate the memory required for a given number of items and false positive rate
- Forgetting that Bloom filters do not support deletion without switching to a counting variant
- Proposing a simple HashSet, which would require far more memory for billions of entries
Likely follow-ups
- What happens when a new user registers? How do you keep the Bloom filter in sync?
- Can you remove an element from a Bloom filter? If not, what alternatives exist?
- How would you handle the filter across multiple application servers?
- What is a counting Bloom filter, and when would you use one instead?
- How does a cuckoo filter compare to a Bloom filter for this use case?
Answer out loud first, then check yourself against the model answer.
CDN Image Delivery Under 50ms
// interview question
Explain how a CDN serves images to users worldwide in under 50ms.
Sample answer
A CDN (Content Delivery Network) places copies of your images on hundreds of edge servers distributed across the globe. When a user requests an image, DNS routes them to the nearest edge server (often called a Point of Presence or PoP), typically within 20-50km. If that edge server already has the image cached, it serves it directly from memory or local SSD, which takes 1-5ms of server processing plus the network round-trip to the nearby PoP, totaling well under 50ms. If the edge does not have the image (a cache miss), it fetches from a regional mid-tier cache or the origin server, caches the response, and then serves it. The key is that after the first request, all subsequent users in that region get the cached copy. CDNs also use anycast routing, where multiple servers share the same IP address and the network layer routes packets to the closest one, and persistent TCP/TLS connections between PoPs to minimize connection setup overhead.
Why this matters
This question tests whether candidates understand the physical constraints of network latency and how CDNs work around them by moving data closer to users. Light in fiber travels at roughly 200,000 km/s, so a round-trip from New York to London (11,000 km) takes at least 55ms just from physics. No amount of server optimization can beat the speed of light, which is why geographic distribution is the only solution for global sub-50ms delivery. Interviewers want to see that you grasp the caching hierarchy, cache invalidation challenges, and the tradeoffs between freshness and speed.
Code examples
CDN caching hierarchy and request flow
User in Tokyo requests: https://cdn.example.com/images/hero.jpg
1. DNS Resolution (anycast)
-> DNS returns IP 198.51.100.1
-> Anycast routes to nearest PoP: Tokyo edge server
2. Edge Server (Tokyo PoP)
Cache HIT? -> Serve from memory/SSD (1-5ms processing)
Total latency: ~10-20ms (nearby network hop)
Cache MISS? -> Check regional mid-tier cache
3. Mid-Tier Cache (Asia-Pacific region, e.g. Singapore)
Cache HIT? -> Return to Tokyo edge, cache locally, serve user
Added latency: ~30-60ms for regional hop
Cache MISS? -> Fetch from origin
4. Origin Server (US-East)
-> Serves the image
-> Mid-tier caches it (TTL: 24 hours)
-> Edge caches it (TTL: 1 hour)
-> User gets the image
Total first-request latency: ~200-300ms
All subsequent Tokyo requests: ~10-20msNginx edge cache configuration
# Simplified CDN edge server config
proxy_cache_path /var/cache/cdn levels=1:2
keys_zone=images:100m
max_size=50g
inactive=24h
use_temp_path=off;
server {
listen 443 ssl http2;
server_name cdn.example.com;
location /images/ {
proxy_cache images;
proxy_cache_valid 200 1h;
proxy_cache_valid 404 1m;
# Serve stale content while revalidating in background
proxy_cache_use_stale updating error timeout;
proxy_cache_background_update on;
# Add cache status header for debugging
add_header X-Cache-Status $upstream_cache_status;
add_header Cache-Control "public, max-age=3600";
# Conditional requests to origin
proxy_cache_revalidate on;
proxy_pass http://origin-servers;
}
}Inspect CDN cache headers
# Check if an image is served from cache
curl -sI https://cdn.example.com/images/hero.jpg | grep -E '(X-Cache|Age|Cache-Control|CF-Cache)'
# Example output:
# X-Cache: HIT
# Age: 3542 <- seconds since edge cached it
# Cache-Control: public, max-age=3600
# CF-Cache-Status: HIT <- Cloudflare-specific header
# Purge a specific cached image (Cloudflare API example)
curl -X POST "https://api.cloudflare.com/client/v4/zones/{zone_id}/purge_cache" \
-H "Authorization: Bearer $CF_TOKEN" \
-H "Content-Type: application/json" \
--data '{"files":["https://cdn.example.com/images/hero.jpg"]}'Common mistakes to avoid
- Not understanding that network latency is bounded by the speed of light, so geographic proximity is the primary optimization
- Confusing CDN caching with browser caching or application-level caching
- Ignoring cache invalidation, which is the hardest part of running a CDN
- Thinking all requests hit the origin server and the CDN just provides 'faster pipes'
- Forgetting about cache warming and the cold-start problem when deploying to new PoPs
Likely follow-ups
- How do you invalidate or purge cached content across all edge servers when the original image changes?
- What is the difference between push-based and pull-based CDN strategies?
- How would you handle personalized or user-specific content that cannot be cached at the edge?
- What role does HTTP/2 and HTTP/3 (QUIC) play in reducing latency for CDN-served content?
- How do you decide on TTL values for different types of content?
Answer out loud first, then check yourself against the model answer.
Search Autocomplete System Design
// interview question
Design the backend for a search autocomplete system that returns suggestions within 100ms as the user types.
Sample answer
The core data structure is a trie (prefix tree) that stores popular search queries. Each node represents a character, and nodes are annotated with frequency scores so you can return the top-k suggestions for any prefix. To meet the 100ms target at scale, you partition the trie across multiple servers by prefix range (a-f on server 1, g-m on server 2, etc.) and keep the working set in memory. A separate offline pipeline aggregates search logs, computes query frequencies, and rebuilds the trie periodically. When the user types, the frontend debounces keystrokes (typically 150-300ms delay), sends the prefix to an API gateway, which routes to the correct shard. The shard walks the trie to the prefix node and returns the top-k results. A CDN or edge cache sits in front for the most common prefixes, since queries like 'how' or 'what' are nearly identical across users.
Why this matters
Autocomplete is one of the most common system design interview questions because it touches on data structures, caching, ranking, and latency budgets all at once. A strong answer addresses the full pipeline: data collection, offline processing, serving infrastructure, and client-side optimizations. Senior candidates should discuss how to handle personalization, freshness of trending queries, and multi-language support. The interviewer is looking for the ability to make tradeoffs between serving speed and data freshness.
Code examples
Trie-based autocomplete with frequency ranking
from collections import defaultdict
import heapq
class TrieNode:
def __init__(self):
self.children = {}
self.is_end = False
self.frequency = 0
# Cache top-k results at each node to avoid recomputation
self.top_suggestions = []
class AutocompleteService:
def __init__(self, top_k=5):
self.root = TrieNode()
self.top_k = top_k
def insert(self, query: str, frequency: int):
node = self.root
for char in query.lower():
if char not in node.children:
node.children[char] = TrieNode()
node = node.children[char]
node.is_end = True
node.frequency = frequency
def _collect_suggestions(self, node, prefix, results):
if node.is_end:
results.append((node.frequency, prefix))
for char, child in node.children.items():
self._collect_suggestions(child, prefix + char, results)
def build_cache(self):
"""Pre-compute top-k suggestions at every node."""
self._build_cache_recursive(self.root, "")
def _build_cache_recursive(self, node, prefix):
results = []
self._collect_suggestions(node, prefix, results)
# Keep top-k by frequency
node.top_suggestions = [
query for freq, query
in heapq.nlargest(self.top_k, results)
]
for char, child in node.children.items():
self._build_cache_recursive(child, prefix + char)
def search(self, prefix: str) -> list:
node = self.root
for char in prefix.lower():
if char not in node.children:
return []
node = node.children[char]
# O(1) lookup thanks to pre-computed cache
return node.top_suggestions
# Build the trie from aggregated search logs
service = AutocompleteService(top_k=5)
queries = [
("how to learn python", 50000),
("how to learn javascript", 45000),
("how to learn go", 30000),
("how to cook rice", 28000),
("how are you", 90000),
("holiday deals", 15000),
]
for query, freq in queries:
service.insert(query, freq)
service.build_cache()
print(service.search("how to l"))
# ['how to learn python', 'how to learn javascript', 'how to learn go']System architecture overview
# Autocomplete system components
data_pipeline:
input: search_query_logs (Kafka topic)
processing: Apache Spark job (runs every 15 minutes)
steps:
- aggregate query counts over rolling 7-day window
- filter offensive or low-quality queries
- weight recent queries higher (time decay)
- merge with curated trending topics
output: ranked_queries.json -> pushed to trie servers
serving_layer:
edge_cache:
technology: CloudFront / Fastly
cache_key: first 3 characters of prefix
ttl: 5 minutes
hit_rate: ~60% of all requests
api_gateway:
rate_limit: 10 requests/sec per user
routes_to: trie shard based on first character
trie_servers:
instances: 6 shards (partitioned by prefix range)
memory: 16 GB per shard
data: in-memory trie with pre-computed top-k
refresh: hot-swap new trie every 15 minutes
client_side:
debounce: 200ms between keystrokes
min_prefix_length: 2 characters
local_cache: LRU cache of last 50 prefix results
fallback: show recent user searches if backend is slowCommon mistakes to avoid
- Proposing a simple SQL LIKE query against a database, which cannot meet the latency requirement at scale
- Forgetting client-side optimizations like debouncing and local caching, which reduce backend load significantly
- Not discussing how the trie data stays fresh or how you handle trending queries
- Ignoring the ranking component and treating all prefix matches as equally relevant
- Overcomplicating the design with ML ranking models before addressing the basic infrastructure
- Not mentioning how to partition or replicate the trie when it outgrows a single server
Likely follow-ups
- How would you handle trending or breaking-news queries that spike suddenly?
- How do you personalize autocomplete results per user without adding latency?
- What happens if one of the trie shards goes down? How do you ensure availability?
- How would you filter out offensive or inappropriate suggestions?
- How does the system handle multiple languages and character sets?
Answer out loud first, then check yourself against the model answer.
More interview topics
Also worth your time on this topic
How Netflix Ships a Third of the Internet: The CDN They Had to Build
At its 2015 peak Netflix was 37% of North American downstream traffic, and almost none of it came from a commercial CDN. Open Connect is a cache hierarchy built on one asymmetry: Netflix knows tonight what people will watch tomorrow. Here is how the appliances, the nightly fill, the BGP steering and the 800 Gb/s FreeBSD boxes fit together, a runnable comparison of push fill against pull-through caching, and what it teaches anyone running a cache.
Back-of-the-Envelope Estimation Quiz
The napkin-math skill that makes or breaks a system design interview: turning users into QPS, data into storage, traffic into bandwidth, and knowing the latency numbers every engineer should have memorised.
16-22 minutes
Redis Caching Strategies for Scalable Applications
Implement production-ready caching patterns with Redis to dramatically improve application performance and scalability.
70 minutes