Search Sreeni's Insights

Filter by content type
technical June 20, 2019 7 min read

How to choose the right server-side caching strategy? Write-through, write-behind and refresh-ahead - Part 3

How write-through, write-behind and refresh-ahead caching work, their trade-offs, and how to choose a strategy for e-commerce and mutual fund use cases.

Share:

How to choose the right server-side caching strategy? Write-through, write-behind and refresh-ahead - Part 3

Lazy loading and read-through are good for reading the data, but what happens when our application is writing a lot of data, or when we already know which data will be requested tomorrow? A single strategy can’t solve all these problems, and every strategy is a trade-off between performance, consistency and complexity. In the previous article, we discussed the cache-aside pattern with lazy loading and read-through. In this article, we are going to see the other three strategies, write-through, write-behind and refresh-ahead, and how to choose the right one for your use case.

TL;DR Summary

  • Write-through writes the data to the cache and then to the database, and returns the response only when all writes are completed. It gives high consistency, but it caches the data which may never be requested.
  • Write-behind writes the data to the cache and sends only the data identifier to a queue. A function updates the database later. It improves the write performance, but the implementation is complex and data can be lost when the database write fails.
  • Refresh-ahead builds the cache in advance for the required dataset, so the application is always served from the cache. We have to maintain the list of queries to refresh.
  • Choose based on the workload, read-heavy or write-heavy, and how much consistency and performance you need.
  • Every strategy has a cost, so measure and validate with your own data.

Write-through

Pick this strategy when your application,

  • Consists of write-heavy operations
  • Requires strong consistency
  • Chooses reliability over performance
Write-through
Write-through

Follow the following steps to understand the flow,

  1. Application receives the request.
  2. It writes the data to the cache.
  3. Then it writes the data to the database.
  4. Finally, it returns the response back to the application only when all writes are completed.
ProsCons
+ Provides high consistency, no stale data− Inefficient because of caching all the data even though the data is not requested by the application

Write-behind

Pick this strategy when your application,

  • Consists of write-heavy operations
  • Requires strong consistency
  • Needs better performance in spite of strong consistency
Write-behind
Write-behind

The flow is,

  1. Application receives the request.
  2. It writes the data to the cache.
  3. Then it writes the data identifier to the queue.
  4. Queue triggers the function to update the database.
  5. Function writes to the database for the provided data identifier by reading from the cache.
ProsCons
+ Improves write performance of the application− Implementation is not straightforward when compared to other strategies
+ Provides strong consistency− Possibility of data loss in case of any failure towards processing the database write

Warning: In write-behind, the response goes back to the application before the database is updated. Think about the failure of the function or the queue before you choose it, otherwise you may lose the data.

The difference between write-through and write-behind is when the caller is released. Write-through waits for the database, write-behind doesn’t. Think about posting a letter. In write-through you wait at the post office till the letter is delivered, in write-behind you drop it in the box and go.

Refresh-ahead

This strategy can be followed on the below circumstances. Pick this strategy when your application,

  • Consists of read-heavy operations
  • Has good prediction over what is being requested on a daily basis
  • Wants better performance and reduced latency
Refresh-ahead
Refresh-ahead
  1. Cache builder is configured to build the cache for the required dataset.
  2. Application is served from the cache directly without having to fetch from the database.
ProsCons
+ Improves performance of the application− Have to maintain the list of queries or scenarios for which the cache needs to be updated. Automatically managing the list could reduce this con
+ Reduced latency

How to choose the right strategy?

All these strategies are based on the type of operations, the consistency we need and what we know about the requests. The following diagram can be used as a starting point to choose the strategy,

How to choose the server-side caching strategy
How to choose the server-side caching strategy

Find below the summary of all the strategies,

StrategyPick whenMain strengthMain cost
Lazy loadingRead-heavy, high control over expiryOnly requested data is cachedMore cache misses, stale data
Read-throughRead-heavy, standalone data provider libraryApplication code is cleanSame as lazy loading
Write-throughWrite-heavy, strong consistency, reliability over performanceNo stale dataCaches data which may not be requested
Write-behindWrite-heavy, strong consistency, better performanceBetter write performanceComplex, possible data loss
Refresh-aheadRead-heavy, good prediction of daily requestsReduced latencyMaintain the list of queries to refresh

Note: The flowchart is a starting point. If you have a different use case, then combine the strategies based on your needs and validate the result with real measurements.

Use cases in e-commerce and mutual fund world

Let us map the strategies to some real-world scenarios. These are illustrative, so validate each one with your own traffic and consistency needs.

Write-through

  • E-commerce: shopping cart - The cart is written by the customer on every add or remove, and the customer expects to see exactly what he added, even on another page or another instance. Writing to the cache and the database together gives the consistency, and we pay with the extra write time.
  • Mutual fund: investor’s watchlist or preferences - It is a small and write-light data, but the investor must see the saved list immediately. The consistency is more important than the speed here.

Write-behind

  • E-commerce: product view counters and recently viewed items - These are written on every page view and nobody will complain if the database is updated few seconds later. The write goes to the cache, and the function updates the database in the background.
  • Mutual fund: page view and search analytics - The same idea. The data is useful for the reports, but losing a few records in a failure is acceptable.

Warning: Don’t use write-behind for the money related data like orders, payments, and fund subscription or redemption. A data loss is not acceptable there. Save them in the database first.

Refresh-ahead

  • E-commerce: home page top products and daily deals - The business knows which products will be on the home page tomorrow, so the cache builder can build the cache before the traffic comes and the first shopper doesn’t pay the miss.
  • Mutual fund: daily NAV and the top performing funds list - NAV is published once per day, and we know that the investors will ask for it the next morning. The cache builder can load the NAV and the top funds list right after the NAV is published, so the application is always served from the cache.

Summary of use cases

Use caseDomainStrategyReason
Product details pageE-commerceLazy loadingRead-heavy, control over expiry
Shopping cartE-commerceWrite-throughCustomer must see his latest cart
Product view countersE-commerceWrite-behindWrite-heavy, small delay is acceptable
Home page top productsE-commerceRefresh-aheadGood prediction of the daily requests
Fund factsheetMutual fundLazy loadingRead-heavy, content changes rarely
Investor’s watchlistMutual fundWrite-throughConsistency over speed
Search and page analyticsMutual fundWrite-behindPerformance over strict durability
Daily NAV and top fundsMutual fundRefresh-aheadPublished once a day, requested many times

Wrap up

In this article, we have looked at write-through, write-behind and refresh-ahead, their pros and cons, and how to choose the right strategy for the workload. I appreciate your time and efforts to read this article. In the next article, I will walk you through the hybrid caching, and how to keep the local and distributed caches in sync with Pub/Sub.

Related Posts