Search Sreeni's Insights

Filter by content type
technical September 9, 2020 7 min read

How to keep local and distributed caches in sync? Hybrid caching with Pub/Sub - Part 4

How hybrid caching combines local and distributed caches, and how Redis Pub/Sub keeps local copies synchronized.

Share:

How to keep local and distributed caches in sync? Hybrid caching with Pub/Sub - Part 4

A local cache is the fastest cache we can have, but it is also the most dangerous one. Each application instance has its own copy of the data, and when one instance changes the data, the others don’t know anything about it. The users will start getting different answers from different instances, and the support calls are starting. In Part 1 we discussed why caching is needed, and in Part 2 we looked at cache-aside, lazy loading and read-through. Part 3 covered write-through, write-behind and refresh-ahead. These articles give us the foundation for the hybrid model. In this article, we are going to see the hybrid caching model, why the local caches need synchronization, and how Redis Pub/Sub solves this problem.

TL;DR Summary

  • Hybrid caching is the way to go when the application needs reduced latency, and high performance and availability.
  • Each application instance keeps a local version of the distributed cache in its memory, so it doesn’t have to fetch the data from the distributed cache every time.
  • The local cache must be in sync with the distributed cache when the same dataset is updated or removed by other applications or instances. Otherwise, we serve stale data.
  • Redis provides Pub/Sub channels which can be used as a backplane to observe the modifications of the data.
  • When an instance changes the data, it publishes the cache key on a topic, and the other instances remove that key from their local cache.
  • A distributed cache also avoids the empty local cache problem of the new instances during the scale-out.

What is hybrid caching?

Hybrid caching model is really the way to go when the application has the following requirements with the cache,

  • Reduced latency
  • High performance and availability

The following diagram depicts the hybrid caching, where each application maintains the local version of the distributed cache in its memory. Hence it doesn’t have to fetch the data from the distributed cache, which reduces the latency and increases the performance of each call.

Hybrid caching with local and distributed caches
Hybrid caching with local and distributed caches

In simple terms, the local cache is the first level and the distributed cache is the second level. The database is read only when both of them don’t have the data.

Why the distributed cache is still needed?

Think about the scale-out. When the traffic increases, new instances are added, and each new instance starts with an empty local cache. If we have only local caches, all the first requests of the new instance are cache misses and they go to the database. With the distributed cache in the middle, the new instance reads from the distributed cache and the database is protected.

Scale-out with a local cache only vs with a distributed cache
Scale-out with a local cache only vs with a distributed cache

Why do we need to synchronize the local caches?

But in the following circumstances, the local cache of the application needs to be in sync with the distributed cache,

  1. When the same dataset is updated by other applications or instances of the same application.
  2. When the same dataset is removed by other applications or instances of the same application.

Otherwise, it may lead to serving the stale data for the users. Hence it becomes very important to synchronize the local in-memory caches with the distributed cache.

How does Pub/Sub help?

In order to avoid this problem of synchronization, Redis provides Pub/Sub channels for the clients to use as a backplane to observe the modifications of the data. The following diagram depicts how it works,

Synchronizing local caches with Redis Pub/Sub
Synchronizing local caches with Redis Pub/Sub

Let us take the fund details as an example,

  1. Application instances 2 and 3 subscribe to a particular topic (for example, funds-details), which is used to communicate the changes on the specific dataset.
  2. Instance 1 updates the latest data of a fund, let us say Unit_001.
  3. Instance 1 publishes the updated cache key, Unit_001, on the topic funds-details.
  4. Instances 2 and 3 receive the notification with the cache key Unit_001, and they clear the key from their local cache, in order to fetch the updated data from Redis.

This way, both local and distributed caches can be kept up to date always. As mentioned above, it improves the overall performance of the application and ensures the consistency between the caches.

Note: The notification carries only the cache key, not the data. Each instance reads the fresh data from Redis, only when it needs it again.

How to implement it with StackExchange.Redis?

It can be implemented using the StackExchange.Redis library.

Subscribe and handle,

ConnectionMultiplexer redisHostConnection = ...;
ISubscriber subscriber = redisHostConnection.GetSubscriber();
...
await subscriber.SubscribeAsync("fund:unitDetails", (channel, message) =>
    Console.WriteLine("Unit code is: {0}", message));

Publish the changes,

ConnectionMultiplexer redisHostConnection = ...;
ISubscriber subscriber = redisHostConnection.GetSubscriber();
...
FundUnitDetails unitDetails = ...;
subscriber.PublishAsync("fund:unitDetails", unitDetails.Code);

In the sample, the subscriber just prints the unit code. In a real application, the handler removes this key from the local cache. Writing and maintaining this plumbing for every application is not a good idea, so there are libraries built on StackExchange.Redis which provide the publish/subscribe functionality as built-in. We will see one of them in the next article.

Use cases in e-commerce and mutual fund world

These are illustrative scenarios to explain when the synchronization matters.

E-commerce: price change

A shopper is looking at the product on instance 2, and the business updates the price through instance 1. Without synchronization, instance 2 keeps showing the old price from its local cache until the TTL is over. A stale price is a real problem, the customer may see one price on the product page and another price on the cart page, which is served by a different instance. When instance 1 publishes the product key on the topic, the other instances clear that product from their local cache and the next request reads the new price from Redis.

Mutual fund: NAV update

After the daily NAV is loaded, all the instances should show the same NAV. The fund unit details of Unit_001 are updated by one application, then the key is published on the funds-details topic and all the other instances remove Unit_001 from their local cache. Investors will never see two different NAVs for the same fund from two instances. It is the same flow as we saw in the Pub/Sub diagram.

E-commerce: flash sale and scale-out

During a sale, the traffic grows and new instances are added. The new instances start with an empty local cache, but with a distributed cache in the middle they read the product data from Redis and the database is protected exactly when the load is highest.

Use caseDomainWhat happens without synchronizationWhat synchronization gives
Price changeE-commerceDifferent prices on different instancesSame price from all instances
NAV updateMutual fundDifferent NAV for the same fundSame NAV for all investors
Flash sale scale-outE-commerceNew instances hit the databaseNew instances read from Redis

Wrap up

In this article, we have looked at what is hybrid caching, why we still need a distributed cache, why the local caches must be synchronized, and how Redis Pub/Sub helps us. Thanks for reading this article. In the next article, I will walk you through how to implement hybrid caching with the EasyCaching library, with the cache-aside extension methods.

Related Posts