Fun with Learning Technology
LearnCoursesQuestionsTracksToolsNewsExplorePractice
Fun with Learning Technology

A new problem, explained clearly, every day.

Subscribe
Learn
  • Lessons
  • Topics
  • News
  • Tools
  • Courses
  • Career tracks
  • Everything
Site
  • About
  • Contact
  • Support
  • Privacy
  • Terms
Get the daily one

One email per new problem. No spam.

Request a tutorial

Requests shape what gets made next.

© 2026 Fun with Learning TechnologyRSS
Home›System Design›Quiz

System Design quiz

Ten questions at a time, drawn from 155. Every answer is explained. Nothing is saved and no account is needed.

Question 1 of 10Score 0

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.

Study first?

Every question comes from a lesson in the System Design course.

Read the course →

Interview prep

Written questions with full answers.

System Design interview questions →

All System Design quiz questions and answers

  1. When defining non-functional requirements, why is it critical to prioritize latency over throughput for a real-time messaging application?

    • High throughput inherently guarantees low latency.
    • User perception of interactivity depends on minimizing the time per individual message delivery.
    • Throughput is irrelevant for small messages.
    • Latency constraints are easier to satisfy than throughput constraints.

    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

  2. A system requires strong consistency for financial transactions but high availability for viewing profiles. How should you approach the data storage strategy?

    • Use a single distributed database with default settings for all data.
    • Force strong consistency on all operations to avoid complex code.
    • Segregate the storage strategy by using different databases or configurations based on data access patterns.
    • Always choose eventual consistency for speed, ignoring financial accuracy.

    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

  3. You are designing a system that must handle sudden traffic spikes. What is the most effective approach to handle this using a load balancer?

    • Increase the hardware capacity of a single server.
    • Use a load balancer to distribute traffic across a pool of auto-scaled instances.
    • Only cache responses to reduce server load.
    • Direct traffic to the database to bypass the application layer.

    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

  4. When performing back-of-the-envelope calculations, what is the primary purpose of estimating the number of concurrent connections?

    • To decide which programming language to use.
    • To determine the bandwidth requirements and necessary load balancer/server capacity.
    • To calculate the total revenue generated by the application.
    • To pick a specific database vendor.

    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

  5. Why is it important to consider the 'read-to-write' ratio when designing a system?

    • It determines if you need a database.
    • It dictates whether read replicas or caching strategies should be prioritized over write-optimization strategies.
    • It dictates the user interface design.
    • It makes data consistency irrelevant.

    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

  6. Which of the following scenarios is best addressed by vertical scaling?

    • A service that experiences unpredictable traffic spikes that vary by 100x throughout the day
    • A legacy monolithic application that cannot run in a distributed environment without major refactoring
    • A highly distributed microservice architecture requiring extreme high availability
    • An application that needs to span multiple geographic regions to reduce latency

    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

  7. What is the primary trade-off when moving from vertical to horizontal scaling in a stateful application?

    • Increased hardware cost per unit
    • Increased complexity in session management and data synchronization
    • Lower maximum capacity limits
    • Decreased flexibility in software deployment

    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

  8. 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?

    • Add more memory to the existing database server
    • Implement a read-replica cluster
    • Implement database sharding or partition the data
    • Increase the network bandwidth of the current node

    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

  9. Why is horizontal scaling often considered more 'resilient' than vertical scaling?

    • It uses higher-quality, server-grade hardware components
    • It eliminates the need for a load balancer entirely
    • It distributes load across multiple independent nodes, avoiding a single point of failure
    • It provides infinite processing power without any configuration overhead

    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

  10. In which case would you choose to NOT horizontally scale your application?

    • When the application must handle millions of concurrent users
    • When the cost of maintaining the orchestration layer outweighs the benefits of extra capacity
    • When you need to provide service in different continents
    • When you want to prevent system outages during individual hardware component failures

    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

  11. Which scenario makes an 'Least Connections' algorithm significantly better than a 'Round Robin' algorithm?

    • When all backend servers have identical hardware specifications.
    • When requests vary significantly in their processing time or computational complexity.
    • When the network latency between the load balancer and servers is uniform.
    • When the system is operating at very low traffic volume.

    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

  12. In a Layer 7 load balancing configuration, what is a primary advantage over Layer 4 balancing?

    • Lower latency due to reduced packet inspection.
    • Ability to route traffic based on URL paths, headers, or content types.
    • Compatibility with non-TCP protocols like raw UDP streams.
    • Significantly lower computational overhead on the load balancer itself.

    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

  13. Why is it dangerous to rely solely on DNS-based load balancing for a highly available production system?

    • DNS servers are not capable of resolving multiple IP addresses.
    • DNS lookups happen too frequently and cause excessive network traffic.
    • DNS caching at the client or ISP level prevents immediate failover when a server goes down.
    • DNS protocols do not support weighted distributions.

    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

  14. How does the 'Session Persistence' (or sticky sessions) feature impact system design?

    • It improves horizontal scalability by distributing traffic perfectly across all nodes.
    • It allows stateless services to run without needing an external database.
    • It reduces the load balancer's CPU usage by offloading hashing to the client.
    • It makes it harder to achieve a balanced distribution if some users have very long-running sessions.

    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

  15. When designing for high availability, what is the purpose of placing a load balancer in front of a cluster of servers?

    • To encrypt all traffic automatically using hardware-based certificates.
    • To provide a single entry point that can route around individual node failures.
    • To convert all incoming traffic to a single protocol like HTTP/2.
    • To act as a primary storage node for distributed file systems.

    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

  16. When implementing a 'Cache-Aside' pattern, what happens during a cache miss?

    • The application fetches data from the database and updates the cache.
    • The cache automatically pulls the latest version from the database.
    • The database pushes the data directly to the cache.
    • The application returns a 404 error to the user.

    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

  17. Which scenario makes Redis a superior choice over Memcached?

    • When you need to store simple key-value strings only.
    • When you require data persistence and complex data structures.
    • When you have a strictly read-only workload with no updates.
    • When you want the absolute lowest memory footprint without advanced features.

    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

  18. What is the primary benefit of placing a CDN in front of your application?

    • It increases the storage capacity of the origin database.
    • It reduces latency by serving static assets from edge locations closer to users.
    • It encrypts all traffic between the user and the origin server.
    • It eliminates the need for any server-side logic in the 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

  19. In a Write-Through caching strategy, which statement is true?

    • The application writes to the cache first, then to the database.
    • The application writes only to the database, and the cache is updated later.
    • Data is written to both the cache and the database synchronously.
    • The application writes to the cache, and the database is updated via a background process.

    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

  20. What is the consequence of a 'Cache Stampede'?

    • The database is overloaded because multiple requests try to regenerate the same expired cache key simultaneously.
    • The cache memory becomes fragmented, leading to performance degradation.
    • The CDN serves outdated content to users indefinitely.
    • The application experiences a timeout while waiting for an external API.

    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

  21. When designing a system that uses a CDN, why is it critical to use versioned filenames (e.g., app.v1.js) for static assets?

    • To ensure the CDN can compress the files better
    • To bypass the browser's cache for security reasons
    • To solve the issue of cache invalidation when content updates
    • To reduce the load on the CDN's control plane

    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)

  22. A system architect decides to use a CDN to cache API responses. Which scenario would make this a poor design choice?

    • The API returns the same public JSON data for every user
    • The API response changes based on the user's authentication token
    • The API is used to serve public images
    • The API is rate-limited by the CDN's edge nodes

    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)

  23. How does a CDN improve the performance of a distributed system?

    • By executing application logic closer to the user
    • By reducing the physical distance between the user and the requested data
    • By replacing the need for load balancers at the origin
    • By encrypting all database traffic automatically

    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)

  24. Which of the following describes the 'Origin Pull' method of populating a CDN cache?

    • The origin server pushes files to the CDN proactively
    • The CDN fetches content from the origin when it receives a request for a file not in its cache
    • Users upload files directly to the CDN instead of the origin server
    • The CDN performs periodic backups of the origin database

    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)

  25. What is the primary benefit of using a CDN to mitigate a DDoS attack?

    • The CDN can eliminate all malicious traffic at the source
    • The CDN distributes the incoming attack traffic across a global network of servers
    • The CDN automatically patches the vulnerability being exploited in the attack
    • The CDN prevents the origin server from needing an IP address

    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)

  26. Which scenario best justifies the selection of a NoSQL document store over a Relational Database?

    • The system requires complex multi-table joins for analytical reporting.
    • The data schema is highly polymorphic and changes frequently.
    • The application requires strict ACID compliance for financial transactions.
    • The dataset has a fixed schema with strong integrity constraints.

    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

  27. 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?

    • A relational database with complex indexing for every field.
    • A wide-column store designed for high-throughput writes.
    • A traditional SQL engine using normalized tables to save storage space.
    • A key-value store with full support for cross-table transactions.

    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

  28. When designing a system that requires high availability and partition tolerance, what is the primary risk of using a traditional single-node SQL database?

    • It lacks support for the SQL query language.
    • It relies on horizontal partitioning for all queries.
    • It presents a single point of failure and scaling bottlenecks.
    • It is fundamentally incapable of supporting ACID properties.

    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

  29. How should a system designer approach data consistency when moving from a monolithic SQL database to a distributed NoSQL architecture?

    • Assume the system will automatically maintain strong consistency across all nodes.
    • Implement application-level logic to handle eventual consistency.
    • Ignore consistency, as performance gains outweigh data integrity.
    • Restrict all operations to a single node to bypass the CAP theorem.

    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

  30. Which characteristic of a system would strongly favor a SQL database despite the presence of high traffic?

    • The need for frequent updates to complex, interconnected entities.
    • The requirement to store massive amounts of unstructured blobs.
    • A preference for eventual consistency to ensure system availability.
    • A requirement for dynamic schema evolution at runtime.

    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

  31. When configuring a primary-replica architecture, why might an application choose asynchronous replication over synchronous replication?

    • To ensure all replicas have the most current data at all times.
    • To prevent any potential data loss during a primary node failure.
    • To minimize the latency impact on write operations.
    • To simplify the logic required for conflict resolution.

    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

  32. What is the primary risk associated with a 'split-brain' scenario in a multi-master replication setup?

    • Increased read latency due to heavy traffic on the secondary nodes.
    • Inconsistency caused by different nodes accepting conflicting writes.
    • Complete loss of data across all shards in the database cluster.
    • An infinite loop of replication traffic between the master nodes.

    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

  33. Which strategy best addresses the problem of stale reads in a system using asynchronous replication?

    • Routing all read requests exclusively to the primary node.
    • Implementing a cache-aside pattern on top of the replicas.
    • Forcing the application to wait for an acknowledgment from all nodes.
    • Using read-your-writes consistency logic at the application layer.

    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

  34. In a Leader-Follower replication model, what is the effect of increasing the number of followers?

    • The system's write throughput capacity increases linearly.
    • The load on the primary node is significantly reduced for read-heavy workloads.
    • The time taken to elect a new leader during a failure is eliminated.
    • The likelihood of data conflicts during concurrent write operations is reduced.

    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

  35. Why is it dangerous to perform an automated failover without a consensus-based monitoring system?

    • It leads to excessive storage consumption on replica nodes.
    • It can trigger an accidental shutdown of the entire database cluster.
    • It may mistakenly promote a healthy node to leader while the old leader is still functioning.
    • It forces the system to switch to a write-only mode temporarily.

    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

  36. Which of the following scenarios is most appropriate for using range-based partitioning instead of hash-based partitioning?

    • When you need to ensure perfectly uniform load distribution across all nodes.
    • When the application frequently queries data within specific chronological intervals.
    • When the sharding key has extremely high cardinality.
    • When you want to avoid hotspots for popular data items.

    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

  37. When implementing a service that requires frequent cross-shard joins for analytics, what is the best strategy?

    • Increase the number of shards to parallelize the join operation.
    • Use a global index to track which shards contain specific records.
    • Denormalize the data to store related entities on the same shard.
    • Perform all joins on the application tier regardless of dataset size.

    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

  38. What is a primary advantage of using Consistent Hashing for sharding?

    • It eliminates the need for a load balancer in front of the database cluster.
    • It ensures that a database record is always stored on exactly one shard.
    • It minimizes the amount of data that needs to be remapped when adding or removing shards.
    • It provides built-in support for ACID transactions across multiple shards.

    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

  39. Why is it dangerous to shard a database by a non-immutable field like 'status' or 'last_login_date'?

    • Because these fields often contain null values which are not allowed in sharding.
    • Because changing the field value would necessitate moving data across physical shard boundaries.
    • Because these fields are not indexed, making initial data placement impossible.
    • Because these fields usually have too many unique values to create balanced partitions.

    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

  40. What occurs when a system experiences 'hotspotting' due to a sharding key choice?

    • Data is perfectly distributed, but the latency is high due to disk speed.
    • One specific node experiences significantly higher traffic than others, leading to a performance bottleneck.
    • The system crashes because the sharding key does not exist on some records.
    • The system becomes unreachable because the hashing function has a collision.

    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

  41. 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?

    • Strong Consistency
    • Eventual Consistency
    • Strict Ordering
    • Linearizability

    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

  42. Why is it impossible to have a truly CA system in a distributed environment?

    • Network latency is always too high to coordinate updates.
    • Hardware failures are inevitable in large clusters.
    • Network partitions are a reality of distributed communication that cannot be ignored.
    • Database throughput drops to zero if consistency is maintained.

    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

  43. 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?

    • Availability
    • Partition Tolerance
    • Latency
    • Throughput

    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

  44. In a CP system, what happens when a network partition occurs between the leader and follower nodes?

    • The system switches to an AP mode automatically.
    • The system allows writes to the leader but blocks reads on followers.
    • The system stops accepting operations that would compromise consistency.
    • The system replicates data asynchronously to maintain speed.

    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

  45. Which scenario best describes a system prioritizing Availability (A) over Consistency (C)?

    • Returning an error message if the database is not in sync.
    • Requiring all nodes to acknowledge a write before completion.
    • Serving cached data from a local node even if it is out of date.
    • Ensuring the system shuts down if the consensus quorum is lost.

    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

  46. A table has a composite index on (last_name, first_name). Which query will effectively utilize this index?

    • SELECT * FROM users WHERE first_name = 'John'
    • SELECT * FROM users WHERE last_name = 'Doe'
    • SELECT * FROM users WHERE email = 'test@example.com'
    • SELECT * FROM users WHERE last_name = 'Doe' AND age = 25

    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

  47. Why does adding too many indexes to a high-throughput write-heavy system lead to performance degradation?

    • The indexes consume too much RAM during read operations.
    • The database must lock the entire table whenever a row is read.
    • Every write operation requires a corresponding update to each index structure.
    • Indexes cause the query optimizer to choose a random execution plan.

    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

  48. When is it optimal to use a covering index?

    • When the query needs to modify large amounts of data.
    • When all columns in the SELECT clause are present in the index.
    • When the table contains millions of rows of text data.
    • When the table has no primary key defined.

    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

  49. What is the primary trade-off of creating a B-Tree index on a column?

    • Decreased disk space usage and faster write speeds.
    • Faster read performance for point queries at the cost of slower write performance.
    • Unlimited horizontal scaling of the database server.
    • Automatic conversion of all queries into join operations.

    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

  50. Which scenario makes a database index highly ineffective?

    • Using a high-cardinality column in an equality filter.
    • Querying a small subset of rows from a large table.
    • Searching for a value in a column where every entry is identical.
    • Joining two tables on their primary key columns.

    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

  51. When designing a system with deep, highly relational data structures that change frequently, which approach best minimizes round-trips?

    • RESTful API with HATEOAS
    • GraphQL with nested queries
    • gRPC with unary calls
    • REST with expanded query parameters

    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

  52. Why would an architect choose gRPC over REST for communication between microservices within a private data center?

    • Better support for human-readable debugging
    • Native browser compatibility without proxies
    • Efficient binary serialization and multiplexing
    • Automatic generation of RESTful documentation

    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

  53. Which trade-off is inherent when moving from REST to GraphQL?

    • Increased complexity in server-side request parsing and authorization
    • Improved ease of implementing standard HTTP caching
    • Strict enforcement of resource naming conventions
    • Automatic reduction in payload size for all endpoints

    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

  54. 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?

    • gRPC
    • GraphQL
    • REST
    • Binary WebSocket

    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

  55. What is the primary benefit of using Protobufs in a gRPC-based architecture compared to JSON-based REST?

    • Ability to include logic within the data object
    • Stronger contract enforcement through schema compilation
    • Support for caching responses in traditional CDNs
    • Ability to view request payloads in raw text format

    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

  56. When designing a system requiring strict message ordering per user across multiple instances, which strategy is most effective in a Kafka-based architecture?

    • Use a single consumer instance to read from all partitions
    • Use the user ID as the partition key
    • Implement a global lock in a distributed cache
    • Enable idempotent writes on the consumer side

    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

  57. Which scenario best justifies using RabbitMQ over Kafka?

    • Implementing a high-throughput event streaming platform
    • Replaying messages from a specific point in history
    • Need for complex routing logic using direct, topic, or fanout exchanges
    • Storing events for long-term audit logs

    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

  58. In a distributed task queue system, what is the primary consequence of failing to implement 'at-least-once' delivery with consumer acknowledgments?

    • Increased system latency
    • Duplicate message processing
    • Data loss during consumer crashes
    • Partition rebalancing issues

    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

  59. A system design requires processing millions of events per second with low retention requirements. What is the most critical factor to consider?

    • Number of total messages in the queue
    • Disk I/O throughput and partition count
    • The number of consumer groups
    • The size of individual message payloads

    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

  60. Why is it often recommended to use a Dead Letter Queue (DLQ) in system design?

    • To increase the speed of primary message processing
    • To offload long-running tasks to a background worker
    • To handle and inspect messages that fail processing after multiple retries
    • To balance the load between producers and consumers

    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

  61. When designing an event-driven system, why is it critical for consumers to be idempotent?

    • To ensure all events are processed in parallel
    • To handle the reality of 'at-least-once' message delivery
    • To reduce the network overhead between producers and brokers
    • To eliminate the need for an external database

    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

  62. Which of the following describes the primary benefit of the Saga pattern in an event-driven architecture?

    • Replacing the need for a message broker
    • Ensuring immediate strong consistency across services
    • Managing distributed transactions via a series of local steps
    • Converting asynchronous event streams into synchronous REST calls

    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

  63. What is the primary architectural trade-off when choosing 'Event-Carried State Transfer' over 'Request-Response' for data synchronization?

    • Increased coupling between service schemas
    • Decreased system availability during consumer downtime
    • Higher complexity in managing eventual consistency
    • Reduced performance due to message serialization

    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

  64. In a high-throughput event streaming system, how can you ensure related events are processed in the correct order?

    • By setting the consumer concurrency to exactly one
    • By using a partition key based on the entity ID
    • By enforcing a global transaction lock on the message broker
    • By implementing a request-response handshake after every message

    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

  65. What is the main danger of using a message broker as an 'event store' without a dedicated log-based storage mechanism?

    • The message broker cannot handle binary data payloads
    • Lack of persistence and replayability for new consumers
    • Increased latency for message producers
    • Inability to scale horizontally

    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

  66. 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?

    • HTTP Long Polling
    • WebSockets
    • RESTful API polling
    • Server-Sent Events

    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

  67. Which scenario most justifies the use of Long Polling over WebSockets?

    • A low-latency collaborative drawing application.
    • A real-time multiplayer gaming backend.
    • A notification system where messages are infrequent and connectivity is unreliable.
    • A real-time high-frequency financial trading dashboard.

    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

  68. What is the primary technical challenge when scaling a WebSocket-based application across multiple server instances?

    • The overhead of the HTTP Upgrade handshake.
    • The browser's limit on concurrent connections per domain.
    • The inability to route messages between different server nodes.
    • The serialization format of the message payload.

    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

  69. In a Long Polling system, what happens if the server does not have data when the client's request arrives?

    • The server returns a 404 Not Found error.
    • The server keeps the request open until new data is available or a timeout occurs.
    • The server immediately returns an empty response to the client.
    • The server closes the connection and signals the client to wait 5 seconds.

    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

  70. Why is the HTTP Upgrade header critical for establishing a WebSocket connection?

    • It switches the protocol from HTTP to a persistent TCP-based binary protocol.
    • It forces the client to use a secure encrypted connection.
    • It increases the maximum packet size for the connection.
    • It allows the load balancer to bypass firewall rules.

    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

  71. When designing a distributed rate limiter using Redis, which operation is critical to ensure atomicity?

    • Reading the counter then writing it back as two separate steps
    • Using a Lua script or Redis transaction to perform the read-increment-check sequence
    • Configuring the application server to lock the database row during the check
    • Sending a signal to all instances to update their local counters simultaneously

    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

  72. Why is the Sliding Window Log algorithm often avoided for high-traffic systems despite its accuracy?

    • It is too complex to implement compared to fixed window
    • It requires significant memory to store timestamps for every request
    • It fails to provide accurate results during peak hours
    • It cannot be implemented with distributed caches

    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

  73. 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?

    • Fixed window counter
    • Token bucket
    • Leaky bucket
    • Hard blocking of IP addresses

    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

  74. A user's request is blocked by a rate limiter. What is the most standard architectural pattern to communicate this to the client?

    • Returning a 503 Service Unavailable status code
    • Closing the TCP connection immediately without response
    • Returning a 429 Too Many Requests status code with a Retry-After header
    • Silently discarding the request to prevent malicious detection

    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

  75. How does implementing rate limiting at the API Gateway level compare to implementing it within each microservice?

    • Gateway limiting is more granular but introduces higher latency per request
    • Microservice-level limiting is always more performant than a central gateway
    • Gateway limiting provides a centralized, consistent policy enforcement but lacks service-specific context
    • There is no difference in performance or policy control between these two patterns

    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

  76. When is it appropriate to decompose a modular monolith into microservices?

    • When the team wants to use multiple programming languages
    • When development velocity is hampered by the coupling of independent domain features
    • When the application needs to run on a cloud-native platform
    • When the application reaches a certain number of lines of code

    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

  77. What is the primary benefit of the Database-per-Service pattern in a microservices architecture?

    • It improves read performance by reducing join complexity
    • It ensures strict consistency across all system data
    • It enforces loose coupling by preventing services from accessing each other's underlying data schemas
    • It simplifies the implementation of distributed transactions

    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

  78. Why is 'Choreography' often preferred over 'Orchestration' for long-running business processes in complex microservice systems?

    • It makes the business logic easier to trace and visualize
    • It removes the central point of failure and reduces coupling between the coordinating service and participants
    • It guarantees transactional atomicity across all involved services
    • It requires less configuration for monitoring and observability

    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

  79. A system experiences a 'cascading failure' when one service is overloaded. Which pattern best mitigates this issue?

    • The Saga Pattern
    • The Circuit Breaker Pattern
    • The Database-per-Service Pattern
    • The Sidecar Pattern

    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

  80. In a distributed microservices environment, how is data consistency typically managed when a business process spans multiple services?

    • Using 2-Phase Commit (2PC) protocols across all services
    • Accepting eventual consistency through techniques like Sagas and compensating transactions
    • Enforcing synchronous ACID compliance at the API gateway layer
    • Merging the involved services into a single process to maintain atomic updates

    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

  81. 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?

    • Implementing a single monolithic gateway that handles all routing logic.
    • Deploying multiple Backend for Frontend (BFF) gateways tailored to each client.
    • Exposing all microservices directly to the public internet for client access.
    • Using a shared database to store all client-specific request schemas.

    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

  82. What is the primary architectural purpose of placing a circuit breaker inside an API Gateway during a service degradation event?

    • To increase the processing power of the downstream microservices.
    • To automatically switch to a different database vendor.
    • To stop sending requests to a failing service, preventing resource exhaustion.
    • To encrypt traffic between the gateway and the backend services.

    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

  83. Which of the following describes the most efficient way to handle authorization at an API Gateway?

    • The gateway performs a database lookup on every request to verify user permissions.
    • The gateway validates a cryptographically signed token locally and checks scopes.
    • The gateway redirects the user to the auth server for every single API call.
    • The gateway trusts all incoming requests without checking headers.

    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

  84. If an API Gateway is experiencing high latency, what is the most appropriate action to evaluate its impact on the internal service network?

    • Adding more memory to the internal services.
    • Analyzing the gateway's request queuing and total duration per downstream service call.
    • Implementing a cache for all POST requests to reduce processing load.
    • Increasing the number of microservice instances indefinitely.

    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

  85. How does the API Gateway improve system security via 'Request Stripping'?

    • By removing sensitive internal headers or metadata before forwarding requests to the public client.
    • By deleting all request parameters to ensure no data reaches the backend.
    • By blocking all requests that contain JSON formatted payloads.
    • By forcing all internal microservices to use the same private IP address.

    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

  86. What is the primary design goal of the Circuit Breaker pattern in a distributed architecture?

    • To increase the processing capacity of the downstream service
    • To prevent a fault in one service from cascading to others
    • To enforce strict data consistency across all microservices
    • To automatically scale up server resources during traffic spikes

    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

  87. When a circuit is in the 'Open' state, how should the system behave when a new request arrives?

    • It should wait for a timeout before returning an error
    • It should attempt to call the downstream service anyway
    • It should immediately execute a fallback mechanism or return an error
    • It should queue the request until the service recovers

    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

  88. Why is it important to include a 'Half-Open' state in the circuit breaker state machine?

    • To allow the system to slowly throttle traffic back to normal levels
    • To perform a health check on the downstream service without overwhelming it
    • To force the service to restart if it is still unresponsive
    • To bypass the circuit breaker entirely for administrative traffic

    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

  89. A service has a circuit breaker with a high failure threshold. What is the most likely consequence during a partial outage?

    • The system will suffer from high latency as it repeatedly attempts to contact the failing service
    • The system will recover instantly once the service is fixed
    • The system will be overly sensitive and trip the breaker for minor issues
    • The system will correctly identify the issue and immediately initiate a rollback

    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

  90. Which scenario best justifies implementing a Circuit Breaker pattern?

    • A service that performs heavy read/write operations to a local database
    • Two services that communicate synchronously over a network
    • A batch processing system running on a single server
    • A frontend application that requires low-latency rendering

    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

  91. What is the primary architectural benefit of separating the read and write models in CQRS?

    • Eliminating the need for a database
    • Allowing independent scaling and optimization of read and write workloads
    • Ensuring that all data remains strictly consistent across the system
    • Automatically simplifying the application code structure

    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

  92. In an Event Sourced system, why is the 'Event Store' considered the single source of truth?

    • Because it is easier to index for search queries than relational tables
    • Because it stores the current state of an object in a JSON blob
    • Because the current application state is derived solely by replaying historical events
    • Because it provides the lowest possible latency for read requests

    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

  93. When is Event Sourcing most appropriate for a system design?

    • When you need a full audit trail and the ability to travel back in time to state
    • When the system is a simple web form with one user interaction
    • When you need the simplest implementation path with minimal infrastructure
    • When all your read queries require transactional 'read-your-writes' consistency

    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

  94. How should a projection handler manage the risk of message delivery failures?

    • By rolling back the entire event store to the last known good state
    • By implementing retries with idempotency checks to ensure events are processed exactly once
    • By skipping the failed event and logging it to the user
    • By switching the system to synchronous updates immediately upon failure

    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

  95. Why is 'Eventual Consistency' an inherent characteristic of CQRS/Event Sourcing?

    • Because the read model is updated asynchronously after the write model processes the event
    • Because event stores are inherently slow and cannot keep up with writes
    • Because it is required to prevent data loss in the write model
    • Because database vendors mandate it for all distributed systems

    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

  96. When is the Saga pattern preferred over a distributed transaction with Two-Phase Commit (2PC)?

    • When you require strict ACID compliance and zero visibility of intermediate states.
    • When the microservices are owned by a single team and share a single database.
    • When the system must maintain high availability and avoid long-lived database locks across services.
    • When the transaction involves a small number of services that share the same network segment.

    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

  97. What is the primary purpose of a compensating transaction in a Saga?

    • To commit the local database changes permanently once the entire Saga succeeds.
    • To revert or undo the changes made by a previously successful local transaction if a later step fails.
    • To retry the failed local transaction until it eventually succeeds.
    • To inform the end-user that the system is experiencing a latency-related delay.

    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

  98. How should a service handle a scenario where a compensating transaction itself fails?

    • Ignore the failure and proceed with the rest of the Saga.
    • Immediately roll back the entire system to a previous snapshot.
    • Retry the compensation indefinitely or alert an operator to intervene.
    • Automatically trigger a new forward-moving transaction to fix the state.

    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

  99. In an Orchestration-based Saga, what is the role of the orchestrator?

    • To store the persistent state of the Saga and explicitly tell each participant which local transaction to execute.
    • To allow services to communicate asynchronously without knowledge of the business process flow.
    • To act as a gateway that validates all user authentication tokens before the Saga starts.
    • To monitor network traffic and optimize the routing of event packets between services.

    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

  100. Why is 'Lack of Isolation' a significant concern in Sagas?

    • Because transactions are executed sequentially, causing high latency.
    • Because other concurrent processes might read or modify data that is part of an ongoing, uncommitted Saga.
    • Because compensating transactions are forced to use locks to ensure safety.
    • Because Sagas cannot integrate with message queues for event propagation.

    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

  101. A system manager decides to move from 99.9% availability to 99.99%. What is the most significant operational shift they must prepare for?

    • Replacing all server hardware annually
    • Implementing automated failover and significantly reducing manual intervention
    • Moving the entire infrastructure to a single geographical region for speed
    • Reducing the frequency of log backups to prioritize compute speed

    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%

  102. If a system has an availability requirement of 99.99%, what is the most critical architectural requirement regarding its dependencies?

    • All components must be deployed in the same rack to reduce latency
    • Dependencies must be synchronously coupled to ensure data consistency
    • Dependencies must be decoupled so that a failure in one does not cause a total system outage
    • All dependencies must be monitored manually by human operators

    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%

  103. Why does moving from 99.9% to 99.99% availability usually involve an exponential increase in budget?

    • Because hardware vendors charge more for '99.99%' branded equipment
    • Because human-in-the-loop processes must be replaced by sophisticated, tested automation and multi-region redundancy
    • Because the cooling costs for data centers increase as availability targets rise
    • Because licensing fees for monitoring software scale linearly with availability

    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%

  104. When designing for 99.99% availability, what is the role of a 'Circuit Breaker' pattern?

    • To physically cut power to faulty servers during a fire
    • To prevent a failing service from exhausting resources and causing a system-wide blackout
    • To ensure that the system never goes down for maintenance
    • To encrypt traffic between microservices to ensure data security

    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%

  105. Which of the following scenarios best justifies targeting 99.99% availability over 99.9%?

    • A internal company tool used once a week by the marketing team
    • A personal blog that receives traffic only during the day
    • A global payment processing gateway where outages result in direct revenue loss and customer attrition
    • A prototyping environment used by developers to test new features

    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%

  106. A microservice cluster experiences latency spikes in a downstream dependency. Which strategy best exemplifies graceful degradation?

    • Returning a cached stale response or a default value instead of failing the request.
    • Increasing the timeout threshold to ensure the request eventually completes.
    • Terminating all active connections to the downstream service to clear the buffer.
    • Performing a rolling restart of all nodes to reset the network stack.

    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

  107. In a distributed system, what is the primary role of the Circuit Breaker pattern?

    • To encrypt all traffic between services to ensure fault-tolerant communication.
    • To prevent a request from hitting a failing service repeatedly, allowing it time to recover.
    • To balance the load equally across all nodes to ensure no single node hits a fault condition.
    • To automatically trigger a failover to a disaster recovery region if latency increases by 5ms.

    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

  108. Why is 'jitter' combined with 'exponential backoff' during retries?

    • To ensure the system logs the failure timestamp with high precision.
    • To prevent a 'thundering herd' problem where many clients retry simultaneously.
    • To reduce the cryptographic overhead required for secure retry communication.
    • To prioritize traffic from high-paying users during a system degradation event.

    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

  109. Which scenario indicates a system is failing to degrade gracefully?

    • The system disables profile picture rendering when the image service is slow.
    • The entire website returns a 500 internal server error because the recommendation engine is down.
    • The system switches from a primary database to a read-only secondary node.
    • The system throttles API requests from non-authenticated users during a traffic surge.

    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

  110. Which design choice best supports fault tolerance in an asynchronous task processing system?

    • Storing tasks in a volatile memory queue to ensure low-latency processing.
    • Implementing idempotent consumers so tasks can be safely retried without side effects.
    • Using a single master node to coordinate all task distribution to avoid consistency issues.
    • Eliminating all logging to maximize the CPU available for task execution.

    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

  111. Which approach best describes the 'Golden Signals' methodology in observability?

    • Focusing strictly on infrastructure CPU, memory, and disk usage.
    • Prioritizing latency, traffic, errors, and saturation.
    • Alerting on every single service failure immediately.
    • Tracking developer commit frequency and build times.

    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

  112. When designing a distributed system, why is distributed tracing superior to simple log aggregation for troubleshooting?

    • It generates less data than logs.
    • It provides a complete visualization of a request's path across service boundaries.
    • It allows for direct modification of service configuration files.
    • It completely replaces the need for metric dashboards.

    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

  113. What is the primary danger of setting alerts based solely on average CPU utilization across a cluster?

    • It is too cheap to monitor.
    • It masks individual node failures or 'hot spots' through aggregation.
    • It generates too few alerts for engineers to react to.
    • It causes the database to perform slower.

    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

  114. Why is 'High Cardinality' a critical factor when choosing a metrics database?

    • It allows for better compression of static configuration data.
    • It enables deep slicing and dicing of metrics by unique attributes like UserID or RequestID.
    • It guarantees that the system will never experience latency.
    • It increases the total number of physical servers needed.

    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

  115. In the context of System Design, what is the 'Error Budget' used for?

    • To define the exact number of dollars saved by preventing downtime.
    • To balance the need for rapid feature deployment with system reliability.
    • To calculate the total cost of cloud infrastructure monitoring tools.
    • To determine how many engineers should be on call.

    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

  116. An architect is evaluating a strategy to achieve the lowest possible RPO for a global database. Which approach should be prioritized?

    • Daily incremental backups to object storage
    • Synchronous data replication across multiple availability zones
    • Asynchronous snapshots taken every hour
    • Cold storage archival of transaction logs

    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

  117. What is the primary trade-off when selecting an Active-Active multi-region disaster recovery architecture compared to a Pilot Light strategy?

    • Active-Active is significantly cheaper to operate
    • Pilot Light provides lower latency for write operations
    • Active-Active requires higher application complexity to handle data consistency
    • Pilot Light ensures faster failover than Active-Active

    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

  118. Which of the following scenarios best justifies the use of 'Warm Standby' over 'Backup and Restore'?

    • The system has very relaxed RTO requirements
    • The system requires immediate traffic redirection with minimal downtime upon failure
    • The data is non-critical and rarely accessed
    • Budget constraints are the only factor in the architectural choice

    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

  119. When designing for disaster recovery, how does the RPO metric influence storage selection?

    • Lower RPO mandates frequent snapshot frequency or continuous replication mechanisms
    • Higher RPO mandates the use of expensive solid-state storage
    • RPO dictates the physical location of the server racks
    • RPO determines the security encryption standards of the backup

    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

  120. Why is 'versioning' a critical component of a robust backup strategy in modern cloud-native systems?

    • It increases the total storage capacity available to users
    • It allows recovery from accidental deletions or application-level data corruption
    • It ensures that all backups are immediately indexed for fast search
    • It replaces the need for geographic redundancy

    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

  121. When designing a URL shortener that requires support for a massive number of links and high availability, which storage strategy is most scalable?

    • Use a single monolithic relational database with no horizontal sharding.
    • Use a NoSQL Key-Value store partitioned by the short URL key.
    • Store all mappings in a distributed file system to maximize disk space.
    • Rely entirely on in-memory storage for all historical link data.

    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

  122. What is the primary benefit of using Base-62 encoding (0-9, a-z, A-Z) for generating short URLs?

    • It provides cryptographic security against link tampering.
    • It maximizes the number of possible unique URLs for a fixed length of characters.
    • It ensures that every URL generated is globally unique across all databases.
    • It compresses the actual content of the destination URL to save space.

    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

  123. If a system uses a counter-based approach to generate unique keys for URLs, what is a potential challenge in a distributed environment?

    • The counter might produce duplicate keys if multiple servers increment it simultaneously.
    • Base-62 encoding cannot process numerical values larger than 32-bit integers.
    • Counter-based approaches are too slow compared to UUID generation.
    • The system will fail to generate shorter URLs as time progresses.

    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

  124. Why is it recommended to add a caching layer specifically between the application and the database for this system?

    • To perform real-time analysis of user demographics for every redirect.
    • To minimize the latency of the redirect process by serving popular links from RAM.
    • To encrypt URLs before they are written to the main database.
    • To act as a persistent backup for all shortened URL links.

    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

  125. In a system design scenario, what is the trade-off of choosing a shorter 'short URL' length?

    • Shorter URLs provide better security against brute-force guessing.
    • Shorter URLs require more database storage space.
    • Shorter URLs reduce the total number of available unique combinations.
    • Shorter URLs make the system immune to network congestion.

    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

  126. When designing a fan-out strategy, why is 'push-on-write' generally preferred for most users?

    • It minimizes the load on the database during read requests.
    • It reduces the amount of storage required for the system.
    • It eliminates the need for a cache layer entirely.
    • It simplifies the schema requirements for relational databases.

    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

  127. How should a system handle the 'Celebrity Problem' in feed generation?

    • Ignore the user's follower count and use a single approach.
    • Force celebrity updates to happen via background batch jobs only.
    • Pull celebrity tweets at request time while pushing others.
    • Increase the hardware capacity of a single shard for celebrities.

    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

  128. What is the primary benefit of using a distributed key-value store for feed storage?

    • It enforces strict ACID compliance for all operations.
    • It allows for high horizontal scalability and low-latency access.
    • It automatically optimizes the ranking algorithm for the user.
    • It prevents data duplication across the cluster.

    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

  129. In a feed system, what is the trade-off of maintaining a 'Feed Cache' per user?

    • Increased write latency for post creation.
    • Decreased availability of historical tweets.
    • Lower storage efficiency due to redundancy.
    • Elimination of the need for a persistent database.

    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

  130. Why is 'request-time merging' inefficient for a global-scale social platform?

    • It requires high memory overhead on the client device.
    • It forces the system to perform heavy aggregation across multiple sources on every read.
    • It prevents the use of database indexes.
    • It results in data loss for tweets that arrive late.

    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

  131. 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?

    • To ensure the database is always updated before the user receives the message.
    • To buffer spikes in traffic and allow for asynchronous processing, preventing service crashes.
    • To guarantee that every message is delivered in the exact order it was generated.
    • To reduce the storage requirement of the Notification Template Service.

    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

  132. Which strategy is most effective for preventing a user from receiving the same push notification multiple times due to a retry logic failure?

    • Increasing the timeout duration on the push gateway client.
    • Using a distributed lock to ensure only one thread reads the message from the queue.
    • Assigning a unique event ID to each notification and checking it against a cache before delivery.
    • Validating the user's login status before every notification attempt.

    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

  133. How should a system handle the 'Rate Limiting' of notifications for a specific user?

    • By enforcing a global limit on the number of notifications sent across the entire platform.
    • By dropping all messages once a user reaches their daily quota.
    • By implementing a per-user bucket in a cache to track and limit notification frequency based on policy.
    • By asking the database to perform a count query before every single dispatch.

    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

  134. Why is it beneficial to separate the Notification Service into dedicated sub-services for different channels (e.g., Email, SMS, Push)?

    • It prevents the system from having a single point of failure and allows independent scaling.
    • It reduces the amount of total network traffic generated.
    • It allows all services to share the same database schema for consistency.
    • It eliminates the need for a message queue.

    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

  135. When storing 'Notification Templates', what is the main advantage of using an external template engine or database instead of hard-coding messages?

    • It improves the performance of the rendering engine.
    • It allows for dynamic content localization and quick content adjustments without code deployment.
    • It makes the system fully synchronous and easier to debug.
    • It ensures that users always receive messages in the exact order they were sent.

    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

  136. Which data structure is most efficient for finding all 'drivers' within a specific radius of a rider?

    • A linked list sorted by driver ID
    • A hash map containing all active driver locations
    • A spatial index like a Quadtree or Geohash
    • A relational table indexed only by driver name

    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)

  137. When a rider requests a ride, why is it better to use a dedicated 'Matching Service' rather than a standard REST API call?

    • REST APIs are only used for mobile apps, not backend services
    • Matching needs to handle high-concurrency state transitions and complex proximity filtering
    • REST APIs cannot return JSON objects to the client
    • Matching services automatically guarantee payment completion

    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)

  138. How should the system handle the rapid updates of driver location coordinates?

    • Update the master SQL database on every GPS movement
    • Buffer updates in a message queue and push to an in-memory store for fast lookups
    • Write updates to a batch processing log that runs every hour
    • Have the mobile client update the driver's profile in the user-management service

    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)

  139. Which mechanism ensures that two different riders aren't matched with the same driver simultaneously?

    • HTTP redirect to the driver's phone
    • Distributed locks or atomic compare-and-swap operations on the driver's status
    • Client-side random wait times to avoid collisions
    • Using a public queue where the first rider to click wins

    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)

  140. What is the primary trade-off when using Geohashes for proximity searches?

    • Precision vs. Query complexity at grid boundaries
    • Encryption speed vs. decryption speed
    • Network latency vs. local storage size
    • Memory usage vs. CPU clock speed

    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)

  141. When designing the video processing pipeline, what is the primary benefit of pre-encoding videos into multiple resolutions and bitrates?

    • To reduce the total storage space occupied by the raw video file
    • To enable Adaptive Bitrate Streaming, allowing the player to switch quality based on network conditions
    • To ensure the video can be encrypted before being moved to the CDN
    • To eliminate the need for a Content Delivery Network entirely

    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)

  142. Which of the following describes the most efficient way to handle high-frequency view count updates in a global system?

    • Increment the value directly in the primary relational database with each view event
    • Use a distributed cache to aggregate increments and periodically flush them to persistent storage
    • Send every view event through a synchronous REST API call to the metadata service
    • Store the view count only on the client side to minimize server-side state

    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)

  143. Why is it necessary to split long videos into smaller chunks (e.g., 5-second segments) for streaming?

    • To ensure the browser can cache the entire video file locally before playing
    • To reduce the compression overhead of the video codec
    • To allow the client to request specific segments, enabling fast seeking and dynamic bitrate switching
    • To make it easier to upload the file to a relational database

    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)

  144. What is the primary role of a CDN in a video streaming architecture?

    • To perform heavy transcoding operations before the video is stored
    • To provide a backup of the user's authentication and account profile data
    • To cache video chunks at edge locations to minimize latency and offload traffic from the origin server
    • To handle user comments and real-time chat during live streaming

    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)

  145. 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?

    • Object storage supports ACID transactions, which are required for video editing
    • Object storage provides better horizontal scalability and is designed to handle massive volumes of unstructured data
    • Object storage allows for real-time querying of video frames using complex SQL joins
    • Object storage automatically transcodes video files into different formats upon upload

    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)

  146. When designing a system that requires strict ACID compliance for global financial transactions, which architectural approach is most critical?

    • Implementing eventual consistency across all database nodes
    • Utilizing a distributed consensus algorithm like Paxos or Raft
    • Sharding the database horizontally based on user ID
    • Using a leaderless replication architecture

    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

  147. What is the primary trade-off when choosing between a push-based and pull-based model for a real-time notification service?

    • Push consumes more server-side resources to maintain active connections
    • Pull ensures faster delivery of urgent messages
    • Push requires the client to handle exponential backoff logic
    • Pull is inherently more scalable due to reduced connection overhead

    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

  148. If your service experiences high latency because of a 'hot shard' in a database, what is the most effective immediate mitigation strategy?

    • Increasing the read-replica count globally
    • Switching from a relational database to a NoSQL store
    • Implementing application-level caching for the most requested keys
    • Enabling synchronous replication to all nodes

    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

  149. Why would an engineer choose a Message Queue over a direct API call between two microservices?

    • To ensure the request is processed in real-time
    • To enforce synchronous execution across services
    • To decouple services and handle traffic spikes through buffering
    • To eliminate the need for load balancing

    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

  150. In a system design, what is the specific role of a Circuit Breaker pattern?

    • To limit the total number of concurrent users
    • To prevent a failing service from cascading failures to the rest of the system
    • To compress data packets to reduce network bandwidth
    • To ensure all database transactions are rolled back upon failure

    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

  151. When estimating QPS for a read-heavy service, which factor is most important to adjust for to ensure system stability?

    • The total number of global users
    • The peak-to-average traffic ratio
    • The average size of a single request
    • The geographical location of the servers

    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

  152. If a system generates 100 terabytes of logs daily, but the policy deletes logs after 30 days, what is the required storage capacity?

    • 100 terabytes
    • 1.5 petabytes
    • 3 petabytes
    • 3.3 petabytes

    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

  153. Which of the following describes the correct approach to estimating the number of database servers needed for a read-heavy application?

    • Total Daily Requests / 86400
    • Total QPS / Expected QPS per database node
    • Total Storage / Disk size per node
    • Number of concurrent users / Network bandwidth

    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

  154. Why is it important to use 'power of 2' approximations (e.g., 1 TB = 10^12 bytes) when performing napkin math?

    • To ensure code compatibility with binary-based architectures
    • To simplify calculations while maintaining an acceptable margin of error
    • Because storage hardware is strictly marketed in binary units
    • To avoid overflow errors in the calculation tool

    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

  155. When calculating network bandwidth for a distributed system, what is the most critical variable to include?

    • The cost of the network hardware
    • The packet header overhead versus payload size
    • The average size of the request and response in bytes
    • The number of switches between client and server

    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