Bird
Raised Fist0
HLDsystem_design~25 mins

Cache-aside pattern in HLD - System Design Exercise

Choose your learning style10 modes available
Design: Cache-aside Pattern Implementation
Design focuses on the cache-aside pattern for read-heavy workloads with a relational database and an in-memory cache. Write-heavy scenarios and distributed cache synchronization are out of scope.
Functional Requirements
FR1: The system should efficiently serve data requests by using a cache to reduce database load.
FR2: When data is requested, the system should first check the cache.
FR3: If data is not in the cache (cache miss), the system should fetch it from the database and update the cache.
FR4: The cache should be updated or invalidated when data changes in the database to maintain consistency.
FR5: The system should handle concurrent requests safely without stale or inconsistent data.
FR6: The cache should improve read performance significantly compared to direct database access.
Non-Functional Requirements
NFR1: The system should handle up to 10,000 concurrent read requests with p99 latency under 100ms.
NFR2: Cache consistency should be eventual but with minimal stale data window (under 5 seconds).
NFR3: Availability target is 99.9% uptime.
NFR4: Cache size is limited and should evict least recently used data when full.
Think Before You Design
Questions to Ask
❓ Question 1
❓ Question 2
❓ Question 3
❓ Question 4
❓ Question 5
Key Components
Client application or service
In-memory cache (e.g., Redis, Memcached)
Primary database (e.g., PostgreSQL, MySQL)
Cache management logic in the application layer
Design Patterns
Cache-aside (Lazy loading)
Cache invalidation strategies
Cache eviction policies (LRU, TTL)
Read-through and write-through caching (for comparison)
Reference Architecture
Client
  |
  v
Application Layer
  |
  |---> Cache (Redis/Memcached)
  |       |
  |       v
  |    Cache Miss?
  |       |
  |       v
  |    Database (PostgreSQL/MySQL)
  |
  v
Response to Client
Components
Client
Any frontend or service
Sends data requests to the application
Application Layer
Backend service (Node.js, Java, Python, etc.)
Implements cache-aside logic: checks cache, fetches from DB on miss, updates cache
Cache
Redis or Memcached
Stores frequently accessed data in memory for fast retrieval
Database
Relational DB like PostgreSQL or MySQL
Stores persistent data; source of truth
Request Flow
1. Client sends a data request to the application.
2. Application checks the cache for requested data.
3. If data is found in cache (cache hit), return data to client immediately.
4. If data is not found (cache miss), application queries the database.
5. Database returns data to application.
6. Application stores the retrieved data in cache for future requests.
7. Application returns data to client.
8. When data updates occur, application invalidates or updates the cache to keep data consistent.
Database Schema
Entities depend on application domain; cache stores serialized data keyed by unique identifiers matching database primary keys. Relationships remain in the database; cache holds denormalized or frequently accessed data subsets.
Scaling Discussion
Bottlenecks
Cache size limits causing frequent evictions and cache misses.
High write volume causing cache invalidation overhead.
Database becoming a bottleneck on cache misses under heavy load.
Cache consistency delays leading to stale data served to clients.
Solutions
Implement cache sharding or distributed cache clusters to increase capacity.
Use asynchronous cache invalidation or write-back strategies to reduce overhead.
Scale database vertically or horizontally (read replicas) to handle increased load.
Use TTL (time-to-live) and event-driven cache updates to minimize stale data window.
Interview Tips
Time: Spend 10 minutes understanding requirements and clarifying constraints, 20 minutes designing the architecture and data flow, 10 minutes discussing scaling and trade-offs, and 5 minutes summarizing.
Explain the cache-aside pattern clearly with real-world analogy (like checking a fridge before going to the store).
Discuss cache hit and miss scenarios and how they affect performance.
Highlight cache invalidation importance to avoid stale data.
Mention trade-offs between consistency and performance.
Address scaling challenges and practical solutions.

Practice

(1/5)
1. What is the main purpose of the cache-aside pattern in system design?
easy
A. To load data into cache only when it is requested
B. To preload all data into cache before any request
C. To write data directly to cache without database interaction
D. To keep cache and database completely separate without synchronization

Solution

  1. Step 1: Understand cache-aside pattern behavior

    The cache-aside pattern loads data into cache only when the application requests it and the data is not already cached.
  2. Step 2: Compare options with this behavior

    To load data into cache only when it is requested correctly states this lazy loading approach. Other options describe preloading or unsynchronized caching, which are incorrect.
  3. Final Answer:

    To load data into cache only when it is requested -> Option A
  4. Quick Check:

    Cache-aside = lazy loading on demand [OK]
Hint: Cache-aside loads data only when requested [OK]
Common Mistakes:
  • Thinking cache preloads all data
  • Assuming cache updates happen before DB writes
  • Believing cache and DB are unsynchronized
2. Which of the following is the correct sequence of operations in the cache-aside pattern when reading data?
easy
A. Read from database -> Update cache -> Return data
B. Read from cache -> If miss, read from database -> Update cache
C. Update cache -> Read from cache -> Read from database
D. Read from cache -> Return data without checking database

Solution

  1. Step 1: Recall cache-aside read flow

    When reading, the system first checks the cache. If data is missing (cache miss), it reads from the database and then updates the cache.
  2. Step 2: Match this flow to options

    Read from cache -> If miss, read from database -> Update cache matches this exact sequence. Other options either skip cache miss handling or update cache before reading.
  3. Final Answer:

    Read from cache -> If miss, read from database -> Update cache -> Option B
  4. Quick Check:

    Cache read -> DB read on miss -> Cache update [OK]
Hint: Cache read first, DB read only if cache miss [OK]
Common Mistakes:
  • Updating cache before reading database
  • Ignoring cache miss and reading only cache
  • Reading database before checking cache
3. Consider this pseudocode using cache-aside pattern:
function getUser(id) {
  user = cache.get(id)
  if (user == null) {
    user = database.query(id)
    cache.set(id, user)
  }
  return user
}
What will getUser(5) return if the cache is empty and the database has user with id 5?
medium
A. null
B. Error due to cache miss
C. Empty object
D. User data from database

Solution

  1. Step 1: Analyze cache miss handling

    Since cache is empty, cache.get(5) returns null, triggering database query.
  2. Step 2: Database query and cache update

    The function queries the database for user id 5, finds the user data, updates the cache, and returns the user data.
  3. Final Answer:

    User data from database -> Option D
  4. Quick Check:

    Cache miss triggers DB read and cache update [OK]
Hint: Cache miss leads to DB read and cache update [OK]
Common Mistakes:
  • Assuming cache miss returns null directly
  • Expecting error on cache miss
  • Ignoring cache update after DB read
4. A developer implemented cache-aside but notices stale data in cache after database updates. What is the likely mistake?
medium
A. Not updating cache after database write
B. Reading from cache before database
C. Preloading cache with all data
D. Using cache for write operations only

Solution

  1. Step 1: Identify cause of stale cache

    Stale cache means cache has old data not reflecting recent database updates.
  2. Step 2: Check cache update after DB write

    If cache is not updated or invalidated after database writes, stale data remains in cache.
  3. Final Answer:

    Not updating cache after database write -> Option A
  4. Quick Check:

    Cache must update after DB write to avoid stale data [OK]
Hint: Always update cache after DB write to avoid stale data [OK]
Common Mistakes:
  • Ignoring cache invalidation after writes
  • Assuming cache updates automatically
  • Confusing read and write cache operations
5. You design a high-traffic product catalog service using cache-aside pattern. To handle frequent updates and reads, which strategy best maintains cache consistency and performance?
hard
A. Preload entire product catalog into cache at service start and never update cache
B. On product update, write to DB only and let cache expire naturally
C. On product update, write to DB then immediately update cache with new data
D. Write updates only to cache and asynchronously sync to DB later

Solution

  1. Step 1: Understand cache consistency needs

    For frequent updates and reads, cache must reflect latest data quickly to avoid stale reads.
  2. Step 2: Evaluate update strategies

    On product update, write to DB then immediately update cache with new data updates DB then cache immediately, ensuring cache consistency and fast reads. On product update, write to DB only and let cache expire naturally risks stale cache. Preload entire product catalog into cache at service start and never update cache ignores updates. Write updates only to cache and asynchronously sync to DB later risks data loss and inconsistency.
  3. Final Answer:

    On product update, write to DB then immediately update cache with new data -> Option C
  4. Quick Check:

    Update DB then cache for consistency and performance [OK]
Hint: Update DB then cache immediately for fresh data [OK]
Common Mistakes:
  • Relying on cache expiration alone
  • Preloading cache without updates
  • Writing only to cache without DB sync
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard