HTHyperTransformer AI

Study cards › System Design

System DesignInterview questions and answers

← Topics1 / 100
1 / 100 viewed
Question

What is SOLID?

Answer

SOLID is five OOP principles for maintainable software: Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, and Dependency Inversion. Together they push you toward small, focused, swappable, and testable components — the foundation of clean object-oriented design.

Question

Single Responsibility Principle?

Answer

A class/module should have exactly one reason to change — one job, one stakeholder. If you find yourself describing a class with 'and' (handles users AND sends emails), it's doing too much. Split it. Smaller, focused units are easier to test, change, and reuse.

Question

Open/Closed Principle?

Answer

Software should be open for extension but closed for modification. You should be able to add new behavior without editing existing stable code. Achieved via interfaces and polymorphism — add a new implementation instead of branching the original with if/else for every new case.

Question

Liskov Substitution Principle?

Answer

Subtypes must be substitutable for their base type without breaking behavior. If Square extends Rectangle but disallows different width/height, code that worked on Rectangle breaks on Square. Inheritance must preserve contracts, not just signatures.

Question

Interface Segregation Principle?

Answer

Many small client-specific interfaces beat one fat general-purpose one. Consumers shouldn't depend on methods they don't use. Splitting interfaces reduces the surface area each component must care about and makes them easier to mock and test.

Question

Dependency Inversion Principle?

Answer

Depend on abstractions, not concretions. High-level modules (business logic) shouldn't know about low-level details (which DB, which HTTP client). Defining an interface that both depend on inverts the direction of dependency, making the system flexible and testable.

Question

What is the Singleton pattern?

Answer

Ensures a class has exactly one instance with a global access point. Useful for things like a logger or config registry — but easy to abuse. Singletons are essentially hidden global state, which makes testing and parallel execution harder. Often DI containers are a better answer.

Question

What is the Factory pattern?

Answer

A Factory encapsulates object creation — callers ask for an object by intent, and the factory picks the concrete class. Useful when construction is complex, the right subclass depends on input, or you want to hide implementation choices from consumers.

Question

What is the Strategy pattern?

Answer

Strategy encapsulates interchangeable algorithms behind a common interface — like swapping sorting algorithms or payment processors at runtime. Lets you pick behavior dynamically without long if/else branches scattered through the code.

Question

What is the Observer pattern?

Answer

An object (subject) notifies a list of subscribers (observers) whenever its state changes. The backbone of event-driven UIs, pub/sub systems, and reactive frameworks like RxJS. Decouples 'something happened' from 'who cares' — many things can react without the subject knowing them.

Question

What is the Adapter pattern?

Answer

Adapter wraps an incompatible interface so it can be used by another piece of code. Like the electrical adapter you use abroad — same plug, different shape. Useful when integrating legacy code, third-party libraries, or migrating between APIs without rewriting callers.

Question

What is the Decorator pattern?

Answer

Decorator wraps an object to add behavior without changing its class — composition over inheritance. Adding logging, caching, or auth around an existing service is a classic decorator use. Many small wrappers compose neatly to layer cross-cutting concerns.

Question

What is clean architecture?

Answer

A layered design where the domain (business rules) sits at the center, surrounded by use cases, then interface adapters (controllers, presenters), then frameworks (Express, DB drivers). Dependencies always point INWARD — the domain knows nothing about the database. Keeps business logic portable and testable.

Question

What is the Repository pattern?

Answer

An abstraction layer between business logic and data access. The service uses a Repository interface (UserRepository.findById), not the DB driver directly. You can swap implementations (Mongo, Postgres, in-memory for tests) without touching the business code.

Question

What does scalability mean?

Answer

Scalability is the ability to handle increased load by adding resources — more users, more requests, more data. Two flavors: vertical (bigger machine) and horizontal (more machines). Real systems eventually need horizontal scaling, because single machines have hard limits.

Question

Vertical vs horizontal scaling?

Answer

Vertical: upgrade to a more powerful machine — simple but capped by hardware and very expensive at the top. Horizontal: add more machines and distribute load. Horizontal is harder (you need to design for it: stateless services, distributed data) but virtually unlimited.

Question

What is load balancing?

Answer

Load balancing distributes incoming traffic across multiple servers via algorithms like round-robin, least-connections, or IP hash. It improves throughput, enables horizontal scaling, and provides resilience — if one server dies, traffic shifts to the others.

Question

L4 vs L7 load balancer?

Answer

L4 balances at the TCP layer — fast but opaque, just forwards bytes. L7 understands HTTP — can route by URL path, hostname, headers, do TLS termination, and apply WAF rules. Most modern cloud LBs are L7 (ALB, Nginx); use L4 (NLB) for raw TCP or extreme throughput.

Question

What is a CDN?

Answer

A Content Delivery Network caches static assets at edge locations spread worldwide. Users get content from a nearby edge instead of a distant origin — much faster load times, much less origin bandwidth. Examples: CloudFront, Cloudflare, Fastly. Essential for any global web app.

Question

What is a caching strategy?

Answer

A coherent plan for what to cache, where, and how to invalidate. Layers: browser cache, CDN edge, app-level (Redis), DB result cache. Each layer compounds: a CDN hit avoids your server entirely. Caching is one of the highest-leverage perf tools — and one of the easiest to get wrong (stale data).

Question

What is an API gateway?

Answer

A single entry point in front of your services. Handles auth, routing, rate limiting, request/response transforms, observability, and protocol translation. Without a gateway, every service must implement these cross-cutting concerns. Examples: Kong, AWS API Gateway, Nginx, Envoy.

Question

What is the CAP theorem?

Answer

In a distributed system, during a network partition you can only guarantee TWO of: Consistency (every read sees the latest write), Availability (every request returns a response), Partition tolerance (works despite network splits). Since partitions happen, you really choose between CP and AP.

Question

Examples of CP vs AP systems?

Answer

CP (consistency over availability): traditional RDBMS, ZooKeeper, MongoDB by default. AP (availability over consistency): Cassandra, DynamoDB defaults, CouchDB. Most cloud-scale systems lean AP for uptime and use eventual consistency, accepting that reads might briefly be stale.

Question

What is the PACELC theorem?

Answer

An extension of CAP: under Partition, choose Consistency or Availability — AND otherwise (Else), choose Latency or Consistency. Captures the fact that even without partitions, distributed systems trade consistency for latency (synchronous replication = slow but strong).

Question

How do you scale a database?

Answer

Tactics, in increasing complexity: vertical scaling (bigger box), read replicas (offload reads), connection pooling, caching (Redis), partitioning (split a table internally), sharding (split across instances), and eventually a different storage tier (e.g. warehouse for analytics). Start simple, scale as needed.

Question

What is a message queue?

Answer

A durable buffer between producers and consumers that decouples services, absorbs traffic spikes, and enables retries. Examples: Kafka (high-throughput log), RabbitMQ (traditional broker with rich routing), AWS SQS (managed simple queue). One of the most important primitives in scalable architectures.

Question

Kafka vs RabbitMQ?

Answer

Kafka is a distributed log — partitioned, replicated, persistent — built for very high throughput and replay. RabbitMQ is a traditional broker with complex routing (exchanges, bindings) and per-message acknowledgements. Kafka for event streams and analytics; RabbitMQ for work queues and complex routing.

Question

What is a distributed system?

Answer

Multiple machines coordinating across a network to act as one logical system. You trade simplicity for scale and fault tolerance. New problems show up: partial failure, network partitions, clock drift, message reordering. Famously summarized: 'You know you have one when a computer you didn't know existed crashes yours.'

Question

What is consensus in distributed systems?

Answer

Multiple nodes agreeing on a single value despite failures. Algorithms: Paxos (foundational, complex), Raft (more readable, used in etcd/Consul). Consensus powers leader election, replicated state machines, and configuration stores. It's slow and expensive — use it where you must, not everywhere.

Question

What is leader election?

Answer

Selecting one node to coordinate work (assign tasks, accept writes) — usually done via consensus (Raft) or an external coordinator (ZooKeeper, etcd). The leader sends heartbeats; if it dies, followers detect timeout and elect a new one.

Question

What is a quorum?

Answer

The minimum number of nodes that must agree for a write or read to be considered valid — typically a majority (e.g. 2 of 3, 3 of 5). Quorums tolerate node failures without losing consistency. Read+write quorums must overlap to guarantee fresh reads (W + R > N).

Question

How would you design WhatsApp?

Answer

Stateless API tier, WebSocket gateways for persistent connections, a message broker (Kafka) to fan messages out, user/conversation services, a message store optimized for write-heavy timeline reads (Cassandra), object storage for media (S3), push-notification service for offline users, end-to-end encryption client-side.

Question

How would you design Uber?

Answer

Rider/driver apps publishing location, a real-time geo-index (S2 cells or quadtree) for nearby-driver lookup, matching service that pairs them, trip service tracking the lifecycle, payments, surge pricing engine, ETA via routing graph, plus support services like notifications, ratings, and abuse detection.

Question

How would you design Netflix?

Answer

CDN-heavy video delivery (Open Connect), adaptive bitrate streaming (HLS/DASH), microservices for catalog/playback/billing/recommendations, A/B testing platform, chaos engineering, multi-region failover, and an offline analytics pipeline crunching viewing logs to drive recommendations.

Question

How would you design a ChatGPT-like clone?

Answer

Frontend with streaming UI, an auth and rate-limit gateway, conversation service for history, a queued GPU inference pool (workers pull jobs), a vector store for RAG over uploaded docs, prompt-cache layer, observability (LangSmith-style), guardrails for safety, and granular usage tracking for billing.

Question

How would you design a notification system?

Answer

Producer API for events, a preference service (does this user want this notification on this channel?), a queue per channel (email/SMS/push), worker pools per channel with rate limits, retries with dead-letter queues, idempotency keys, templating, and analytics to track delivery/open rates.

Question

How would you design a URL shortener?

Answer

Generate a short code (base62 of an ID, or hash + collision check), store the mapping in a KV store + persistent DB, redirect via 302, log analytics async (queue → warehouse), support custom aliases and expiry. The hard parts at scale: write throughput, analytics ingestion, and abuse prevention.

Question

How would you design an AI chatbot system?

Answer

Frontend, API tier handling sessions, conversation store, RAG retrieval (vector DB + reranker), LLM gateway with prompt caching and provider failover, tool/function calling layer, guardrails on input and output, observability and eval pipelines, and per-tenant cost/usage tracking.

Question

How would you design an AI agent architecture?

Answer

Planner LLM that decomposes goals, a registry of tools (with descriptions and JSON schemas), an executor that runs tool calls, short-term memory (context) and long-term memory (vector store), state machine for the loop, observability for every step, sandboxing for risky tools, and hard budget/time caps.

Question

What is a sticky session?

Answer

The load balancer routes a user's repeat requests to the same backend (via cookie or IP hash). Lets you keep session state in memory on that instance — simple but bad for scaling and failover. Better: keep state external (Redis) and stay stateless.

Question

What is the thundering herd problem?

Answer

Many clients retry simultaneously after a failure, overwhelming a recovering service the moment it comes back online. Fix with exponential backoff WITH JITTER (add randomness so retries don't sync up), request coalescing, and gradual ramp-up.

Question

What is cache stampede?

Answer

When a popular cache entry expires, many concurrent requests miss simultaneously and all hit the database to recompute it. Fix with single-flight (only one request recomputes, others wait), TTL jitter, or refresh-ahead (recompute slightly before expiry).

Question

What is consistent hashing?

Answer

Map keys to nodes via a hash ring so adding/removing a node only remaps a small fraction of keys — instead of nearly all of them as with modulo hashing. Used in distributed caches (Memcached clients), Cassandra, and most modern sharded systems.

Question

What is a heartbeat?

Answer

Periodic 'I'm alive' signals between nodes (every few seconds). Missing heartbeats trigger failover, removal from a cluster, or alerting. Tuning is delicate: too short causes false positives under load; too long means slow detection of real failures.

Question

What is split-brain?

Answer

Two nodes both think they're the leader after a network partition, accepting writes independently and causing divergent state. Prevented with quorums (only a majority can be leader) and fencing (kill the old leader on recovery before it can resume writing).

Question

What is eventual consistency?

Answer

After writes stop, all replicas eventually converge to the same value. Reads in the meantime might return stale data. The trade-off you accept for high availability and low latency in geo-distributed systems. UX must handle the 'just made a change but don't see it yet' moment.

Question

What is strong consistency?

Answer

Every read sees the latest committed write — no staleness. Required by most financial systems and anywhere ordering really matters. Costs latency and availability under partitions (per CAP). Achieve it via synchronous replication, quorum reads, or single-leader designs.

Question

What's CDN cache hit ratio?

Answer

The fraction of requests served from the CDN's edge cache vs forwarded to your origin. Higher = lower origin load and faster page loads. Improve it with longer TTLs, fewer URL parameters that bust the cache, and cache-friendly headers (Cache-Control: public, immutable for hashed assets).

Question

What is a read replica?

Answer

A read-only copy of the primary DB that streams changes (via WAL) and serves SELECT queries. Distributes read load and gives you a candidate for failover. Beware replication lag — replicas can be milliseconds to seconds behind.

Question

What is a write-behind cache?

Answer

Writes go to the cache first; the cache asynchronously flushes them to the DB later. Boosts write throughput dramatically because you don't wait for the DB. Trade-off: if the cache fails before flushing, you lose those writes. Used carefully in OLTP, often in metric pipelines.

Question

What is a service mesh?

Answer

An infrastructure layer (Istio, Linkerd, Consul Connect) that handles service-to-service traffic — mTLS encryption, retries, circuit breaking, observability, traffic routing — without app code changes. Typically implemented as sidecars (Envoy proxies) running next to each service.

Question

What is API gateway rate limiting?

Answer

Centralized control of requests/sec per user, IP, or API key at the gateway layer — protects every downstream service in one place. Without it, each service would have to implement its own rate limiting, with inevitable inconsistencies. Most managed API gateways have it built in.

Question

Idempotency in distributed systems?

Answer

Making operations safe to retry without side effects. Achieved via idempotency keys (client sends a unique key, server returns cached result on retry), conditional writes (ETag, version field), or naturally idempotent ops (PUT, DELETE). Critical when networks can fail and clients will retry.

Question

How do you design for high availability?

Answer

Redundancy at every layer (no single instance), health checks and automated failover, multi-AZ deployment, graceful degradation when dependencies fail, stateless services so any instance can serve any request, and chaos engineering to validate the failure paths actually work.

Question

What is a circuit breaker?

Answer

A pattern that stops calling a failing dependency once errors exceed a threshold — the breaker 'opens' and fails fast instead of piling up timeouts. After a cool-down it lets a probe through (half-open). Protects the caller and gives the dependency time to recover.

Question

What is the bulkhead pattern?

Answer

Isolate resources (threads, connection pools) per dependency so one failing service can't exhaust shared resources and take down everything. Like watertight compartments on a ship — a leak floods one compartment, not the whole vessel.

Question

What is a fan-out service?

Answer

A service that takes one event and dispatches it to many subscribers — central to notifications, feeds, and broadcasts. Implemented with pub/sub topics, message broadcast lists, or per-subscriber queues. The scale challenge is whales (a celebrity with 100M followers) — design for it upfront.

Question

Pull vs push notifications?

Answer

Pull: client polls the server (simple, wasteful for low-frequency events). Push: server sends to client when ready, via WebSocket, SSE, or mobile push notification services. Push is more efficient for rare events; pull is fine for things that change predictably.

Question

What is partition tolerance?

Answer

The system continues to operate despite network partitions splitting the cluster. The 'P' in CAP. Realistically partition tolerance isn't optional — networks fail — so the real choice in CAP is C vs A during partitions.

Question

What is geo-replication?

Answer

Replicating data to multiple geographic regions so users get low latency (read from a nearby region) and you survive a whole region failing (disaster recovery). Async replication is easier but adds lag; sync gives consistency but adds latency. Most systems mix both.

Question

Multi-region active-active?

Answer

Multiple regions accept writes concurrently, then replicate to each other. Best latency for users worldwide and strong DR, but requires conflict resolution (CRDTs, last-write-wins, or app-specific merging). Complex but the gold standard for global scale.

Question

Active-passive deployment?

Answer

One region is the primary; others are warm standbys ready to take over on failure. Simpler than active-active because only one region accepts writes at a time, but failover has measurable downtime and idle resources cost money.

Question

What is graceful degradation?

Answer

When a dependency fails, the system continues to serve a reduced experience instead of erroring out — cached recommendations instead of fresh ones, skipping the live status, hiding non-critical UI. Users get something working rather than an error page.

Question

What is a feature flag?

Answer

A runtime toggle that turns features on or off without redeploying. Enables canary releases (5% of users), A/B tests, kill switches for buggy code, and gradual rollouts. Tools: LaunchDarkly, GrowthBook, Unleash, Flagsmith.

Question

What is a canary deployment?

Answer

Roll out a new version to a small slice of traffic (1-5%) first, observe metrics, then expand if healthy or roll back if not. Catches problems with much less blast radius than deploying to 100% at once. Common pattern in modern CD pipelines.

Question

Blue-green deployment?

Answer

Maintain two identical production environments — 'blue' (current) and 'green' (new). Deploy to green, switch traffic over atomically (via load balancer), and you can switch back instantly if there's a problem. Wasteful (double resources during cutover) but gives the safest rollback.

Question

What is a rolling deployment?

Answer

Replace instances incrementally — kill 10%, deploy new code, wait until healthy, repeat. Zero downtime, no double resource cost. But you'll have BOTH versions in production briefly, so APIs must remain backwards compatible during the rollout.

Question

Common API rate limiting algorithms?

Answer

Fixed window (simple, but boundaries cause bursts), sliding window (smoother, more accurate), token bucket (allows bursts up to bucket size, refills steadily — most popular), leaky bucket (smooths output rate). Token bucket is the default choice for most APIs.

Question

Token bucket algorithm explained?

Answer

A bucket holds up to B tokens and refills at rate R tokens/sec. Each request takes one token; if the bucket is empty, the request is rejected. Lets clients burst up to B requests immediately, then enforces R sustained rate. Simple and predictable.

Question

What is request coalescing?

Answer

Merging identical concurrent requests into a single upstream call and sharing the result with all callers. Saves work in caches and prevents stampedes. Sometimes called 'single-flight' (Go's golang.org/x/sync/singleflight implements this pattern cleanly).

Question

Heartbeat-based service discovery?

Answer

Instances register with a discovery service (Consul, etcd, Eureka) and send periodic heartbeats. Missing heartbeats trigger removal from the registry. Clients query for healthy instances. Common in microservice setups before service meshes became standard.

Question

What is autoscaling?

Answer

Adding or removing instances based on metrics (CPU, queue depth, request rate). Configure thresholds and cool-down periods to avoid flapping (scaling up and down repeatedly). Best practice: scale on a leading indicator like queue depth, not lagging like CPU.

Question

What is HPA (Horizontal Pod Autoscaler)?

Answer

Kubernetes feature that scales the number of pod replicas based on CPU, memory, or custom metrics. Configure target utilization (e.g. 70% CPU) and min/max replicas; HPA adjusts the deployment automatically. Pairs with cluster autoscaler that adds/removes nodes.

Question

What is the shard key for a chat app?

Answer

Conversation ID — keeps all messages of a chat on one shard, so reading a chat doesn't scatter-gather across shards. Beware mega-chats (10M-member channels): you may need to sub-shard or treat them specially. User ID is the alternative for personal inboxes.

Question

How would you design a social feed?

Answer

Fan-out on write (push to each follower's feed at post-time) for fast reads — best when fan-out is small. Fan-out on read (compute the feed when requested) for celebrities with millions of followers. Most real systems are hybrid, with feeds cached in Redis and recomputed lazily.

Question

What is a WebSocket gateway?

Answer

A specialized tier that maintains long-lived WebSocket connections from clients and forwards messages to/from backend services via internal pub/sub. Decouples connection management from business logic and lets you scale them independently. Often built on Envoy, custom Node services, or AWS API Gateway WebSocket APIs.

Question

What is a presence service?

Answer

Tracks who's online and idle — used in chat, gaming, collaboration tools. Implemented with Redis sorted sets keyed by last-seen timestamp, or specialized services. Hard at scale because heartbeats arrive constantly from every connected client.

Question

How would you design a payment system?

Answer

Idempotent APIs (idempotency keys), double-entry ledger (every transaction has equal debits and credits), eventual consistency between systems with reconciliation jobs, audit logs for every change, retries with backoff and dedup, and strict compliance (PCI, SOX) on what you log and store.

Question

Why double-entry bookkeeping in payments?

Answer

Every financial transaction is recorded as equal debits and credits across at least two accounts. The invariant 'total debits = total credits' makes corruption detectable instantly, makes reconciliation tractable, and matches established accounting practice — auditors expect it.

Question

Idempotency in payments?

Answer

Critical: clients send an idempotency key with each request; the server stores the result for the key and returns it on retry. Without this, a flaky network can charge the customer twice. Stripe and every other modern payment API enforce idempotency keys for this reason.

Question

How to handle hot keys in Redis?

Answer

Shard the key: store it as key#1, key#2, … key#N, and have clients pick a random shard for writes and aggregate on read. Or use local in-process caches in front of Redis to absorb reads. The worst case is a single celebrity's profile hammering one Redis node.

Question

What is a read-through cache?

Answer

The cache itself fetches from the DB on a miss and stores the result; the app only talks to the cache. Cleaner app code, but couples the cache tightly to the data source. Less common than cache-aside in practice.

Question

Trade-offs of eventual consistency?

Answer

Pros: low latency, high availability, scales geographically. Cons: complex client/UI logic to handle 'just changed but don't see it', harder reasoning about ordering, conflict resolution needed for concurrent writes. Eventual consistency is great where users tolerate brief lag — and bad in places they don't (bank balances).

Question

Saga vs 2PC?

Answer

Saga: chain of local transactions with compensating actions on failure — async, scales horizontally, no global locks. 2PC: synchronous coordinator-driven commit — strong consistency but blocks if the coordinator fails. Modern microservice systems almost always pick saga.

Question

How do you size a DB connection pool?

Answer

Start with (CPU cores × 2) + effective_spindle_count for OLTP. Increase only if you see waits in the DB, not just because. Larger pools cause context switching and lock contention in the DB. The right number is often much smaller than people guess.

Question

How do you handle a hot row?

Answer

Strategies: shard the value (split a counter into N sub-counters, sum on read), batch writes (accumulate changes in memory, flush periodically), queue writes to a single writer, or move the field to a separate update path with eventual aggregation. Hot rows are a top scaling failure mode.

Question

What is write amplification?

Answer

One logical write triggers many physical writes — LSM compaction, secondary indexes, WAL, replication. Affects SSD wear and throughput. Modern databases work hard to keep amplification low; understanding it helps when tuning storage-intensive systems.

Question

What is a metadata service?

Answer

A centralized config/identity store that services consult on startup or periodically — used for service discovery, feature flags, dynamic config, secret retrieval. Examples: Consul, etcd, AWS Parameter Store. Keep it highly available because everyone depends on it.

Question

How do you design real-time analytics?

Answer

Event ingestion via Kafka or Kinesis → stream processor (Flink, Spark Streaming, ksqlDB) → real-time store (Druid, ClickHouse, Pinot) → dashboards. Keep raw events durable so you can replay if downstream logic changes.

Question

What is a dead-letter queue (DLQ)?

Answer

A separate queue for messages that repeatedly fail processing. Lets you inspect and replay them without blocking the main queue with poison messages. Every production queue needs a DLQ plus an alarm when it gets non-trivially full.

Question

What is exactly-once delivery?

Answer

Every message is processed exactly once — no duplicates, no losses. Genuinely hard in distributed systems. Usually achieved through at-least-once delivery + idempotent processing (dedup by message ID). Pure exactly-once exists in some systems (Kafka with transactions) but with strong constraints.

Question

At-least-once vs at-most-once?

Answer

At-least-once: messages are never lost but may be duplicated — most queues default here. At-most-once: messages are never duplicated but may be lost (UDP-style). Choose at-least-once for most use cases and add idempotency at the consumer; data loss is usually worse than duplicates.

Question

How would you scale writes to a single user's feed?

Answer

Append-only log per user (Cassandra wide row), batch writes from producers, async fan-out into the user's feed cache, cap the feed size (keep last N items in fast storage, older in cheap), separate hot/cold storage tiers.

Question

How would you design a leaderboard?

Answer

Redis sorted set with ZADD/ZINCRBY for scores and ZRANGE/ZREVRANGE for top-N. O(log N) updates, O(log N + M) reads. For billions of users, shard by region and aggregate top results across shards. Persist periodically to a durable store.

Question

How to design a rate-limited public API?

Answer

API key per consumer, token bucket per key stored in Redis, expose remaining quota via response headers (X-RateLimit-Remaining), return 429 with Retry-After when exceeded. Separate tiers (free, pro, enterprise) with different limits. Document quotas clearly.

Question

How to design a search system?

Answer

Inverted index (Elasticsearch, OpenSearch, Meilisearch), tokenization/analyzer pipelines per language, query DSL exposing filters and facets, ranking that combines BM25 with business signals (popularity, recency), caching for popular queries, async reindexing via CDC when source data changes.

Question

How to design a video upload pipeline?

Answer

Resumable upload to S3 (browser PUTs directly using signed URL), S3 event triggers a queue, transcoder workers (ffmpeg) generate HLS variants at multiple resolutions, store manifests in DB, deliver via CDN. Generate thumbnails and captions in parallel. Notify the uploader when ready.

Question

How to design a metrics/logging pipeline?

Answer

Collector agents on each host → buffered ingestion (Kafka) → stream processor → time-series DB (Prometheus, InfluxDB) for metrics, log store (Elasticsearch, Loki) for logs. Tiered retention (hot/warm/cold), aggregation rules, and SLO-driven alerts on top.

Question

How to design an e-commerce inventory system?

Answer

Strong consistency on stock counts (you cannot oversell), atomic decrements or optimistic locking on the inventory row, short-lived reservation TTLs during checkout so abandoned carts release stock, async reconciliation jobs, idempotent payment-and-fulfillment events.

Question

What is a single point of failure (SPOF)?

Answer

Any component whose failure brings down the whole system — one DB without replicas, one load balancer, one auth service. Eliminate via redundancy, load balancing, stateless services, and multi-AZ deployment. The cheapest reliability wins come from removing SPOFs.

Practise System Design in the app
Track your progress, flag tricky cards and write your own answers.

Open in the app

More topics: React & Frontend JavaScript & TypeScript Backend Engineering Databases AI & Agentic AI DevOps & Cloud Security Testing DSA Coding Problems (Python)