A) CQRS & Event Sourcing
Use this when you need correct writes + many fast read views + the ability to rebuild safely.
What
Concept- CQRS: separate write model (commands) from read model (queries).
- Event Sourcing: source of truth is an append-only event log (immutable events).
- Read models are projections built from events (Redis/Cassandra/Elastic).
Why
Motivation- Writes enforce invariants once; reads are optimized per use-case.
- Independent scaling: write throughput vs read latency.
- Auditability (who did what when) + replay/backfill without risky DB scripts.
Template — how to present CQRS/ES in interviews
Template1) Define the invariants on the write side - authorization, state transitions, limits, uniqueness, ordering 2) Define the event model (append-only) - examples: PostCreated, PostDeleted, FollowCreated, LikeAdded - rules: event schema is “forever” → versioning/upcasters 3) Choose the event log / stream - Kafka/Kinesis/EventStore - partition strategy (postId or userId) + ordering guarantees 4) Build projections (read models) - timeline store (IDs), post view store (metadata), search index (text) - each projection has its own schema optimized for its query 5) Define consistency + freshness SLA - “post visible in feed within 30s p95” - what happens if projection lags (degrade gracefully) 6) Avoid dual-writes - use Outbox pattern or an event store that is the database 7) Rebuild strategy - drop projection → replay events → rebuild → verify → swap
Facebook-like Home Feed — CQRS/ES applied
ExampleWrite path (commands): • POST /post - validate (auth, limits, spam checks) - append PostCreated(postId, authorId, contentRef, ts, visibility) - publish to stream (or write to outbox then publish) Event log: • topic: posts-events (partition by authorId or postId) Projections: 1) UserTimelineProjection - consumes PostCreated + FollowCreated - builds “timeline IDs” per user (fast read) 2) PostViewProjection - stores post metadata by postId (fast hydrate) 3) SearchProjection - indexes post text/tags into Elasticsearch 4) EngagementProjection - counts likes/comments/views (for ranking features) Read path: • GET /feed - fetch postIds (timeline) - batch-hydrate PostViewProjection - rank + rules - return cursor Rebuild: • if ranking features change, replay events to rebuild projections safely.
Common pitfalls
- Dual write (DB + stream) without outbox → mismatched truth
- No event versioning plan → stuck when schema changes
- Not defining freshness SLA → product confusion
- Replay takes too long → need compaction/snapshots/partitioning
Interview one-liner
“We keep writes correct by appending immutable events, then build multiple read-optimized projections; if a read model is wrong, we replay safely instead of risky backfills.”
B) Sagas: orchestration vs choreography
Use sagas for multi-step business flows with retries, timeouts, and compensations.
What
Concept- Saga = distributed transaction implemented as steps + compensations.
- Choreography: services react to events and emit next events.
- Orchestration: a workflow engine drives the sequence, retries, and timeouts.
When to use orchestration
Decision- Long-running flows (minutes → days).
- You need visibility: where is the workflow stuck?
- Complex compensations + global deadlines.
- Exactly-once activities with automatic retries.
Template — saga design checklist
Template1) Identify the workflow goal - “Publish post with media safely and make it visible in feed” 2) Break into steps (each must be idempotent) - step inputs/outputs clearly defined 3) Define compensations per step - what does “undo” mean if step 3 fails? 4) Add timeouts & retry policy - per-step timeout + overall deadline 5) Store saga state - workflow engine state store OR your own (dedupe keys) 6) Observability - step metrics, traces, dead-letter queue, operator runbook
Facebook-like Home Feed — “Create post with video” saga
ExampleGoal: user posts a video; it becomes visible only if processing & safety checks pass. Orchestrated steps: 1) CreateDraftPost (writes PostDraftCreated) 2) UploadVideo (multipart upload) 3) TranscodeRenditions (240p/480p/720p) 4) SafetyScan (policy/moderation) 5) PublishPost (writes PostPublished) 6) FanoutToFollowers (async) Compensations: • If transcode fails → keep draft hidden + retry • If safety fails → mark post blocked + delete media reference (or quarantine) Why orchestration: • Long-running transcode + explicit timeouts + operator visibility.
Common pitfalls
- Steps are not idempotent → duplicates during retries
- No compensation strategy → stuck partial state
- Hidden coupling in choreography at scale
- No global deadline → workflows run forever
Interview one-liner
“We choreograph simple event chains, but anything with long timeouts or compensations goes into an orchestrator so we can observe every step and retry safely.”
C) Search systems & relevancy
Full-text search is about indexing + retrieval + ranking, not just storing text.
Core pieces
Concept- Inverted index: term → posting list (fast retrieval).
- Analyzer pipeline: normalize/tokenize/stem/synonyms.
- Ranking: BM25 + recency + personalization + business rules.
Operational concerns
Ops- Shards + replicas; merge pressure and disk usage.
- Indexing lag SLA: how long until new content is searchable?
- Guard expensive aggregations and high-cardinality fields.
Template — search architecture you can draw
TemplateIndexing pipeline: 1) ingest documents (posts/users/pages) 2) normalize + analyze (language aware) 3) enrich (entities, synonyms, spam signals) 4) index into shards (replicate for read) Query pipeline: 1) parse query (autocomplete/spell/corrections) 2) retrieve candidates (inverted index) 3) rank (BM25 + signals) 4) filter/facets 5) return results + metrics Define SLAs: • indexing lag (p95) • query latency (p95/p99) • relevance metrics (CTR, zero-result rate)
Facebook-like Home Feed — searching posts and people
ExampleIndexing: • PostPublished events → SearchProjector → Elasticsearch • Fields: text, hashtags, authorId, language, created_at, engagement_score Query “travel nepal”: 1) retrieve candidates via inverted index 2) rank by BM25 + recency + engagement + personalization 3) apply filters (language, friends-only content if required) Operational contract: • indexing lag SLA = 30–60s • monitor: zero-result rate, p95 latency, top failed queries
Common pitfalls
- Analyzer mismatch (index vs query) → poor results
- Unbounded dynamic fields → mapping explosion
- Heavy aggs on high-cardinality fields → cluster instability
- No indexing-lag SLA → users can’t find new posts
Interview one-liner
“Search is an index + ranking system: we index asynchronously from events, rank with BM25 + recency + personalization, and we publish an indexing-lag SLA.”
D) Home feeds: fan-out vs fan-in
The classic: fast reads vs write amplification. Hybrid is the common real-world answer.
Fan-out on write
Push- On publish: push postId into each follower’s timeline.
- Pros: fast reads; simple read path.
- Cons: expensive writes; celebrity problem.
Fan-in on read
Pull- On read: merge followees’ timelines at request time.
- Pros: cheap writes; handles celebs naturally.
- Cons: heavy reads; merge+rank cost; caching required.
Template — feed design (hybrid) + ranking pipeline
Template1) Choose feed storage model - fan-out, fan-in, or hybrid 2) Define candidate generation - timeline IDs from Redis/Cassandra - special handling for celebrity authors 3) Hydration strategy - batch fetch posts/media - avoid N+1 calls 4) Ranking pipeline - candidates → features → score → post-ranking rules - enforce safety + diversity + freshness 5) Caching strategy - cache feed head (first N IDs) - refresh-ahead / background recompute 6) Protection mechanisms - rate limits, backpressure workers, hot-key mitigation
Facebook-like Home Feed — practical hybrid feed
ExampleWrite: • Typical users → fan-out into follower timelines (async workers) • Celebrity users → do NOT fan-out to millions; keep in author timeline Read (GET /feed): 1) fetch cached “feed head” IDs for user 2) merge in celebrity timelines (fan-in) if needed 3) batch-hydrate post metadata + media refs 4) rank with features (affinity, engagement, recency) 5) apply rules (no duplicates, diversity, safety) 6) return items + cursor Hot key controls: • worker queues bounded + backpressure • per-celebrity cache of recent posts • cache stampede protection on popular feeds
Common pitfalls
- Celebrity fan-out storms (write amplification)
- N+1 hydration (one call per post)
- Cache stampedes during viral spikes
- Online ranking too expensive (move heavy compute offline)
Interview one-liner
“We use a hybrid feed: fan-out for typical users, fan-in for celebrities, cache the feed head, and rank via a lightweight online model plus rules.”
E) Geo & mapping (H3/Geohash)
Spatial indexing for ‘nearby’ experiences, geo-sharding, and heatmaps.
Template — geo indexing & radius query
TemplateStore: • compute cellId = H3(lat, lon, resolution) • store by cellId prefix (locality) Query radius: 1) compute covering cells (ring/cover) 2) fetch candidates by cellId prefix 3) precise filter using Haversine distance 4) sort/rank by distance and relevance Scale: • shard by region/cell prefix + hash inside region • use multi-resolution for small vs large radii
Facebook-like Home Feed — “Events near you” module
ExampleUse-case: • Show nearby events/posts in the home feed Storage: • event location → H3(r8) cellId Query: • user location → k-ring cells → fetch candidate event IDs • Haversine filter → rank (distance + popularity + personalization) Scaling: • shard by H3 prefix to avoid global scans
Common pitfalls
- Huge radius creates too many cells (needs caps)
- Edge effects near cell borders (cover strategy matters)
- Dense metros skew load (need balancing)
F) Media delivery (ABR + CDN + origin shielding)
How to serve billions of images/videos reliably and cheaply.
Template — media pipeline + delivery checklist
TemplateUpload: 1) multipart upload to object store 2) transcode renditions (ABR) 3) publish manifests + segments Delivery: • CDN caches versioned URLs (long TTL) • origin shield reduces origin hits • signed URLs for private content • range requests for video seeking Measure: • CDN hit rate, startup time, rebuffer %, origin errors, transcode backlog
Facebook-like Home Feed — autoplay videos in feed
ExamplePipeline: • upload → transcode → HLS playlist + 4–6s segments • store segments with versioned URLs (cache safe) Playback: • ABR chooses bitrate per bandwidth • CDN + shield handles viral spikes without crushing origin Cost: • monitor egress spikes and low cache hit rate, pre-warm only truly hot videos
Common pitfalls
- Bad cache keys (low CDN hit rate)
- Missing CORS/range breaks streaming/seeking
- Segment duration extremes harm QoE
G) Payments, ledger, finops
Correct money movement requires idempotency + immutable ledger + reconciliation.
Template — payments correctness story
Template1) Make charges/refunds idempotent - Idempotency-Key + unique constraints 2) Record effects in immutable double-entry ledger - debit/credit lines are append-only 3) Materialize balances for reads - do not mutate ledger rows 4) Reconcile - nightly compare ledger totals to PSP/bank reports - exceptions queue + runbooks 5) FinOps hooks - tag costs, budgets, anomaly detection (egress, hot shards)
Facebook-like Home Feed — ads billing + ledger
ExampleAds billing: • impressions/clicks → aggregate → charge advertiser (idempotent) Ledger: • debit advertiser / credit platform revenue • balances are materialized views Recon: • nightly compare to payment provider reports • mismatches go to ops queue FinOps: • track major costs: CDN egress, storage, ML inference • alert on sudden egress spikes during viral events
Common pitfalls
- Mutable ledger rows (audit breaks)
- No idempotency → duplicate charges
- Recon exists but not operationalized (no review)
H) Feature stores & realtime ML
Make online ranking consistent with training and safe to roll out.
Template — feature store + inference + safety
TemplateDefinitions: • Feature store = registry + offline store + online store • Goal: same features in training and serving, with freshness SLAs Flow: 1) offline compute (warehouse/lake) 2) online serve (KV/Redis) with TTL + fast lookup 3) online inference: candidates → feature fetch → score → rules Safety: • shadow traffic, canary cohorts, rollback switch • drift monitoring (input/output), latency SLO monitoring
Facebook-like Home Feed — ranking service with feature store
ExampleRanking: • candidates → fetch features (affinity, engagement, freshness, author quality) • online KV returns < 10ms p95 • model score + rule layer Freshness: • some features near-real-time (recent interactions) • others daily batch (author quality) Rollout: • shadow 5% traffic to new model • canary 1% cohort • rollback if CTR drops or latency breaches
Common pitfalls
- Training/serving skew (different feature logic)
- Stale features (no TTL or freshness SLAs)
- No rollback (bad model hurts metrics)
Glue patterns (how these combine)
The interviewer loves when you connect patterns into one coherent story.
Template — “glue story” you can say in 30 seconds
TemplateStructure your explanation like this: 1) Source of truth (events or DB) 2) Derived views (projections for fast reads) 3) Async pipelines (fan-out, indexing, counters) 4) Serving layer (caches/CDN, pagination) 5) Ranking layer (features + model + rules) 6) Safety/ops (SLAs, retries, monitoring, rollback) One-line summary: • “Writes are correct, reads are fast, pipelines are async, and rollouts are safe.”
Facebook-like Home Feed — glue story in a clean sequence
Example1) Post/like/follow events are appended (audit + replay). 2) Projections build timelines, post views, search index, and counters. 3) Feed read uses timeline IDs → hydrate → rank → rules. 4) Celebrities handled via fan-in; typical users via fan-out. 5) Media served via CDN with ABR; viral spikes protected by caches/shields. 6) Ranking uses feature store and safe rollout (shadow/canary + rollback).
Quick sound bites
Short lines you can memorize and reuse in any system design interview.
Sound bites (copy/paste)
TemplateCQRS/ES: Writes append events; reads are projections; replay fixes bad projections safely.
Sagas: Choreograph simple flows; orchestrate complex ones for timeouts/compensations/visibility.
Search: Inverted index + BM25 + recency; indexing lag is an explicit SLA.
Feeds: Hybrid feed: fan-out for most, fan-in for celebs; cache the feed head.
Geo: Index by H3; expand ring cells then Haversine-filter for precision.
Media: HLS/DASH on CDN with origin shield; versioned URLs and signed access.
Payments: Idempotency keys + immutable double-entry ledger + nightly reconciliation.
Features: One feature definition for training/serving; online KV with freshness SLAs; safe rollouts.Facebook-like Home Feed — 10-second wrap-up
Example“For the Home Feed, we write events, build projections for timelines and search, hydrate in batches, rank with a feature store, and serve media via CDN—using hybrid fan-out/fan-in to handle celebrities and viral spikes safely.”