Cache in System Design – Complete Guide | Redis, LRU, Consistency, Stampede, Hot Key
Understanding Cache: Concepts and Importance
What is Cache?
- Cache is defined as a fast temporary storage that enhances data retrieval speed by storing frequently accessed information close to the processing unit.
- It operates significantly faster than traditional databases because it utilizes RAM, which allows for response times in nanoseconds compared to milliseconds from SSD or hard disk drives.
Why Not Store Everything in Cache?
- Storing all data in cache is impractical due to cost; RAM is expensive, so only frequently used data should be cached.
- Additionally, having too much data in cache can lead to inefficiency and difficulty in quickly locating specific items.
Types of Caches and Their Roles
Multiple Levels of Caching
- Cache can exist at various levels including client-side caches, CDN (Content Delivery Network), server-level caches, database internal caches, and distributed caches.
Client-Side Cache
- This type of cache resides on the user's device (e.g., mobile apps or web browsers), storing static assets like images and API responses for quicker access.
CDN
- CDNs serve as edge servers that store static content globally, reducing latency by delivering content closer to end-users.
Challenges with Caching
Hotkey Problem & Cache Stampede
- The hotkey problem occurs when multiple requests target a single shard or key in the cache, leading to performance bottlenecks.
- A cache stampede happens when many requests hit an expired cache simultaneously; strategies are needed to mitigate these issues effectively.
Common Mistakes Regarding Caching
Interview Insights
- In interviews related to system design, candidates often overlook discussing caching strategies despite their critical role in optimizing performance.
Practical Example of Cache Usage
Cooking Analogy
- Using a cooking analogy, essential ingredients like salt and pepper represent frequently accessed data stored near the chef (server), illustrating how caching improves efficiency by minimizing trips back to the kitchen (database).
Technical Aspects of Caching
Data Retrieval Speed
- The speed advantage of caching stems from its use of RAM versus slower storage solutions like SSD or HDD; this results in dramatically reduced response times for applications relying on quick data access.
Temporary vs. Permanent Storage
- Unlike databases that provide persistent storage, caches are temporary; if they fail or go down, all cached data is lost necessitating reliance on databases for durability.
Distributed Caching Solutions
Role of Redis
- Redis serves as a popular distributed caching solution allowing multiple servers within a system architecture to share cached data efficiently while avoiding inconsistencies across different server caches.
Understanding Database Cache Limitations
Limitations of Database Cache
- The database cache is not under user control; it is determined by the database itself.
- Even when using database cache, the load on the database remains significant as all requests still hit the database.
- Redis offers a simpler structure for caching compared to databases, utilizing key-value pairs without complex joins or SQL parsing.
- Redis can handle millions of queries per second and is designed to manage high loads effectively, unlike traditional databases.
- Using Redis allows users to control what data gets cached, providing flexibility that internal database caches do not offer.
Importance of Distributed Caches
Focus on Distributed Cache
- While understanding internal database caches is useful, they can generally be ignored in system design interviews.
- Key areas to focus on include Content Delivery Networks (CDN) and distributed caches like Redis for large systems design.
- When discussing caching in this context, it primarily refers to distributed caches rather than CDNs which serve static assets.
- The role of CDN is limited to caching static content such as images and videos, while distributed caches handle dynamic data between servers and databases.
- Distributed caches are integral parts of backend systems that improve performance by reducing latency through faster access to frequently used data.
Comparing In-Memory Cache with Distributed Cache
Performance Insights
- In-memory cache operates faster than Redis because it resides within the server's process, eliminating network call delays.
- Fetching data from Redis involves network calls since it's a separate distributed system, making it slower than in-memory cache access.
- Despite being slower due to network overhead, focusing on distributed cache is essential for designing scalable systems capable of handling large volumes of traffic.
Understanding Cache Hits and Misses
Definitions and Scenarios
- A "cache hit" occurs when requested data is found in the cache and returned directly without querying the database.
- Conversely, a "cache miss" happens when requested data isn't available in the cache; thus requiring retrieval from the database instead.
- After a cache miss occurs and data is fetched from the database, that data will be stored in the cache for future requests.
- This mechanism ensures that subsequent requests for previously missed data can result in a faster response time if served from cache.
Cache Eviction Policies Explained
Necessity of Eviction
- Due to limited storage capacity in caches, eviction policies are necessary to remove less frequently accessed items when new entries need space.
- The Least Recently Used (LRU), which evicts items based on their usage frequency over time, is one common strategy employed for managing cached items.
LRU Example Walkthrough
- An example illustrates how LRU works: if an item hasn't been accessed recently compared to others present in the cache, it will be removed first during eviction processes.
Time-to-Live (TTL): Managing Data Freshness
TTL Concept Overview
- TTL stands for Time-to-Live; it's set as an expiration period after which cached entries automatically become invalidated.
- Setting TTL helps mitigate stale or inconsistent data issues by ensuring old entries are removed after a specified duration even if they aren't manually invalidated.
Benefits of Implementing TTL
- By implementing TTL strategies based on entry dynamics—shorter durations for frequently changing values versus longer ones for static information—data freshness can be maintained effectively across applications.
Cache Write Strategies: Ensuring Consistency
Overview of Write Strategies
- Different strategies dictate how updates occur between caches and databases; these affect overall consistency levels across both storage types.
- The most commonly used strategy known as "Cache Aside" involves reading from cache first before falling back onto direct reads from databases upon misses while also managing write operations carefully.
Implementation Details:
- During writes under this strategy: updates happen directly within databases followed by invalidating corresponding keys within caches preventing inconsistencies during read operations later on.
Cache Strategies: Pros and Cons
Cache Aside Strategy
- The cache aside strategy is simple as it involves writing directly to the database while invalidating keys in the cache, similar to deleting a key from a hashmap.
- This method ensures that the database remains the source of truth, making it safe and scalable across multiple servers.
- A potential downside is a small inconsistency window during which read requests may fetch outdated data if they occur between updating the database and deleting the cache entry.
- The first read after deletion can be slow due to lazy loading, resulting in latency as data must be fetched from the database instead of being retrieved from cache.
- Steps are not atomic; thus, multi-threading scenarios can lead to race conditions where reads may occur before updates complete.
Handling Inconsistencies
- Approaches like short expiry (TTL), versioning, or double delete strategies can mitigate inconsistencies during high load situations.
- Despite various strategies available, cache aside remains the default approach for many applications due to its simplicity.
Write Through Cache Strategy
Overview
- In this strategy, writes occur first in the cache before synchronously updating the database, ensuring that all write operations go through the cache.
- This synchronous process introduces latency since success responses are only sent after both cache and database updates are completed.
Advantages
- Data in the cache is always fresh because every write operation updates both locations simultaneously.
- There will be no cache misses immediately following writes since data has just been added to the cache.
Disadvantages
- Increased latency for write operations occurs due to synchronous updates requiring completion before returning success messages.
- Inefficient use of caching resources may arise if written data is never read back from the cache.
Write Behind Cache Strategy
Concept
- The write behind strategy allows immediate success responses after writing to the cache while asynchronously updating the database later on.
Benefits
- Extremely fast writes benefit systems with heavy write loads by reducing latency significantly compared to synchronous methods.
- Asynchronous updates reduce load on databases by allowing batch writes rather than individual transactions for each operation.
Risks
- There’s a risk of data loss if a crash occurs before asynchronous updates complete since cached data isn't permanent storage.
- Complex recovery logic becomes necessary to handle potential failures associated with this strategy leading to eventual consistency rather than strong consistency.
Additional Cache Strategies
Overview of Other Methods
- Various other strategies exist beyond those discussed; some involve simply writing directly into databases without affecting caches until TTL expires.
Key Takeaways
- Memorizing all strategies isn’t essential; understanding core concepts like lazy loading and how they function within distributed systems is more critical.
Understanding Distributed Caching with Redis
Structure and Functionality
- Redis serves as a distributed caching solution comprising multiple nodes that prevent single points of failure within system design.
Data Management
- Data stored in Redis follows key-value pairs; effective key structuring enhances retrieval efficiency.
- Fetching values utilizes
radius.getmethod while storing new entries employsradius.set, including optional TTL settings for expiration management.
Example Scenario
- In cases of "cache miss," fetching fresh data from databases ensures users receive updated information promptly while maintaining consistency across requests.
Understanding Key-Value Data Structures
Storing Complex Data in Key-Value Pairs
- The value part of a key-value pair can hold complex data, such as JSON objects, rather than just simple types like integers or strings.
- An example includes a video with ID 99, where the key contains metadata like title, description, and URL.
- Another example is a user feed identified by ID 123, which maintains an array of videos similar to social media platforms.
Handling Data Inconsistency Between Cache and Database
- Discusses the challenge of data inconsistency between cache (Redis) and database systems.
- Introduces the "cache aside" pattern where the database is treated as the source of truth; upon updating the database, corresponding cache entries are deleted to prevent serving stale data.
Strategies for Managing Cache Inconsistencies
Cache Aside Pattern
- After deleting outdated cache entries post-database update, any read requests will result in a cache miss leading to fresh data being fetched from the database.
Time-to-Live (TTL)
- TTL sets an expiration time for cached data; after this period (e.g., 10 minutes), old data is automatically removed from the cache.
- This limits how long inconsistent or stale data can be served to users before refreshing it from the database.
Versioning Approach
- Addresses issues arising from multi-threading where simultaneous updates may lead to inconsistencies; versioning ensures that only matching versions update caches.
Advanced Techniques for Consistency Management
Double Delete Strategy
- Involves deleting cache entries twice within a short timeframe (e.g., 500 milliseconds), addressing potential race conditions during multi-threaded operations.
Read Your Writes Consistency
- Suggestion to force reads directly from the master database immediately after updates for critical operations until caches synchronize with new data.
Accepting Eventual Consistency
Concept of Eventual Consistency
- Acknowledges scenarios where temporary inconsistencies are acceptable; users may see outdated information briefly without significant impact on experience.
Examples of Acceptable Eventual Consistency
- YouTube's like counts serve as an example where slight delays in displaying updated numbers do not affect user experience significantly.
Scenarios Where Eventual Consistency Is Not Acceptable
- Real-time applications like messaging services require strict consistency due to their nature of immediate communication needs.
Addressing Cache Stampede Issues
Understanding Cache Stampede
- Describes "cache stampede" or "thundering herd problem," occurring when multiple requests hit a non-existent cached entry simultaneously after expiration leads to overwhelming load on databases.
Solutions for Mitigating Cache Stampede
- Using mutexes or locks allows only one request through while others wait, preventing excessive simultaneous hits on databases.
Logical Expiry Technique
- Instead of deleting expired cache entries outright, marking them as expired allows serving old but usable data while refreshing it in the background.
Random TTL Implementation
- Introducing randomness into TTL values helps stagger expirations across different keys reducing simultaneous loads on databases.
Pre-Warming Cache Strategy
- Proactively refreshes cached items before they expire based on known timelines ensuring continuous availability without hitting databases unnecessarily.
Solutions for Cache Stamp Paid Case
Overview of Solutions
- Four solutions can address the cash stamp paid case, emphasizing that only one request will go to the database while others wait.
- The approach involves marking data instead of deleting it; if this is overwhelming, it's acceptable to set it aside for now.
- Jitter is introduced as a fundamental concept but can be ignored if it's difficult to grasp initially.
- Solutions one and four are highlighted as particularly effective in demonstrating a strong understanding of system design concepts.
Understanding Hotkey Problem
Definition and Impact
- A hotkey refers to a cache key that experiences significantly higher traffic than others, such as popular posts by celebrities.
- Problems associated with hotkeys include overloaded shards in distributed caches like Redis, leading to high latency and potential node failures.
Addressing Hotkey Issues
Techniques for Resolution
- The first solution involves using local cache at the server level to store frequently accessed hotkeys, reducing reliance on Redis.
- The second solution suggests replicating hotkeys across multiple shards (key sharding), allowing traffic distribution among them.
- Utilizing CDN (Content Delivery Network) helps cache static assets like images and videos, minimizing backend load when clients access these resources directly.
Additional Strategies for Cache Management
Expiry and Refresh Techniques
- Logical expiry allows old data to remain accessible while refreshing it in the background without causing cache stampede issues.
- Proactively fetching data from the database before TTL expiration prevents premature removal from cache, aiding in maintaining availability during high traffic.
When to Implement Caching in System Design
Use Cases for Caching
- Introduce caching when systems are read-heavy, where frequent requests can overload databases due to high traffic volumes.
- Caching reduces latency since accessing RAM is faster than disk storage; thus improving user experience significantly.
Common Mistakes in Caching Discussions
Identifying What to Cache
- It's crucial not just to mention using a cache but also specify what data will be cached and how it benefits system performance.
Turn any video into a summary like this
YouTube links, meetings, lectures. With transcripts, search, and chat.