Ten questions at a time, drawn from 155. Every answer is explained. Nothing is saved and no account is needed.
When defining non-functional requirements, why is it critical to prioritize latency over throughput for a real-time messaging application?
Practice quiz for System Design. Scores are not saved.
When defining non-functional requirements, why is it critical to prioritize latency over throughput for a real-time messaging application?
Answer: User perception of interactivity depends on minimizing the time per individual message delivery.. Latency is critical for user experience in real-time apps. Throughput does not guarantee latency; high throughput can coexist with high latency (like in batch processing). The other options are incorrect because throughput is absolutely relevant, and latency is generally harder to satisfy.
From lesson: System Design Interview Framework
A system requires strong consistency for financial transactions but high availability for viewing profiles. How should you approach the data storage strategy?
Answer: Segregate the storage strategy by using different databases or configurations based on data access patterns.. Using a one-size-fits-all approach is a mistake. Segregation allows optimizing for the specific consistency and availability needs of different data types. Forcing one consistency model compromises either accuracy or availability unnecessarily.
From lesson: System Design Interview Framework
You are designing a system that must handle sudden traffic spikes. What is the most effective approach to handle this using a load balancer?
Answer: Use a load balancer to distribute traffic across a pool of auto-scaled instances.. Auto-scaling behind a load balancer allows dynamic handling of variable traffic. Vertical scaling (option 1) has hard limits. Caching is helpful but not sufficient for write-heavy spikes. Bypassing the app layer is dangerous and doesn't solve traffic distribution.
From lesson: System Design Interview Framework
When performing back-of-the-envelope calculations, what is the primary purpose of estimating the number of concurrent connections?
Answer: To determine the bandwidth requirements and necessary load balancer/server capacity.. Concurrent connections directly dictate the load on the network layer, connection pool management, and server resource allocation (memory/threads). This has no direct link to language choice, revenue, or choosing a database vendor.
From lesson: System Design Interview Framework
Why is it important to consider the 'read-to-write' ratio when designing a system?
Answer: It dictates whether read replicas or caching strategies should be prioritized over write-optimization strategies.. High read ratios favor caching and read replicas. High write ratios require focusing on queueing, database sharding, or write-ahead logging. It does not dictate UI, does not make data consistency irrelevant, and you always need a data storage mechanism.
From lesson: System Design Interview Framework
Which of the following scenarios is best addressed by vertical scaling?
Answer: A legacy monolithic application that cannot run in a distributed environment without major refactoring. Vertical scaling involves increasing the power of a single machine. Option 2 is correct because refactoring for horizontal scaling is time-intensive and risky. Option 1, 3, and 4 are ideal for horizontal scaling, which provides elasticity, redundancy, and geographic distribution.
From lesson: Scalability — Horizontal vs Vertical Scaling
What is the primary trade-off when moving from vertical to horizontal scaling in a stateful application?
Answer: Increased complexity in session management and data synchronization. Horizontal scaling requires managing distributed state (e.g., sticky sessions or shared caches), which is significantly more complex than keeping state on a single machine. Option 1 is false as horizontal scaling often uses cheaper nodes. Option 3 and 4 are incorrect because horizontal scaling offers higher limits and easier rollouts.
From lesson: Scalability — Horizontal vs Vertical Scaling
If your system is experiencing high latency due to a single database node becoming a bottleneck for write operations, what is the most effective approach?
Answer: Implement database sharding or partition the data. Adding memory (vertical scaling) doesn't solve write contention. Read-replicas only help with read-heavy traffic. Sharding distributes write traffic across multiple nodes, effectively scaling the system horizontally. Network bandwidth is rarely the bottleneck for logic-heavy write operations.
From lesson: Scalability — Horizontal vs Vertical Scaling
Why is horizontal scaling often considered more 'resilient' than vertical scaling?
Answer: It distributes load across multiple independent nodes, avoiding a single point of failure. Horizontal scaling creates redundancy; if one node fails, others continue operating. Vertical scaling creates a single point of failure. Option 1 is wrong as it uses commodity hardware. Option 4 is false due to the high configuration overhead.
From lesson: Scalability — Horizontal vs Vertical Scaling
In which case would you choose to NOT horizontally scale your application?
Answer: When the cost of maintaining the orchestration layer outweighs the benefits of extra capacity. Horizontal scaling adds operational complexity. If the system is small, the overhead of managing a cluster is higher than simply scaling up a single server. The other options are classic justifications for why you SHOULD choose horizontal scaling.
From lesson: Scalability — Horizontal vs Vertical Scaling
Which scenario makes an 'Least Connections' algorithm significantly better than a 'Round Robin' algorithm?
Answer: When requests vary significantly in their processing time or computational complexity.. Least Connections tracks active requests, preventing servers handling 'heavy' tasks from being overwhelmed. Round Robin is fine for identical, fast tasks, but fails when requests differ in cost. The others don't necessitate switching algorithms.
From lesson: Load Balancing
In a Layer 7 load balancing configuration, what is a primary advantage over Layer 4 balancing?
Answer: Ability to route traffic based on URL paths, headers, or content types.. Layer 7 (Application Layer) can inspect the payload to make intelligent routing decisions (e.g., sending /api traffic to one pool and /static to another). Layer 4 is faster but 'blind' to content. Layer 4 handles UDP better, and L7 is more computationally intensive.
From lesson: Load Balancing
Why is it dangerous to rely solely on DNS-based load balancing for a highly available production system?
Answer: DNS caching at the client or ISP level prevents immediate failover when a server goes down.. DNS entries have TTLs (Time to Live). If a server fails, clients will continue trying to reach it until their local cache expires. Options 1, 2, and 4 are technically incorrect regarding DNS capabilities.
From lesson: Load Balancing
How does the 'Session Persistence' (or sticky sessions) feature impact system design?
Answer: It makes it harder to achieve a balanced distribution if some users have very long-running sessions.. Sticky sessions bind a user to a specific node, which can create 'hot spots' if one user is very active. It does not improve scalability (Option 1), has no relation to database necessity (Option 2), and actually increases load balancer state tracking (Option 3).
From lesson: Load Balancing
When designing for high availability, what is the purpose of placing a load balancer in front of a cluster of servers?
Answer: To provide a single entry point that can route around individual node failures.. The load balancer abstracts the cluster, allowing nodes to be added, removed, or replaced without the client knowing. Encryption is a feature but not the primary goal of the architectural pattern, and it is not a file storage tool.
From lesson: Load Balancing
When implementing a 'Cache-Aside' pattern, what happens during a cache miss?
Answer: The application fetches data from the database and updates the cache.. In Cache-Aside, the application is responsible for the interaction. If a miss occurs, the app fetches from the database and writes it to the cache. Options 1 and 2 are incorrect because the cache is passive. Option 3 is incorrect because the database doesn't manage the cache.
From lesson: Caching Strategies — CDN, Redis, Memcached
Which scenario makes Redis a superior choice over Memcached?
Answer: When you require data persistence and complex data structures.. Redis supports persistence and data structures like sorted sets and hashes, which Memcached lacks. Memcached is only for simple strings, making Option 0 and 3 better suited for Memcached, and Option 2 is not a differentiator.
From lesson: Caching Strategies — CDN, Redis, Memcached
What is the primary benefit of placing a CDN in front of your application?
Answer: It reduces latency by serving static assets from edge locations closer to users.. CDNs cache static content at the edge to shorten the network distance. Option 0 is wrong because CDNs don't expand databases. Option 2 is a feature of TLS, not CDNs. Option 3 is wrong because CDNs cannot replace application logic.
From lesson: Caching Strategies — CDN, Redis, Memcached
In a Write-Through caching strategy, which statement is true?
Answer: Data is written to both the cache and the database synchronously.. Write-Through ensures data is written to both simultaneously, ensuring consistency. Option 0 describes a variation of write-back, Option 1 is standard Cache-Aside, and Option 3 is Write-Behind.
From lesson: Caching Strategies — CDN, Redis, Memcached
What is the consequence of a 'Cache Stampede'?
Answer: The database is overloaded because multiple requests try to regenerate the same expired cache key simultaneously.. Cache Stampede happens when a popular key expires and many processes fetch from the DB at once. Option 1 refers to memory management, Option 2 refers to TTL configuration, and Option 3 is unrelated to the cache layer.
From lesson: Caching Strategies — CDN, Redis, Memcached
When designing a system that uses a CDN, why is it critical to use versioned filenames (e.g., app.v1.js) for static assets?
Answer: To solve the issue of cache invalidation when content updates. Versioned filenames allow you to set very long TTLs (improving speed) because the file name changes when the content changes, forcing the CDN to fetch the new version immediately. Option 0 and 3 are incorrect as naming doesn't affect compression or control plane load, and option 1 is incorrect because it defeats the caching performance benefits.
From lesson: Content Delivery Networks (CDN)
A system architect decides to use a CDN to cache API responses. Which scenario would make this a poor design choice?
Answer: The API response changes based on the user's authentication token. Caching user-specific (authenticated) content at the edge is dangerous and usually ineffective, as it risks showing one user's private data to another. Option 0 is a perfect use case for CDN caching, option 2 is a static asset use case, and option 3 is a common CDN feature.
From lesson: Content Delivery Networks (CDN)
How does a CDN improve the performance of a distributed system?
Answer: By reducing the physical distance between the user and the requested data. CDNs cache data on Edge Servers geographically closer to the user, reducing latency (round-trip time). Option 0 refers to Edge Computing, not standard CDN caching; option 2 is false as CDNs sit in front of load balancers; option 3 is false as CDNs handle external, not internal, database traffic.
From lesson: Content Delivery Networks (CDN)
Which of the following describes the 'Origin Pull' method of populating a CDN cache?
Answer: The CDN fetches content from the origin when it receives a request for a file not in its cache. Origin Pull is the standard 'lazy loading' method where the CDN retrieves content only when a user requests it for the first time. Option 0 describes 'Origin Push', which is less common for general traffic; option 2 is incorrect; option 3 is false because CDNs are for serving static data, not database backups.
From lesson: Content Delivery Networks (CDN)
What is the primary benefit of using a CDN to mitigate a DDoS attack?
Answer: The CDN distributes the incoming attack traffic across a global network of servers. CDNs have huge bandwidth and distributed edges that can absorb massive amounts of traffic, preventing the origin server from being overwhelmed. Option 0 is unrealistic as some malicious traffic bypasses filters; option 2 is false as patches are an application duty; option 3 is technically impossible as servers require IP addresses to function.
From lesson: Content Delivery Networks (CDN)
Which scenario best justifies the selection of a NoSQL document store over a Relational Database?
Answer: The data schema is highly polymorphic and changes frequently.. NoSQL document stores excel with polymorphic data that changes often, as they don't require schema migrations. Option 0 and 3 favor SQL's relational capabilities, and option 2 requires the ACID guarantees traditionally associated with relational engines.
From lesson: SQL vs NoSQL — When to Use Which
A developer needs to store user activity logs that are append-only, massive in volume, and have no relational dependencies. Which approach is most efficient?
Answer: A wide-column store designed for high-throughput writes.. Wide-column stores are optimized for high-volume write throughput in append-only scenarios. Relational databases (0, 2) incur overhead from integrity checks, and key-value stores (3) are generally not the primary choice for log-style analytical workloads.
From lesson: SQL vs NoSQL — When to Use Which
When designing a system that requires high availability and partition tolerance, what is the primary risk of using a traditional single-node SQL database?
Answer: It presents a single point of failure and scaling bottlenecks.. Single-node SQL databases create a vertical scaling ceiling and a single point of failure, contradicting high availability. Option 0 and 3 are factually incorrect regarding SQL, and option 1 describes a distributed system, not a single-node one.
From lesson: SQL vs NoSQL — When to Use Which
How should a system designer approach data consistency when moving from a monolithic SQL database to a distributed NoSQL architecture?
Answer: Implement application-level logic to handle eventual consistency.. In distributed systems, eventual consistency is common, necessitating application-level handling of stale data. Option 0 is a dangerous assumption, option 2 ignores the importance of data integrity, and option 3 negates the benefit of a distributed architecture.
From lesson: SQL vs NoSQL — When to Use Which
Which characteristic of a system would strongly favor a SQL database despite the presence of high traffic?
Answer: The need for frequent updates to complex, interconnected entities.. Relational databases are best for interconnected entities requiring integrity across updates. Unstructured blobs (1) and dynamic schemas (3) favor NoSQL, and eventual consistency (2) is more typical of NoSQL, not the strength of SQL.
From lesson: SQL vs NoSQL — When to Use Which
When configuring a primary-replica architecture, why might an application choose asynchronous replication over synchronous replication?
Answer: To minimize the latency impact on write operations.. Synchronous replication requires waiting for confirmation from replicas, which increases write latency. Asynchronous replication avoids this wait, making it faster. The other options are incorrect because synchronous replication is better for consistency and data loss prevention, and neither mode inherently simplifies conflict resolution.
From lesson: Database Replication
What is the primary risk associated with a 'split-brain' scenario in a multi-master replication setup?
Answer: Inconsistency caused by different nodes accepting conflicting writes.. A split-brain occurs when the network partition prevents nodes from communicating, leading them to accept independent, conflicting writes. The other options describe performance or storage issues, not the logical data divergence caused by split-brain.
From lesson: Database Replication
Which strategy best addresses the problem of stale reads in a system using asynchronous replication?
Answer: Using read-your-writes consistency logic at the application layer.. Read-your-writes consistency ensures that a user sees their own updates even if replicas lag, by routing the read to the primary or waiting for specific version tags. Routing to the primary is a valid architectural choice, but it doesn't solve the issue for the replication system itself, while option 3 is just synchronous replication.
From lesson: Database Replication
In a Leader-Follower replication model, what is the effect of increasing the number of followers?
Answer: The load on the primary node is significantly reduced for read-heavy workloads.. Adding followers allows read traffic to be distributed, offloading the primary. Writes are still limited by the primary, so throughput doesn't increase linearly. Election time remains, and conflict frequency is unaffected because only one node writes.
From lesson: Database Replication
Why is it dangerous to perform an automated failover without a consensus-based monitoring system?
Answer: It may mistakenly promote a healthy node to leader while the old leader is still functioning.. Without consensus, multiple nodes might 'think' the leader is dead and trigger elections, resulting in two leaders (split-brain). This causes massive data corruption. The other choices are either non-consequential or technically incorrect regarding how failover works.
From lesson: Database Replication
Which of the following scenarios is most appropriate for using range-based partitioning instead of hash-based partitioning?
Answer: When the application frequently queries data within specific chronological intervals.. Range-based partitioning is ideal for temporal queries (e.g., getting logs for the last hour) because data is stored physically together. Hash-based is better for uniform distribution and high cardinality. Options 1, 3, and 4 describe strengths of hashing, not range-based schemes.
From lesson: Database Sharding and Partitioning
When implementing a service that requires frequent cross-shard joins for analytics, what is the best strategy?
Answer: Denormalize the data to store related entities on the same shard.. Denormalization allows related data to be collocated on the same shard, removing the need for network-intensive cross-shard joins. Increasing shards (1) makes joins harder, global indices (2) don't solve join performance, and application-side joins (4) fail at scale.
From lesson: Database Sharding and Partitioning
What is a primary advantage of using Consistent Hashing for sharding?
Answer: It minimizes the amount of data that needs to be remapped when adding or removing shards.. Consistent hashing maps nodes and keys to a ring, meaning only k/n keys need to be remapped when a node changes. Option 1 is false; load balancers are still needed. Option 2 is a property of all standard hashing. Option 4 is false, as consistent hashing is a distribution strategy, not a transaction coordinator.
From lesson: Database Sharding and Partitioning
Why is it dangerous to shard a database by a non-immutable field like 'status' or 'last_login_date'?
Answer: Because changing the field value would necessitate moving data across physical shard boundaries.. Sharding keys determine physical location; if the key changes, the row's 'home' changes, requiring a move. Null values (1) can be handled, indexing (3) is required regardless of immutability, and high cardinality (4) is usually good for sharding, not bad.
From lesson: Database Sharding and Partitioning
What occurs when a system experiences 'hotspotting' due to a sharding key choice?
Answer: One specific node experiences significantly higher traffic than others, leading to a performance bottleneck.. Hotspotting occurs when a disproportionate number of requests target one shard, rendering the rest of the cluster idle. Option 2 describes the outcome. Option 1 is wrong because load is not distributed. Option 3 and 4 describe general bugs, not the definition of hotspotting.
From lesson: Database Sharding and Partitioning
If a distributed database is designed to be highly available even during a network split but accepts that nodes may return stale data, which design pattern is it following?
Answer: Eventual Consistency. Eventual consistency prioritizes availability and partition tolerance. Strong consistency, strict ordering, and linearizability all prioritize consistency over availability during partitions.
From lesson: CAP Theorem
Why is it impossible to have a truly CA system in a distributed environment?
Answer: Network partitions are a reality of distributed communication that cannot be ignored.. The 'P' (Partition Tolerance) is a physical reality of distributed systems. A CA system would require a perfect network that never drops packets or experiences delays, which does not exist.
From lesson: CAP Theorem
A developer wants to ensure that every user sees the same balance update immediately after a deposit. What must they sacrifice during a network partition to guarantee this?
Answer: Availability. To guarantee the same balance update (Consistency), the system must refuse requests if it cannot synchronize across nodes due to a partition, sacrificing Availability. Partition tolerance cannot be sacrificed, and latency/throughput are performance metrics, not CAP components.
From lesson: CAP Theorem
In a CP system, what happens when a network partition occurs between the leader and follower nodes?
Answer: The system stops accepting operations that would compromise consistency.. A CP system chooses consistency over availability, meaning if it cannot guarantee consistent data, it must block operations. AP mode and asynchronous replication are features of AP systems, and blocking only reads while allowing writes doesn't solve the consistency requirement.
From lesson: CAP Theorem
Which scenario best describes a system prioritizing Availability (A) over Consistency (C)?
Answer: Serving cached data from a local node even if it is out of date.. Serving stale data ensures the system remains available for requests (A) while ignoring the consistency (C) requirement. The other options involve blocking or erroring, which are characteristics of a CP-focused design.
From lesson: CAP Theorem
A table has a composite index on (last_name, first_name). Which query will effectively utilize this index?
Answer: SELECT * FROM users WHERE last_name = 'Doe'. The index follows the leftmost-prefix rule. Option 2 works because it uses the leftmost column. Option 1 fails because it skips the leftmost column. Option 3 fails as the column is not in the index. Option 4 works, but Option 2 is the most direct application of the leftmost-prefix rule.
From lesson: Indexing Strategies
Why does adding too many indexes to a high-throughput write-heavy system lead to performance degradation?
Answer: Every write operation requires a corresponding update to each index structure.. Every index is a separate data structure that must be updated synchronously when data is inserted, updated, or deleted. Option 1 is false because RAM is used for caching, not exclusively for indexes. Option 2 is incorrect as modern DBs use row-level locking. Option 4 is incorrect as optimizers are deterministic.
From lesson: Indexing Strategies
When is it optimal to use a covering index?
Answer: When all columns in the SELECT clause are present in the index.. A covering index allows the database to retrieve all required data directly from the index tree without performing a costly 'bookmark lookup' to the actual table data. Options 1, 3, and 4 do not describe scenarios where index-only retrieval provides the specific benefit of avoiding heap access.
From lesson: Indexing Strategies
What is the primary trade-off of creating a B-Tree index on a column?
Answer: Faster read performance for point queries at the cost of slower write performance.. B-Tree indexes provide O(log n) lookup times for read operations but introduce overhead for every write. Option 1 is wrong because indexes increase space usage and slow down writes. Options 3 and 4 are irrelevant to the fundamental nature of B-Tree structures.
From lesson: Indexing Strategies
Which scenario makes a database index highly ineffective?
Answer: Searching for a value in a column where every entry is identical.. Indexes rely on the ability to distinguish between rows; if all entries are identical (zero cardinality), the index provides no filtering benefit, resulting in a full scan. High cardinality (Option 1) and small result sets (Option 2) are ideal for indexing, and joining on keys (Option 4) is the most efficient use of indexes.
From lesson: Indexing Strategies
When designing a system with deep, highly relational data structures that change frequently, which approach best minimizes round-trips?
Answer: GraphQL with nested queries. GraphQL is designed to fetch relational graphs in a single request. REST often requires multiple requests or complex 'expand' logic. gRPC is efficient for streaming/binary but doesn't natively solve graph-traversal round-trips. HATEOAS improves discovery but increases request count.
From lesson: REST vs GraphQL vs gRPC
Why would an architect choose gRPC over REST for communication between microservices within a private data center?
Answer: Efficient binary serialization and multiplexing. gRPC uses Protobuf for compact binary serialization and HTTP/2 for multiplexing, reducing latency. REST is more readable for humans but less efficient for internal machine-to-machine traffic. Browsers struggle with gRPC, and REST docs are better handled by OpenAPI.
From lesson: REST vs GraphQL vs gRPC
Which trade-off is inherent when moving from REST to GraphQL?
Answer: Increased complexity in server-side request parsing and authorization. GraphQL requires more complex resolvers and granular authorization at the field level. Caching is harder because queries are often POSTs. Payload size is only reduced if the client explicitly omits unnecessary fields, unlike the automatic fixed-schema reduction.
From lesson: REST vs GraphQL vs gRPC
A team needs to provide a mobile app API that must be easily consumable by third-party developers with standard tooling. Which is the most appropriate choice?
Answer: REST. REST is the industry standard for public APIs, supported by every HTTP client and proxy. gRPC requires complex code-gen and library support, while GraphQL requires specific client-side state managers. REST is the most interoperable.
From lesson: REST vs GraphQL vs gRPC
What is the primary benefit of using Protobufs in a gRPC-based architecture compared to JSON-based REST?
Answer: Stronger contract enforcement through schema compilation. Protobuf requires a strict schema definition that generates code, ensuring type safety. REST/JSON is loose and requires external validation (like JSON Schema). JSON is better for CDN caching and raw text readability.
From lesson: REST vs GraphQL vs gRPC
When designing a system requiring strict message ordering per user across multiple instances, which strategy is most effective in a Kafka-based architecture?
Answer: Use the user ID as the partition key. Using the user ID as a partition key ensures all messages for a specific user end up in the same partition, maintaining order. Single consumers negate parallel processing benefits. Global locks create bottlenecks. Idempotency handles duplicates, not ordering.
From lesson: Message Queues — Kafka, RabbitMQ
Which scenario best justifies using RabbitMQ over Kafka?
Answer: Need for complex routing logic using direct, topic, or fanout exchanges. RabbitMQ excels at complex routing (exchanges), whereas Kafka is optimized for high-throughput, persistent, and replayable streams. Storing long-term logs is a Kafka strength, not a routing-focused task.
From lesson: Message Queues — Kafka, RabbitMQ
In a distributed task queue system, what is the primary consequence of failing to implement 'at-least-once' delivery with consumer acknowledgments?
Answer: Data loss during consumer crashes. Without ACKs, the broker assumes the message is delivered as soon as it's sent. If the consumer dies, the message is lost. Duplicate processing is a side effect of 'at-least-once', not a loss of data. Latency and rebalancing are unrelated to ACKs.
From lesson: Message Queues — Kafka, RabbitMQ
A system design requires processing millions of events per second with low retention requirements. What is the most critical factor to consider?
Answer: Disk I/O throughput and partition count. Kafka's throughput is bound by disk I/O and the partition count (parallelism). Total messages, consumer groups, and payload sizes affect storage and complexity, but not the raw throughput ceiling as directly as I/O and parallelism.
From lesson: Message Queues — Kafka, RabbitMQ
Why is it often recommended to use a Dead Letter Queue (DLQ) in system design?
Answer: To handle and inspect messages that fail processing after multiple retries. A DLQ is a design pattern for error handling; it isolates poisoned or failed messages so they don't block the main flow. It does not speed up processing, balance load, or handle background tasks directly.
From lesson: Message Queues — Kafka, RabbitMQ
When designing an event-driven system, why is it critical for consumers to be idempotent?
Answer: To handle the reality of 'at-least-once' message delivery. Idempotency ensures that processing the same event multiple times results in the same state, which is necessary because network retries often lead to duplicate deliveries. It is not required for parallelism, does not affect network overhead, and does not replace the need for persistence.
From lesson: Event-Driven Architecture
Which of the following describes the primary benefit of the Saga pattern in an event-driven architecture?
Answer: Managing distributed transactions via a series of local steps. The Saga pattern coordinates multiple services to maintain consistency through local transactions and compensating actions. It does not provide immediate strong consistency (which is impossible in distributed systems) and is not intended to replace brokers or convert events to REST.
From lesson: Event-Driven Architecture
What is the primary architectural trade-off when choosing 'Event-Carried State Transfer' over 'Request-Response' for data synchronization?
Answer: Higher complexity in managing eventual consistency. Sending full state in events requires consumers to maintain their own local copy and handle eventual consistency, which is more complex than simple fetching. It actually reduces coupling, increases availability, and serialization overhead is usually negligible compared to the consistency challenges.
From lesson: Event-Driven Architecture
In a high-throughput event streaming system, how can you ensure related events are processed in the correct order?
Answer: By using a partition key based on the entity ID. Partition keys ensure that events sharing the same ID are sent to the same partition, which is consumed sequentially by a single thread. Global locks kill performance, a single consumer limits scalability, and a handshake adds unnecessary latency.
From lesson: Event-Driven Architecture
What is the main danger of using a message broker as an 'event store' without a dedicated log-based storage mechanism?
Answer: Lack of persistence and replayability for new consumers. Standard brokers often delete messages once acknowledged, preventing new consumers from replaying past events. Modern event stores/logs keep data for recovery and re-processing. The other options are generally false as most brokers support binary data, are low-latency, and scale well.
From lesson: Event-Driven Architecture
When designing a system that requires a single server to handle millions of concurrent connections, which protocol is most likely to cause memory exhaustion due to the persistence of state?
Answer: WebSockets. WebSockets maintain a full-duplex TCP connection for every client, which consumes significant server memory per connection. Long Polling is stateless during the 'hold' phase, and SSE is unidirectional with lower overhead. RESTful polling is stateless and doesn't hold open connections.
From lesson: WebSockets and Long Polling
Which scenario most justifies the use of Long Polling over WebSockets?
Answer: A notification system where messages are infrequent and connectivity is unreliable.. Long Polling is better for infrequent updates because it avoids the overhead of maintaining thousands of idle connections. The other options involve high-frequency interaction where the cost of re-establishing HTTP connections (handshakes) would be prohibitive.
From lesson: WebSockets and Long Polling
What is the primary technical challenge when scaling a WebSocket-based application across multiple server instances?
Answer: The inability to route messages between different server nodes.. Because WebSockets are stateful, a message broadcast to a user connected to 'Server A' will not reach a user connected to 'Server B' without an external pub/sub broker to bridge the nodes. The other options are either manageable or minor compared to state synchronization.
From lesson: WebSockets and Long Polling
In a Long Polling system, what happens if the server does not have data when the client's request arrives?
Answer: The server keeps the request open until new data is available or a timeout occurs.. Long Polling works by delaying the response until data is available, which minimizes latency. Returning a 404 or empty response defeats the purpose of 'long' polling, and arbitrary waiting is less efficient than server-side blocking.
From lesson: WebSockets and Long Polling
Why is the HTTP Upgrade header critical for establishing a WebSocket connection?
Answer: It switches the protocol from HTTP to a persistent TCP-based binary protocol.. WebSockets start as an HTTP handshake that 'upgrades' the connection to a persistent socket. It doesn't inherently force encryption (that's WSS), change packet sizes, or bypass firewalls; its purpose is the protocol switch.
From lesson: WebSockets and Long Polling
When designing a distributed rate limiter using Redis, which operation is critical to ensure atomicity?
Answer: Using a Lua script or Redis transaction to perform the read-increment-check sequence. Option 2 is correct because atomic operations prevent race conditions. Option 1 leads to lost updates under high concurrency. Option 3 creates a bottleneck at the DB layer, defeating the purpose of a fast cache. Option 4 is non-performant and breaks system scalability.
From lesson: Rate Limiting and Throttling
Why is the Sliding Window Log algorithm often avoided for high-traffic systems despite its accuracy?
Answer: It requires significant memory to store timestamps for every request. Option 2 is correct because storing every request timestamp for every user consumes massive memory. Option 1 is subjective and incorrect regarding difficulty. Option 3 is false as it is highly accurate. Option 4 is false, as it can be stored in Redis sorted sets.
From lesson: Rate Limiting and Throttling
If you need to ensure that no single user consumes more than 100 requests per minute while allowing for small bursts, which approach is most appropriate?
Answer: Token bucket. Option 2 is correct because the Token Bucket allows for bursts of traffic if the bucket is full. Option 1 creates artificial spikes at the start of a minute. Option 3 forces a constant flow rate and discourages bursts. Option 4 is too blunt and doesn't handle quota management.
From lesson: Rate Limiting and Throttling
A user's request is blocked by a rate limiter. What is the most standard architectural pattern to communicate this to the client?
Answer: Returning a 429 Too Many Requests status code with a Retry-After header. Option 3 is correct because 429 is the standard HTTP status for rate limiting and provides the client with clear instructions on when to try again. 503 implies the server is down. Closing the connection is bad for UX. Silently discarding is poor API design as the client won't know why it failed.
From lesson: Rate Limiting and Throttling
How does implementing rate limiting at the API Gateway level compare to implementing it within each microservice?
Answer: Gateway limiting provides a centralized, consistent policy enforcement but lacks service-specific context. Option 3 is correct because gateways provide a uniform policy layer, though they may lack deep service-specific metrics. Option 1 is wrong as gateways are usually optimized. Option 2 is false as duplicate logic in every microservice is hard to maintain. Option 4 is false as they serve different operational needs.
From lesson: Rate Limiting and Throttling
When is it appropriate to decompose a modular monolith into microservices?
Answer: When development velocity is hampered by the coupling of independent domain features. Decomposition should solve organizational or scaling bottlenecks. Option 1 is a side effect, not a primary driver. Option 2 addresses the actual business value of decoupling. Option 3 is possible with monoliths. Option 4 is an arbitrary metric that does not indicate a need for architectural change.
From lesson: Microservices Architecture
What is the primary benefit of the Database-per-Service pattern in a microservices architecture?
Answer: It enforces loose coupling by preventing services from accessing each other's underlying data schemas. Loose coupling is the goal; separate databases prevent services from becoming coupled through shared database schemas. Option 1 is incorrect as joining is often harder. Option 2 is wrong because isolation makes consistency harder. Option 4 is false as distributed transactions become more complex.
From lesson: Microservices Architecture
Why is 'Choreography' often preferred over 'Orchestration' for long-running business processes in complex microservice systems?
Answer: It removes the central point of failure and reduces coupling between the coordinating service and participants. Choreography uses events to trigger actions, removing a central controller, which lowers coupling. Option 1 is wrong because orchestration is actually easier to visualize. Option 3 is wrong as neither guarantees atomicity. Option 4 is wrong because distributed systems are inherently harder to monitor.
From lesson: Microservices Architecture
A system experiences a 'cascading failure' when one service is overloaded. Which pattern best mitigates this issue?
Answer: The Circuit Breaker Pattern. The Circuit Breaker prevents a failing service from consuming resources across the system by failing fast. The Saga pattern handles failures in distributed transactions, not cascading service load. Database patterns relate to data management, and the Sidecar pattern is for infrastructure cross-cutting concerns.
From lesson: Microservices Architecture
In a distributed microservices environment, how is data consistency typically managed when a business process spans multiple services?
Answer: Accepting eventual consistency through techniques like Sagas and compensating transactions. Distributed systems often rely on eventual consistency via Sagas to avoid the performance penalties of 2PC. Option 1 is outdated and problematic at scale. Option 3 is technically impossible to enforce across remote services. Option 4 defeats the purpose of microservices by creating a monolith.
From lesson: Microservices Architecture
When designing a system with multiple client types (e.g., Mobile, Web, IoT), which architectural approach best minimizes the coupling between the API Gateway and the downstream services?
Answer: Deploying multiple Backend for Frontend (BFF) gateways tailored to each client.. BFFs allow each client to interact with an interface optimized for its needs without bloating one central gateway. A single gateway becomes a bottleneck and a point of tight coupling, while direct exposure is a security risk. Shared databases do not solve architectural coupling at the routing layer.
From lesson: API Gateway Pattern
What is the primary architectural purpose of placing a circuit breaker inside an API Gateway during a service degradation event?
Answer: To stop sending requests to a failing service, preventing resource exhaustion.. Circuit breakers protect the system by failing fast when a service is unhealthy, preventing cascading failures. Increasing power or switching databases doesn't solve the immediate availability issue, and encryption is a security concern, not a traffic management one.
From lesson: API Gateway Pattern
Which of the following describes the most efficient way to handle authorization at an API Gateway?
Answer: The gateway validates a cryptographically signed token locally and checks scopes.. Local validation of signed tokens is performant and stateless. Database lookups or frequent redirects to auth servers introduce extreme latency and make the system less available. Trusting requests without checking headers is a major security vulnerability.
From lesson: API Gateway Pattern
If an API Gateway is experiencing high latency, what is the most appropriate action to evaluate its impact on the internal service network?
Answer: Analyzing the gateway's request queuing and total duration per downstream service call.. To diagnose latency, you must observe where the bottleneck resides—tracking request duration helps identify which service calls or processing steps are the cause. Caching POST requests is usually incorrect due to data mutation, and scaling services does not fix gateway-level latency.
From lesson: API Gateway Pattern
How does the API Gateway improve system security via 'Request Stripping'?
Answer: By removing sensitive internal headers or metadata before forwarding requests to the public client.. Request stripping ensures internal infrastructure details (like internal headers) aren't leaked to external clients. Deleting all parameters breaks functionality, blocking JSON is unreasonable, and IP address management is a network concern, not a gateway security feature.
From lesson: API Gateway Pattern
What is the primary design goal of the Circuit Breaker pattern in a distributed architecture?
Answer: To prevent a fault in one service from cascading to others. The pattern prevents cascading failure by stopping requests to an unhealthy service. Option 0 is wrong as it doesn't increase capacity. Option 2 is a database concern, not a breaker function. Option 3 describes load balancing or auto-scaling.
From lesson: Circuit Breaker Pattern
When a circuit is in the 'Open' state, how should the system behave when a new request arrives?
Answer: It should immediately execute a fallback mechanism or return an error. An 'Open' circuit represents a confirmed failure, so it must 'fail fast' via a fallback. Option 0 causes latency, option 1 defeats the purpose of the breaker, and option 3 creates memory pressure in the queue.
From lesson: Circuit Breaker Pattern
Why is it important to include a 'Half-Open' state in the circuit breaker state machine?
Answer: To perform a health check on the downstream service without overwhelming it. The 'Half-Open' state tests if the dependency is healthy before fully reopening. Option 0 describes rate limiting. Option 2 is a deployment/orchestration task. Option 3 undermines the pattern's safety.
From lesson: Circuit Breaker Pattern
A service has a circuit breaker with a high failure threshold. What is the most likely consequence during a partial outage?
Answer: The system will suffer from high latency as it repeatedly attempts to contact the failing service. A high threshold allows too many failing requests to pass before tripping, keeping the system waiting. Options 1 and 3 are incorrect because a high threshold delays reaction, and option 2 is irrelevant to the threshold setting.
From lesson: Circuit Breaker Pattern
Which scenario best justifies implementing a Circuit Breaker pattern?
Answer: Two services that communicate synchronously over a network. Synchronous remote calls are the primary sources of cascading failures. Option 0 is a local operation. Option 2 is isolated. Option 3 is a UI concern rather than a service-to-service communication issue.
From lesson: Circuit Breaker Pattern
What is the primary architectural benefit of separating the read and write models in CQRS?
Answer: Allowing independent scaling and optimization of read and write workloads. Correct: It allows scaling reads (via caches/denormalized views) differently than writes. Wrong: It does not eliminate databases; it often increases them. It creates eventual consistency, not strict consistency. It increases code complexity, not simplification.
From lesson: CQRS and Event Sourcing
In an Event Sourced system, why is the 'Event Store' considered the single source of truth?
Answer: Because the current application state is derived solely by replaying historical events. Correct: Event sourcing relies on reconstructing state from events. Wrong: Event stores are bad for search indexing. They do not store current state, but a history of transitions. They are not optimized for read-heavy latency.
From lesson: CQRS and Event Sourcing
When is Event Sourcing most appropriate for a system design?
Answer: When you need a full audit trail and the ability to travel back in time to state. Correct: The append-only nature of events provides a natural, immutable audit trail. Wrong: It is too complex for simple CRUD. It is not the simplest path. Eventual consistency makes 'read-your-writes' difficult to guarantee.
From lesson: CQRS and Event Sourcing
How should a projection handler manage the risk of message delivery failures?
Answer: By implementing retries with idempotency checks to ensure events are processed exactly once. Correct: Idempotency ensures that reprocessing the same event does not corrupt the read model. Wrong: You cannot roll back a distributed event store. Skipping data leads to inconsistencies. Synchronous updates would negate the decoupling benefits.
From lesson: CQRS and Event Sourcing
Why is 'Eventual Consistency' an inherent characteristic of CQRS/Event Sourcing?
Answer: Because the read model is updated asynchronously after the write model processes the event. Correct: Decoupling the write process from the read view projection necessarily means there is a lag between a write and when it is visible in the read model. Wrong: Performance isn't the primary driver for eventual consistency; the decoupling is. It's not about data loss prevention. It is not a vendor mandate.
From lesson: CQRS and Event Sourcing
When is the Saga pattern preferred over a distributed transaction with Two-Phase Commit (2PC)?
Answer: When the system must maintain high availability and avoid long-lived database locks across services.. Sagas provide high availability by avoiding distributed locks; 2PC blocks resources, hurting scalability. 2PC is for strict ACID, whereas Sagas accept eventual consistency. Sharing a database is an antipattern.
From lesson: Distributed Transactions — Saga Pattern
What is the primary purpose of a compensating transaction in a Saga?
Answer: To revert or undo the changes made by a previously successful local transaction if a later step fails.. Compensations are semantic undo operations required because the original transaction was already committed. Retries are a different mechanism, and notifying the user does not solve the data inconsistency.
From lesson: Distributed Transactions — Saga Pattern
How should a service handle a scenario where a compensating transaction itself fails?
Answer: Retry the compensation indefinitely or alert an operator to intervene.. Compensations must eventually succeed to ensure consistency. Ignoring it leaves the system in an inconsistent state; rolling back isn't always possible, and forward-moving requires a valid state to move to.
From lesson: Distributed Transactions — Saga Pattern
In an Orchestration-based Saga, what is the role of the orchestrator?
Answer: To store the persistent state of the Saga and explicitly tell each participant which local transaction to execute.. The orchestrator centralizes the state machine logic. Asynchronous communication without central knowledge describes choreography. Gateway and network routing are infrastructure concerns, not Saga logic.
From lesson: Distributed Transactions — Saga Pattern
Why is 'Lack of Isolation' a significant concern in Sagas?
Answer: Because other concurrent processes might read or modify data that is part of an ongoing, uncommitted Saga.. Since each step in a Saga commits locally, the intermediate state is visible. Sequentially executing transactions is a feature, not a lack of isolation. Locks are what Sagas aim to avoid.
From lesson: Distributed Transactions — Saga Pattern
A system manager decides to move from 99.9% availability to 99.99%. What is the most significant operational shift they must prepare for?
Answer: Implementing automated failover and significantly reducing manual intervention. To achieve 99.99%, manual intervention is too slow to meet the ~52-minute annual limit, requiring automated failover. Hardware replacement is irrelevant to this metric, regional concentration decreases availability, and reducing backups risks data loss, not availability.
From lesson: High Availability — 99.9% vs 99.99%
If a system has an availability requirement of 99.99%, what is the most critical architectural requirement regarding its dependencies?
Answer: Dependencies must be decoupled so that a failure in one does not cause a total system outage. Decoupling is essential for high availability to prevent cascading failures. Synchronous coupling often creates availability bottlenecks, and manual monitoring is impossible for 99.99% targets.
From lesson: High Availability — 99.9% vs 99.99%
Why does moving from 99.9% to 99.99% availability usually involve an exponential increase in budget?
Answer: Because human-in-the-loop processes must be replaced by sophisticated, tested automation and multi-region redundancy. Achieving higher 'nines' requires redundant infrastructure and complex automation to handle failures without human delay, which is significantly more expensive than standard setups. The other options are incorrect or not the primary cost drivers.
From lesson: High Availability — 99.9% vs 99.99%
When designing for 99.99% availability, what is the role of a 'Circuit Breaker' pattern?
Answer: To prevent a failing service from exhausting resources and causing a system-wide blackout. A circuit breaker prevents the system from hanging on failing requests, which is crucial for maintaining overall system availability. It is not for power management, encryption, or eliminating maintenance, which is impossible.
From lesson: High Availability — 99.9% vs 99.99%
Which of the following scenarios best justifies targeting 99.99% availability over 99.9%?
Answer: A global payment processing gateway where outages result in direct revenue loss and customer attrition. High availability targets should be driven by the business cost of downtime. A payment gateway loses money every second it is down, justifying the cost of 99.99%. The other options have low business impact if offline.
From lesson: High Availability — 99.9% vs 99.99%
A microservice cluster experiences latency spikes in a downstream dependency. Which strategy best exemplifies graceful degradation?
Answer: Returning a cached stale response or a default value instead of failing the request.. Returning cached data maintains core system utility. Increasing timeouts risks request pile-up (wrong), terminating connections is aggressive and potentially destructive (wrong), and a restart causes unnecessary downtime (wrong).
From lesson: Fault Tolerance and Graceful Degradation
In a distributed system, what is the primary role of the Circuit Breaker pattern?
Answer: To prevent a request from hitting a failing service repeatedly, allowing it time to recover.. The circuit breaker halts calls to failing services to prevent cascading failures. Encryption is security, not fault tolerance (wrong). Load balancing doesn't handle component failure (wrong). A 5ms increase is too trivial to trigger a disaster recovery failover (wrong).
From lesson: Fault Tolerance and Graceful Degradation
Why is 'jitter' combined with 'exponential backoff' during retries?
Answer: To prevent a 'thundering herd' problem where many clients retry simultaneously.. Jitter adds randomness to retry intervals, preventing synchronized spikes of traffic. Precision logging is not the goal of backoff (wrong). Cryptographic overhead is unrelated (wrong). Prioritization is a separate mechanism from retry strategy (wrong).
From lesson: Fault Tolerance and Graceful Degradation
Which scenario indicates a system is failing to degrade gracefully?
Answer: The entire website returns a 500 internal server error because the recommendation engine is down.. A full 500 error signifies a total collapse of functionality rather than partial degradation. Disabling one feature is graceful (wrong). Using a secondary node is a standard redundancy pattern (wrong). Throttling is a controlled degradation technique (wrong).
From lesson: Fault Tolerance and Graceful Degradation
Which design choice best supports fault tolerance in an asynchronous task processing system?
Answer: Implementing idempotent consumers so tasks can be safely retried without side effects.. Idempotency is crucial for fault tolerance because it allows retrying failures safely. Volatile memory loses state on crash (wrong). A single master is a single point of failure (wrong). Removing logs makes debugging failures impossible (wrong).
From lesson: Fault Tolerance and Graceful Degradation
Which approach best describes the 'Golden Signals' methodology in observability?
Answer: Prioritizing latency, traffic, errors, and saturation.. The Golden Signals focus on user-facing outcomes. Option 0 focuses on causes, not symptoms. Option 2 leads to noise and fatigue. Option 3 measures productivity, not system health. Option 1 is the standard for service-level observability.
From lesson: Monitoring, Alerting, and Observability
When designing a distributed system, why is distributed tracing superior to simple log aggregation for troubleshooting?
Answer: It provides a complete visualization of a request's path across service boundaries.. Tracing correlates events across services using trace IDs, which is essential in microservices. Option 0 is false, tracing is often data-heavy. Option 2 is a security risk/out of scope. Option 3 is incorrect because metrics serve a different purpose (aggregation).
From lesson: Monitoring, Alerting, and Observability
What is the primary danger of setting alerts based solely on average CPU utilization across a cluster?
Answer: It masks individual node failures or 'hot spots' through aggregation.. Averages hide outliers; one stuck node could be failing while the average looks healthy. Option 0 is irrelevant. Option 2 is the opposite of the truth. Option 3 is unrelated to the alerting mechanism.
From lesson: Monitoring, Alerting, and Observability
Why is 'High Cardinality' a critical factor when choosing a metrics database?
Answer: It enables deep slicing and dicing of metrics by unique attributes like UserID or RequestID.. High cardinality allows you to filter metrics by specific dimensions. Option 0 is false (cardinality increases storage complexity). Option 2 is unrelated. Option 3 is wrong as it is a database feature, not a hardware scaling strategy.
From lesson: Monitoring, Alerting, and Observability
In the context of System Design, what is the 'Error Budget' used for?
Answer: To balance the need for rapid feature deployment with system reliability.. Error budgets allow teams to innovate up to a defined reliability threshold. Option 0 is a business metric, not a reliability one. Option 2 is a management decision. Option 3 is the core purpose of SRE (Site Reliability Engineering) as taught in System Design.
From lesson: Monitoring, Alerting, and Observability
An architect is evaluating a strategy to achieve the lowest possible RPO for a global database. Which approach should be prioritized?
Answer: Synchronous data replication across multiple availability zones. Synchronous replication ensures that a transaction is not committed unless it is written to the standby, resulting in zero data loss (RPO 0). Daily/hourly snapshots result in data loss during the interval. Cold storage is for long-term retention, not immediate recovery.
From lesson: Disaster Recovery and Backup Strategies
What is the primary trade-off when selecting an Active-Active multi-region disaster recovery architecture compared to a Pilot Light strategy?
Answer: Active-Active requires higher application complexity to handle data consistency. Active-Active requires sophisticated conflict resolution and synchronization between regions, increasing complexity. Pilot Light is cheaper but involves a slower failover (Warm-up). Active-Active does not inherently provide faster failover than an already-running standby.
From lesson: Disaster Recovery and Backup Strategies
Which of the following scenarios best justifies the use of 'Warm Standby' over 'Backup and Restore'?
Answer: The system requires immediate traffic redirection with minimal downtime upon failure. Warm Standby maintains a scaled-down version of the environment running, allowing for rapid scaling to full capacity. Backup and Restore is for scenarios where downtime is acceptable. Budgeting usually favors Backup and Restore, not Warm Standby.
From lesson: Disaster Recovery and Backup Strategies
When designing for disaster recovery, how does the RPO metric influence storage selection?
Answer: Lower RPO mandates frequent snapshot frequency or continuous replication mechanisms. RPO (Recovery Point Objective) measures the acceptable amount of data loss. A low RPO requires constant synchronization or frequent capture to keep the gap small. The other options describe operational requirements unrelated to the definition of RPO.
From lesson: Disaster Recovery and Backup Strategies
Why is 'versioning' a critical component of a robust backup strategy in modern cloud-native systems?
Answer: It allows recovery from accidental deletions or application-level data corruption. Versioning preserves previous states of data, enabling recovery if an application bug corrupts the live data. It does not increase capacity, it consumes it. It is not an indexing tool, nor does it provide geographic protection against site-wide failure.
From lesson: Disaster Recovery and Backup Strategies
When designing a URL shortener that requires support for a massive number of links and high availability, which storage strategy is most scalable?
Answer: Use a NoSQL Key-Value store partitioned by the short URL key.. NoSQL Key-Value stores allow for horizontal partitioning and high-throughput read/writes, essential for global scale. Option 0 is a bottleneck; Option 2 introduces unnecessary latency; Option 3 is non-persistent and risks data loss on restart.
From lesson: Design URL Shortener
What is the primary benefit of using Base-62 encoding (0-9, a-z, A-Z) for generating short URLs?
Answer: It maximizes the number of possible unique URLs for a fixed length of characters.. Base-62 increases the addressable space compared to decimal or hexadecimal, allowing for shorter URLs with more combinations. Option 0 is false as it's a representation, not encryption; Option 2 is handled by unique IDs; Option 3 is impossible without a compression algorithm.
From lesson: Design URL Shortener
If a system uses a counter-based approach to generate unique keys for URLs, what is a potential challenge in a distributed environment?
Answer: The counter might produce duplicate keys if multiple servers increment it simultaneously.. Distributed increments lead to race conditions; you need a centralized service or token ranges to prevent this. Option 1 is false (Base-62 is agnostic); Option 2 is false; Option 3 is false.
From lesson: Design URL Shortener
Why is it recommended to add a caching layer specifically between the application and the database for this system?
Answer: To minimize the latency of the redirect process by serving popular links from RAM.. Caching popular entries reduces latency and database read frequency, which is vital for high-traffic redirects. The other options are either not primary goals or are handled by other system components.
From lesson: Design URL Shortener
In a system design scenario, what is the trade-off of choosing a shorter 'short URL' length?
Answer: Shorter URLs reduce the total number of available unique combinations.. Shorter length reduces the keyspace, making collisions more frequent and limiting capacity. Longer keys offer a larger keyspace. Options 0, 1, and 3 are conceptually incorrect.
From lesson: Design URL Shortener
When designing a fan-out strategy, why is 'push-on-write' generally preferred for most users?
Answer: It minimizes the load on the database during read requests.. Push-on-write moves the computational cost to the time of writing, making reads extremely fast (O(1)). Option 1 is wrong because it doesn't reduce storage. Option 2 is wrong because caching is still necessary. Option 3 is wrong because the model doesn't negate the need for persistent storage.
From lesson: Design Twitter / News Feed
How should a system handle the 'Celebrity Problem' in feed generation?
Answer: Pull celebrity tweets at request time while pushing others.. Mixing pull and push models allows the system to remain responsive. Option 0 is wrong because a push model for celebrities creates massive spikes. Option 1 is wrong because batch jobs don't provide real-time updates. Option 3 is wrong because vertical scaling has strict limits.
From lesson: Design Twitter / News Feed
What is the primary benefit of using a distributed key-value store for feed storage?
Answer: It allows for high horizontal scalability and low-latency access.. Distributed key-value stores excel at scaling horizontally and providing low latency, which is essential for feed reads. Option 0 is wrong because feed systems often favor eventual consistency over strict ACID. Option 2 is wrong because ranking is an application layer concern. Option 3 is wrong because data is often intentionally replicated for availability.
From lesson: Design Twitter / News Feed
In a feed system, what is the trade-off of maintaining a 'Feed Cache' per user?
Answer: Lower storage efficiency due to redundancy.. Caching feeds requires storing the same tweet IDs across many user-specific caches, which is redundant. Option 0 is incorrect as writes are usually asynchronous. Option 1 is false because caches hold recent items, not necessarily historical ones. Option 3 is incorrect as the database remains the source of truth.
From lesson: Design Twitter / News Feed
Why is 'request-time merging' inefficient for a global-scale social platform?
Answer: It forces the system to perform heavy aggregation across multiple sources on every read.. Merging feeds during the request involves gathering data from all followed users, which is computationally expensive for high-volume readers. Option 0 is wrong as this happens on the server. Option 2 is wrong because indexes are still usable. Option 3 is wrong because late arrival is a sync issue, not a merging issue.
From lesson: Design Twitter / News Feed
When designing a notification system that must support millions of users, why is introducing a message queue between the notification service and the delivery workers essential?
Answer: To buffer spikes in traffic and allow for asynchronous processing, preventing service crashes.. Option 2 is correct because queues act as a shock absorber for bursty traffic. Option 1 is wrong because synchronous DB updates are the bottleneck we are trying to avoid. Option 3 is wrong because ordering is rarely required for notifications and complicates performance. Option 4 is wrong because queues do not affect storage.
From lesson: Design Notification System
Which strategy is most effective for preventing a user from receiving the same push notification multiple times due to a retry logic failure?
Answer: Assigning a unique event ID to each notification and checking it against a cache before delivery.. Option 3 is correct as it implements idempotency via a unique ID, which is the industry standard. Option 1 doesn't solve duplication. Option 2 is inefficient for large scale. Option 4 is a security check, not a duplicate prevention mechanism.
From lesson: Design Notification System
How should a system handle the 'Rate Limiting' of notifications for a specific user?
Answer: By implementing a per-user bucket in a cache to track and limit notification frequency based on policy.. Option 3 is correct because Redis/distributed caches provide low-latency lookups for rate limiting. Option 1 is wrong because limits must be per-user, not global. Option 2 is poor UX. Option 4 is inefficient and would crash the database under load.
From lesson: Design Notification System
Why is it beneficial to separate the Notification Service into dedicated sub-services for different channels (e.g., Email, SMS, Push)?
Answer: It prevents the system from having a single point of failure and allows independent scaling.. Option 1 is correct because each channel has different latency and third-party API requirements, necessitating independent scaling. Option 2 is false as traffic volume remains the same. Option 3 is incorrect as schemas often differ per channel. Option 4 is false, as queues remain essential for throughput.
From lesson: Design Notification System
When storing 'Notification Templates', what is the main advantage of using an external template engine or database instead of hard-coding messages?
Answer: It allows for dynamic content localization and quick content adjustments without code deployment.. Option 2 is correct because business teams often need to change marketing copy without developer intervention. Option 1 is not the primary benefit. Option 3 is false, as decoupling actually increases complexity. Option 4 has no relationship to templates.
From lesson: Design Notification System
Which data structure is most efficient for finding all 'drivers' within a specific radius of a rider?
Answer: A spatial index like a Quadtree or Geohash. A Quadtree or Geohash allows spatial partitioning, making it easy to query nearby nodes efficiently. A hash map or linked list would require scanning every driver, leading to O(N) complexity which is too slow for millions of users.
From lesson: Design Ride-Sharing (Uber)
When a rider requests a ride, why is it better to use a dedicated 'Matching Service' rather than a standard REST API call?
Answer: Matching needs to handle high-concurrency state transitions and complex proximity filtering. Matching requires maintaining the state of available drivers, filtering by distance, and handling racing requests, which standard REST controllers are not built to orchestrate. REST is just a transport layer, not a business logic coordinator.
From lesson: Design Ride-Sharing (Uber)
How should the system handle the rapid updates of driver location coordinates?
Answer: Buffer updates in a message queue and push to an in-memory store for fast lookups. In-memory stores handle low-latency writes and fast reads needed for 'nearby' queries, while message queues handle the throughput pressure. Direct SQL writes would kill database performance, and batch processing would render the map stale.
From lesson: Design Ride-Sharing (Uber)
Which mechanism ensures that two different riders aren't matched with the same driver simultaneously?
Answer: Distributed locks or atomic compare-and-swap operations on the driver's status. Concurrency control (locks) is required to ensure atomicity during the reservation process. Relying on clients is insecure, and public queues do not account for distance or driver preference.
From lesson: Design Ride-Sharing (Uber)
What is the primary trade-off when using Geohashes for proximity searches?
Answer: Precision vs. Query complexity at grid boundaries. Geohashes can place points that are close to each other into different grid cells if they are near the boundary, necessitating extra queries for neighboring cells. This trade-off between simplicity and boundary handling is the core of spatial indexing.
From lesson: Design Ride-Sharing (Uber)
When designing the video processing pipeline, what is the primary benefit of pre-encoding videos into multiple resolutions and bitrates?
Answer: To enable Adaptive Bitrate Streaming, allowing the player to switch quality based on network conditions. Adaptive Bitrate Streaming allows a seamless experience even if bandwidth fluctuates; the others are incorrect because pre-encoding increases total storage, doesn't handle encryption specifically, and makes CDNs more, not less, necessary.
From lesson: Design Video Streaming (YouTube)
Which of the following describes the most efficient way to handle high-frequency view count updates in a global system?
Answer: Use a distributed cache to aggregate increments and periodically flush them to persistent storage. Caching and batching updates prevents database write contention. The other methods fail due to high latency, database locks, or lack of data integrity.
From lesson: Design Video Streaming (YouTube)
Why is it necessary to split long videos into smaller chunks (e.g., 5-second segments) for streaming?
Answer: To allow the client to request specific segments, enabling fast seeking and dynamic bitrate switching. Chunking is essential for HTTP-based streaming protocols (DASH/HLS) to enable granular control. Caching the whole file is inefficient, codecs work on frames regardless of chunking, and databases are not for blob storage.
From lesson: Design Video Streaming (YouTube)
What is the primary role of a CDN in a video streaming architecture?
Answer: To cache video chunks at edge locations to minimize latency and offload traffic from the origin server. CDNs are for caching content geographically near users. Transcoding, auth, and chat management are handled by dedicated backend microservices, not the CDN.
From lesson: Design Video Streaming (YouTube)
In a distributed storage system for raw video files, what is the advantage of using object storage over a traditional file system on an application server?
Answer: Object storage provides better horizontal scalability and is designed to handle massive volumes of unstructured data. Object storage is highly scalable and suited for static large blobs. The others are false because object storage lacks transactional locks, does not support SQL joins, and does not perform transcoding.
From lesson: Design Video Streaming (YouTube)
When designing a system that requires strict ACID compliance for global financial transactions, which architectural approach is most critical?
Answer: Utilizing a distributed consensus algorithm like Paxos or Raft. Consensus algorithms ensure nodes agree on a single state, vital for ACID, unlike eventual consistency or leaderless replication which prioritize availability. Sharding helps scale but doesn't solve the consistency coordination problem.
From lesson: System Design Interview Tips
What is the primary trade-off when choosing between a push-based and pull-based model for a real-time notification service?
Answer: Push consumes more server-side resources to maintain active connections. Push (like WebSockets) requires keeping connections open, consuming more memory and file descriptors on the server. Pull is less resource-heavy on the server but introduces latency (the polling interval), making it slower for urgent updates.
From lesson: System Design Interview Tips
If your service experiences high latency because of a 'hot shard' in a database, what is the most effective immediate mitigation strategy?
Answer: Implementing application-level caching for the most requested keys. Caching removes load from the database for popular keys. Adding replicas doesn't fix a write-heavy hot shard; switching databases is a long-term architectural change, and synchronous replication would increase latency further.
From lesson: System Design Interview Tips
Why would an engineer choose a Message Queue over a direct API call between two microservices?
Answer: To decouple services and handle traffic spikes through buffering. Message queues allow asynchronous processing and load leveling. Direct API calls are synchronous and fragile during spikes. Queues don't support real-time delivery or replace the need for load balancers at the entry point.
From lesson: System Design Interview Tips
In a system design, what is the specific role of a Circuit Breaker pattern?
Answer: To prevent a failing service from cascading failures to the rest of the system. A circuit breaker stops requests to a failing service after a threshold, preventing resources from being exhausted. It is unrelated to concurrency limits, data compression, or atomic database transactions.
From lesson: System Design Interview Tips
When estimating QPS for a read-heavy service, which factor is most important to adjust for to ensure system stability?
Answer: The peak-to-average traffic ratio. The peak-to-average ratio is critical because systems must handle bursts; options like user count or request size are inputs, but don't define the burst threshold. Geography relates to latency, not QPS capacity directly.
From lesson: Back-of-the-Envelope Estimation
If a system generates 100 terabytes of logs daily, but the policy deletes logs after 30 days, what is the required storage capacity?
Answer: 3 petabytes. 100 TB * 30 days equals 3000 TB, which is exactly 3 petabytes. Option 1 is daily, 1.5 petabytes is half the required capacity, and 3.3 petabytes overestimates due to unnecessary padding.
From lesson: Back-of-the-Envelope Estimation
Which of the following describes the correct approach to estimating the number of database servers needed for a read-heavy application?
Answer: Total QPS / Expected QPS per database node. To size DB nodes, you divide throughput demand by the throughput capability of a single node. Daily requests ignore peak, storage doesn't account for CPU/IO pressure, and concurrent users is a poor proxy for throughput.
From lesson: Back-of-the-Envelope Estimation
Why is it important to use 'power of 2' approximations (e.g., 1 TB = 10^12 bytes) when performing napkin math?
Answer: To simplify calculations while maintaining an acceptable margin of error. Napkin math is for order-of-magnitude correctness; powers of 10 simplify mental math effectively. Other options are incorrect as they confuse architectural requirements with estimation methodology.
From lesson: Back-of-the-Envelope Estimation
When calculating network bandwidth for a distributed system, what is the most critical variable to include?
Answer: The average size of the request and response in bytes. Bandwidth is calculated as (Avg Request Size + Avg Response Size) * RPS. Hardware cost and switches are physical infrastructure details, and header overhead is secondary to the primary payload volume.
From lesson: Back-of-the-Envelope Estimation