Guide / System design Most asked
Design: typeahead, crawler, video streaming, job scheduler, metrics
Five more frequently asked designs in condensed form: autocomplete, web crawler, video streaming pipeline, distributed job scheduler and a metrics/logging platform.
Each design follows the same frame: requirements → estimates → architecture → deep dive → failure modes → follow-ups.
Fundamentals (the five designs)#
1. Typeahead / autocomplete#
Requirements: suggestions for a prefix within ~100 ms, top 5–10 by popularity/personalisation, freshness within hours. Estimate: 10M DAU × 10 searches × ~4 keystroke requests ≈ 4B/day ≈ 46K QPS (peak ~150K); the dataset (top queries) fits in memory.
Design: precompute the top-K completions per prefix.
- Trie where each node stores its top-K completions (space heavy but O(prefix length) lookup), or a prefix → top-K map in Redis/in-memory built offline.
- Pipeline: search logs → Kafka → stream/batch aggregation (counts per query, time-decayed) → build prefix index nightly (and incrementally for trends) → publish a new versioned snapshot and swap atomically.
- Serving: browser debounces (wait ~100–150 ms of no typing), caches responses, and the CDN/edge caches popular prefixes; servers hold the index in memory, sharded by prefix range or replicated per region.
- Ranking: frequency × recency, plus personalisation and filtering (blocklist, safe search, deduplicate near-duplicates).
- Follow-ups: typos (edit-distance/fuzzy via n-grams), multi-language, cold-start for new queries (blend with trending), privacy (do not suggest other users’ private queries; threshold on distinct users).
2. Web crawler#
Requirements: crawl billions of pages, politeness (robots.txt, per-host rate), freshness (recrawl by change rate), dedupe, extensible parsers. Estimate: 1B pages/month ≈ 400 pages/s; at 100 KB each ≈ 100 TB/month raw.
Design:
Seed URLs → URL frontier (priority + politeness queues per host) → fetchers (DNS cache, robots cache)
→ content store (S3) → parser/extractor → new URLs → dedupe (Bloom filter / URL hash set) → back to frontier
└→ content fingerprint (SimHash) → duplicate/near-duplicate detection → indexer
- Frontier: front queues by priority (page rank, change frequency), back queues one per host to enforce politeness delay (e.g. 1 request/s/host); a scheduler picks the next ready host.
- Dedupe: URL normalisation + Bloom filter for “seen”; content hash for exact duplicates; SimHash for near-duplicates.
- Traps: infinite calendars and session IDs: limit depth per site, URL pattern budgets.
- Distributed: partition hosts across crawler nodes by consistent hashing of hostname (keeps politeness local), checkpoint frontier state, retry with backoff, respect
Crawl-delay. - Recrawl: adaptive intervals from observed change rate (ETag/Last-Modified conditional requests).
3. Video streaming (YouTube/Netflix)#
Requirements: upload videos, watch with adaptive quality worldwide, search, recommendations (out of scope here). Key idea: separate the upload/transcode pipeline from the delivery path.
Upload: client uploads in chunks via presigned multipart URLs to object storage → event → transcoding DAG (split into segments, encode in parallel to multiple resolutions/bitrates and codecs, generate thumbnails, subtitles, content moderation) → store HLS/DASH segments and manifests → metadata DB updated, CDN invalidated/warmed.
Playback: player fetches a manifest listing renditions, then adaptive bitrate (ABR) picks the next segment’s quality from measured bandwidth and buffer; segments are small (2–6 s) static files served from a CDN; popular content is cached at edge, long tail from origin shield. DRM (Widevine/FairPlay) for premium content.
Numbers: a 1-hour HD video at multiple renditions can total several GB; egress dominates cost, so peering with ISPs and edge appliances (Netflix Open Connect) matter. View counts: buffered counters aggregated asynchronously (approximate). Metadata in a sharded relational/KV store; search in Elasticsearch.
4. Distributed job scheduler (cron at scale)#
Requirements: schedule one-off and recurring jobs (millions), execute reliably at roughly the right time, retries, no double execution, observability.
Design: a jobs table (job_id, schedule, next_run_at, status, payload), scheduler nodes partition jobs (by hash or time bucket) and poll due jobs (WHERE next_run_at <= now() AND status='SCHEDULED'), claiming them with FOR UPDATE SKIP LOCKED or a lease (locked_until), then enqueue to a work queue; workers pull, execute and ack; on completion compute next_run_at. Execution is at-least-once, so jobs must be idempotent (idempotency key = job ID + scheduled time). Heartbeats extend leases; a reaper re-queues jobs whose lease expired (worker died). Leader election (ZooKeeper/etcd/DB lease) for singleton scheduler duties. Add priorities, rate limits per tenant, timeouts, retry policies with backoff and a DLQ, and missed-run policies (skip, run once, catch up). For long workflows use Temporal/Airflow.
5. Metrics / logging platform#
Requirements: ingest millions of data points/s, query dashboards in seconds, alerting, retention tiers. Design:
Agents (per host) → regional collectors → Kafka → stream processors (aggregate, downsample, enrich)
→ hot store (time-series DB: Prometheus/VictoriaMetrics/ClickHouse) 24h–30d at full resolution
→ cold store (Parquet on S3) with downsampled data for months/years
Query service → caches; Alert engine evaluates rules on a schedule/stream → notification system
Main dangers: high cardinality labels (user_id as a label explodes series count: limit and drop), write amplification, hot partitions, unbounded queries (limit time range and series). Logs: structured JSON, index only selected fields, sample debug logs, tier retention. Use delta encoding and Gorilla-style compression for time series. Make agents buffer locally and apply backpressure.
Most asked questions#
1. Typeahead: trie or hash map? Trie with precomputed top-K per node, or prefix-keyed map; both built offline and served from memory; choose by memory and update simplicity.
2. How does a crawler stay polite and avoid duplicates? Per-host queues with delay and robots.txt; URL Bloom filter, content hashes and SimHash.
3. How does adaptive bitrate streaming work? Video split into short segments in several qualities; the player picks each segment’s quality from bandwidth and buffer.
4. How do you ensure a scheduled job runs once? Claim with a lease or SKIP LOCKED, execute at-least-once with idempotent jobs and unique run IDs.
5. How do you control metrics cardinality? Limit label sets, reject user-level labels, aggregate at ingestion, quotas per team.
Senior-level questions#
1. “Suggestions suddenly show an offensive or stale query.” Add blocklists and review pipeline, time-decay for trending, rollback of index snapshots (versioned), and monitoring for anomalous top-K shifts.
2. “Crawler gets blocked by sites.” Honour limits, rotate legitimate user agents/IPs responsibly, use caching and conditional requests, request API access; never evade explicit bans.
3. “Transcoding queue is backed up after a viral upload day.” Prioritise by popularity and creator tier, produce a fast low-resolution rendition first, scale workers (spot instances), split work in segments, and apply backpressure on non-critical renditions.
4. “A scheduler node dies mid-run.” Lease expiry returns the job to the queue; idempotent execution makes the retry safe; heartbeats distinguish slow from dead.
5. “Alerts fire late during peak.” Backlogged ingestion; separate the alerting path with its own lightweight stream, prioritise alert queries, protect with admission control.
Quiz#
1. Why debounce typeahead requests?
It avoids sending a request per keystroke, reducing load and wasted work while keeping suggestions responsive.
2. What does SimHash detect?
Near-duplicate documents via similarity of fingerprint bits (small Hamming distance).
3. Why short HLS segments?
They let the player switch quality quickly and start playback sooner, while remaining cacheable static files.
4. How do multiple schedulers avoid claiming the same job?
Atomic claim with FOR UPDATE SKIP LOCKED or a conditional update setting locked_until/owner.
5. Why is user_id a bad metric label?
Each distinct value creates a new time series, causing cardinality explosion, memory and cost blowup.