Caching: Why, Patterns, and Pitfalls

Caching (Image generated through ChatGPT)

Whenever we build an application, we want faster responses in lowest cost. This cost can be in many different forms like saving disk I/O or reducing time to compute or avoiding network call. Consequently there are many different ways in which we can reduce the cost. One of the options to achieve this is through caching.

What is Caching?

Caching is a technique used to store copies of frequently accessed data in a temporary storage location (the cache) so that future requests for that data can be served faster. It helps reduce the time it takes to access information and improves the overall performance of a system.

Let's understand this using an analogy of a chef. Imagine a chef in a busy restaurant who has to prepare popular dishes quickly. Every time a customer orders a common dish, like spaghetti, it would take the chef a lot of time to prepare it from scratch, slowing down the entire kitchen and making customers wait.

To solve this, the chef decides to prepare the most popular ingredients ahead of time and keep them within reach—like pre-cooked pasta, sauce, and chopped vegetables—on a nearby shelf. This is the chef's "cache". Now, when someone orders spaghetti, the chef doesn’t have to start from scratch; instead, they grab the pre-cooked ingredients from the shelf and quickly assemble the dish.

Why do we need caching?

Primary reasons for using caching is to improve performance, improve resiliency, reduce load on backend systems, reduce costs and improve user experience.

  • Improve performance: Fetching data from a cache is faster than retrieving it from the primary storage like database, remote server, or disk.
    • Without caching:
      • User requests for product details
      • Application sends a query to the database, database processes the query and returns the results
      • Application send the response back to the user
    • With caching:
      • User requests for product details
      • Application checks the cache
      • If data is in cache then it will return the response immediately
      • If data is not in cache then it will send the query to the database, database processes the query, returns the results, application caches the data and then sends the response back to the user.
  • Improve resilience: Caching improves system resilience by maintaining a copy of the data and reducing dependency on underlying services. Consider a social media application that displays user profiles.
    • Without caching:
      • User makes a request for profile information.
      • If the database goes down
      • User profile request will fail with an error
    • With caching:
      • User makes a request for profile information.
      • If the database goes down
      • If the user's profile is available in the cache
      • Then the application responds back with user's profile information from cache
      • If the user's profile is not available in the cache only then the request will fail with an error.
  • Reduce load: Caching reduces the load on the primary storage or backend by handling requests directly from the cache. Consider a retail website requesting product information.
    • Without caching:
      • Users makes request for product information.
      • Application sends a query to the database every time, database processes the same query for each request and returns the results
      • Application send the response back to the user
    • With caching:
      • Users makes request for product information.
      • Then the application responds back with product information from cache and only one request hits database thereby reducing number of queries being run on database and hence reducing the load.
      • If the product information is not available in the cache only then the request will be sent to the database.
  • Cost efficiency: It can reduce the cost of database operations and network traffic, especially in cloud-based systems where resources are billed. Consider you have health articles that you show on your website and the third party system charges you per requests.
    • Without caching:
      • Many users makes request for health article on nutrition.
      • Application makes API call to get the article content from third party for each request.
      • Application send the response back to the user
    • With caching:
      • Many users makes request for health article on nutrition.
      • Application makes API call to get the article content from third party only for the first request.
      • Application then caches the content and sends the response back to the user.
      • For all other requests application reads from the cache and sends the response back to the user
      • This saves the number of requests hitting the third party API and thereby reducing the costs.
  • Improved user experience: Caching can lead to faster response times and less errors, resulting in a smoother experience for end users. Looking back to our above example of user making request for profile information.
    • Without caching:
      • User makes a request for profile information.
      • If the database goes down user profile request will fail with an error
      • If the database is overwhelmed or running a slow query then user experiences longer wait time
    • With caching:
      • User makes a request for profile information.
      • If the profile information is in cache then then application responds immediately.
      • This is not impacted even if the database is down.
      • This response is faster also compared to getting it from database and hence improves user's experience.

Caching is everywhere

Caching has been around since the early days of computing. Early computers had very slow access to memory and storage. The concept of caching became crucial as it allowed systems to store frequently used data closer to the processor (in faster memory) for quick access.

  • CPU: The concept of caching first started with CPU caches. Modern computers have multiple levels of CPU caches (L1, L2, and L3) to minimize the time it takes to access memory.
  • OS: OS uses memory and disk caching to improve the file system performance.
  • Client side caching: Browsers use cache to store static assets like image, CSS and JavaScript files to load the websites faster.
  • DNS caching: Domain to IP mapping get cached at various levels of domain resolution path (local device, network equipment, ISP, and global infrastructure).
  • CDN caching: Content delivery networks make use of edge caches to improver the delivery of content.
  • Load balancer: A load balancer might cache the results of common queries. This improve performance If multiple clients request the same data within a short time frame.
  • Application servers: application servers employ some form of caching service to avoid round trips to database or other backend services for frequently used data.

These examples shows that caching indeed is everywhere in modern computing, from the lowest hardware levels to high-level distributed systems. Each implementation aims to improve performance, reduce latency, or enhance system resilience.

 

Key caching terminologies

  • System of record: The main data source. Example - In an e-commerce system, the product database is the system of record for product information.
  • Cache miss: When the requested data isn't in the cache and must be fetched from the system of record. Example - A newly registered user's data isn't in the cache, so it must be fetched from the database.
  • Cache hit: When the data is found in the cache. A user's profile information is successfully retrieved from the cache without querying the database.
  • Time to Live (TTL): A TTL is the amount of time that a piece of data should be kept in the cache before being considered stale or invalid.
  • Cold Cache: A cache that is empty or has very little stored data is called a cold cache. It usually occurs when a system is newly started.
  • Warm Cache: A cache that has been populated with data but is still building up.
  • Cache pollution: When unnecessary data fills up the cache. Example - Caching every single API request, including one-time queries, leading to useful data being evicted.
  • Cache Eviction: The process of removing data from the cache, usually to make room for new data.
  • Data Freshness: How up-to-date the cached data is compared to the system of record. Example - A product's price in the cache was last updated 5 minutes ago.
  • Cache Expiration: When cached data becomes too old to use and needs to be refreshed or removed.
  • Cache Invalidation: The process of marking cache entries as invalid due to updates in the system of record.

 

Caching Patterns

Caching patterns are well-defined strategies or approaches for using caching effectively. These patterns determine how and when data is added to the cache and how data is kept consistent between the cache and the source.

  • Side Cache or Cache aside or Lazy loading: The application is responsible for fetching data from the database and storing it in the cache. This is the most common caching pattern.
    • Best for:
      • Read-heavy workloads with a high cache hit ratio
      • Data that doesn't change frequently
      • Simplest to implement and understand

Side Cache or Cache aside  or Lazy loading

  • Read through cache: The cache is responsible for fetching data from the database when it's not found in the cache. The caching layer acts as an abstraction between the application and the data source.
    • Best for:
      • Applications where caching logic should be abstracted away from the application code
      • Scenarios where you want to ensure the cache is always populated (no cold cache)
    • Consideration:
      • May cache infrequently accessed data unnecessarily
      • More complex to implement than Cache-Aside

Read through cache

  • Write through cache: data is written to both the cache and the database in a single operation.
    • Best for:
      • Systems requiring strong consistency between cache and database
      • Write-heavy workloads where data is also frequently read
    • Consideration:
      • Writes are slower due to the need to update both cache and database
      • Can lead to unnecessary cache updates for data that's rarely read

Write through cache

  • Write around cache: Data is written directly to the database, bypassing the cache. The cache is only updated when data is read from the database.
    • Best for
      • Write-heavy workloads where written data is not immediately read
      • Systems where write performance is critical
    • Consideration:
      • Prevents the cache from being filled with data that may not be read
      • Can lead to higher read latency for recently written data

Write around cache

  • Write behind cache: Data is written to the cache and then asynchronously written to the database. This can be done in batches to improve write performance.
    • Best for:
      • Scenarios where you want to absorb write spikes
      • Systems where write performance is critical and eventual consistency is acceptable
    • Consideration:
      • Reduces database load by batching writes
      • Risk of data loss if the cache fails before data is written to the database
      • Eventual consistency model, which may not be suitable for all use cases

Write behind cache

 

Cache Eviction Policies

Cache eviction is the process of removing data from a cache when the cache storage is full or when data becomes stale. This is essential because caches typically have limited storage capacity.

Eviction ensures that the most relevant and frequently accessed data remains in the cache, while older or less-used data is replaced to make room for new entries. The method or strategy used to decide which data to evict is called a cache eviction policy or cache eviction strategy.

Selecting the appropriate cache eviction policy depends on your specific use case, data access patterns, and application requirements.

  • Least Recently Used (LRU): Evicts the data that has not been accessed for the longest time.
    • Use LRU when:
      • our data access follows a temporal locality pattern (recently accessed items are likely to be accessed again soon)
      • You have a mix of frequently and infrequently accessed items
      • You want a good balance between implementation complexity and cache hit rate
    • Example scenarios:
      • Web page caching
      • Database query result caching
  • First In First Out (FIFO): Evicts the data that was added to the cache first, regardless of how often or recently it was accessed.
    • Use FIFO when:
      • You need a very simple implementation
      • Your data has a natural temporal order or lifecycle
      • All items in the cache have roughly equal importance
    • Example scenarios:
      • Simple message queues
      • Logging systems
      • Scenarios where data freshness is more important than access frequency
  • Least Frequently Used (LFU): Evicts the data that has been accessed the least number of times.
    • Use LFU when:
      • Some items are accessed much more frequently than others
      • The popularity of items remains relatively stable over time
      • You want to maximize cache hit rate for very frequently accessed items
    • Example scenarios:
      • Content Delivery Networks (CDNs)
      • Caching popular articles or products on a website
      • API response caching for high-traffic endpoints
  • Random Replacement (RR): Randomly selects and evicts an item from the cache.
    • Use RR when:
      • You need an extremely simple implementation
      • Your data access patterns are unpredictable or uniform
      • You can tolerate potentially suboptimal cache performance
    • Example scenarios:
      • In systems with very limited resources where complex policies are too expensive
      • When data access is truly random and no other policy would provide significant benefits
  • Time To Live (TTL): Each item in the cache has a fixed expiration time (TTL). When the time expires, the item is evicted, even if space isn’t needed.
    • Use TTL when:
      • Your data has a clear expiration time or becomes stale after a certain period
      • You need to ensure cache coherence with an underlying data store
      • You want to limit how long sensitive data is retained in the cache
    • Example scenarios:
      • Session data caching
      • Caching of time-sensitive information (e.g., weather data, stock prices)
      • Temporary storage of authentication tokens
  • Hybrid Approaches
    • LRU with TTL: Combine LRU eviction with a time-based expiration to balance access recency with data freshness.
    • LFU with Dynamic Aging: Implement LFU but periodically reduce frequency counts to allow for changes in item popularity over time.
    • Multi-Queue: Use multiple queues with different eviction policies for different types of data within the same cache.

 

Considerations for choosing an eviction policy

Choosing the right cache eviction strategy is critical for ensuring efficient caching performance while meeting the specific needs of your application. The strategy you select should align with your workload, access patterns, and business requirements.

  • Access patterns: Analyze how your data is typically accessed. Is it bursty, cyclical, or uniform?
  • Data lifecycle: Understand how long your data remains valid and how its importance changes over time.
  • Performance requirements: Consider the impact of the eviction policy on your application's performance, including both cache hit rates and the computational overhead of the policy itself.
  • Memory constraints: Evaluate how much memory you can allocate to your cache and how this affects your choice of policy.
  • Consistency requirements: Determine how important it is to keep your cache in sync with the underlying data store.
  • Implementation complexity: Weigh the benefits of a more sophisticated policy against the costs of implementation and maintenance.

 

Caching Pitfalls and how to avoid them

While caching can significantly improve system performance, it also introduces complexities that can lead to various issues.

  • Cache Stampede (Thundering Herd) : Many requests hit the database simultaneously when a cache entry expires, potentially overwhelming the database.

    • Example
      • Time 0: Popular item X is cached
      • Time 60: Cache for X expires
      • Time 61: 1000 requests for X arrive, all miss the cache and query the database
    • Mitigation Strategies:
      • Implement stale-while-revalidate: Serve stale content while asynchronously updating the cache.
      • Use cache warming: Proactively refresh cache before expiration.
  • Cache Penetration: Repeatedly querying for non-existent data, bypassing the cache and hitting the database.

  • Example

    • Attacker repeatedly requests /user/99999 (non-existent user)
    • Each request misses the cache and queries the database
  • Mitigation Strategies:

    • Cache negative results (with a shorter TTL).
    • Use a bloom filter to quickly check if an item might exist before querying.
    • Implement request rate limiting.
  • Cache Crash: When the cache system fails, potentially overwhelming the database with requests.

    • Mitigation Strategies:
      • Implement circuit breakers to prevent excessive load on the database.
      • Use a distributed cache system with high availability.
  • Cache Avalanche: Multiple caches expire at the same time, overwhelming the system.

    • Mitigation Strategies:
      • Add random jitter to expiration times.
      • Use a sliding expiration window.
  • Stale Data: Cached data becomes outdated, leading to inconsistencies with the source of truth.

    • Mitigation Strategies:
      • Implement cache invalidation on write operations.
  • Cache Avalanche vs Cache Stampede: While Cache Avalanche and Cache Stampede are both issues that can overwhelm a system, they have distinct characteristics and occur under different circumstances

    • Cache Avalanche Triggered by simultaneous expiration of multiple cache entries
    • Cache Stampede Typically affects a single, popular piece of data
    • Scope: Avalanche is system-wide, Stampede is typically for a single piece of data.

 

Caching in Microservice

Like we discussed above caching in microservices will improve resilience and help in scalability. This is done via reduced inter-service communication between microservices.

  • Client-Side Caching:

    • Implemented in the client application
    • Challenges: Maintaining cache consistency across multiple clients
  • Service-Level Caching

    • Each microservice maintains its own cache. Its improve the service response time.
    • Challenges: Potential data inconsistency between services
  • Distributed Caching:

    • Centralized cache shared by multiple microservices
    • Challenges: Increased complexity, potential single point of failure
  • API Gateway Caching:

    • Caching implemented at the API gateway level
    • Challenges: Determining appropriate cache invalidation strategies


Try few questions