World is now on Opti ID! Learn more

Sujit Senapati
Oct 28, 2024
  42
(0 votes)

Mastering clearing Cache in Optimizely CMS with ISynchronizedObjectInstanceCache & MemoryCache

In the fast-paced world of web development, efficient memory management is essential for optimizing application performance and enhancing user experience. Among the many optimization techniques available, clearing memory cache using a cache key is a fundamental approach. When storing objects in cache, developers often set an expiration policy, such as an absolute or sliding cache eviction policy, to control how long the data remains. While cache clearing is manageable in lower CMS environments, production environments can be challenging, especially when sliding cache policies make it nearly impossible to expire cached items in real time.

In Optimizely, most cache management is handled by ISynchronizedObjectInstanceCache. However, Optimizely doesn’t offer a straightforward method to retrieve all cache items in memory.

Understanding Memory Cache and Cache Keys

  • Memory Cache: This is where your web application stores data that can be accessed more quickly than if it were stored in a database or on a disk. It's a portion of RAM reserved for temporarily holding data.
  • Cache Key: This is a unique identifier used to store and retrieve specific data from the cache. Using cache keys ensures you're managing the right data.

Why Clear the Cache?

  • Performance: Over time, the cache can become cluttered with outdated data, slowing down access speeds.
  • Data Integrity: Clearing cache ensures your application uses the latest data, vital for dynamic content.
  • Memory Management: Freeing up memory can prevent memory leaks and improve overall performance.

Implementation Steps in Optimizely CMS

Step 1: Identify Your Cache System

First, identify the caching system your application uses. In Optimizely CMS, the common choice is ISynchronizedObjectInstanceCache, which relies on MemoryCache internally.

Step 2: Determine the Cache Key

  • Static Keys: For fixed data, like user profile information, a static key pattern like "user_" + userID can be effective. In Optimizely CMS and Commerce, most caches utilize static keys, making cache management straightforward.
  • Dynamic Keys: For frequently changing data (e.g., session-based), keys might incorporate timestamps or session IDs.

Step 3: Clearing the Cache

With ISynchronizedObjectInstanceCache, you can only clear individual items by specifying their cache key. However, if dynamic values such as user IDs, class names, content IDs, or language IDs are used, determining the exact key can be challenging.

To overcome this, you can retrieve the private property containing all cached items in MemoryCache using BindingFlags. This allows you to access cached entries, making it possible to locate and manage items based on a keyword search within the cache keys.

Here’s an example approach to find all cache keys matching a keyword (e.g., "cacheKey") and then remove them from the cache using ISynchronizedObjectInstanceCache.

var field = typeof(MemoryCache).GetProperty("StringKeyEntriesCollection", BindingFlags.NonPublic | BindingFlags.Instance);
//_memoryCache is an instance of IMemoryCache
var collection = field?.GetValue(_memoryCache) as ICollection;
var items = new List<string>();
if (collection != null)
{
	foreach (var item in collection)
	{
		var methodInfo = item.GetType().GetProperty("Key");
		var val = methodInfo?.GetValue(item);
		if (val != null)
			items.Add(val.ToString());
	}
}

var cacheKeysTobeCleaned =
	items.Where(key => key.StartsWith(cacheKey, StringComparison.OrdinalIgnoreCase)).ToList(); //cacheKey is the keyword we are searching for in cacheKey

if (!cacheKeysTobeCleaned.Any())
	return NotFound();

foreach (string cacheKeyToBeCleaned in cacheKeysTobeCleaned)
{
//_cache is an instance of ISynchronizedObjectInstanceCache
	this._cache.RemoveLocal(cacheKeyToBeCleaned);
	this._cache.RemoveRemote(cacheKeyToBeCleaned);
}
			
This method uses reflection to access the MemoryCache entries, finds keys matching a prefix, and clears them using ISynchronizedObjectInstanceCache.
UPDATE: Although the above approach was mostly used only for urgent scenarios rather than regular cache management. Alternative and the most effective method to clear the cache for a specific list of objects is to use a master key when adding items to the cache, which serves as an additional feature of the CacheEvictionPolicy. For more information, refer to cache objects documentation. While standard dependency keys within a CacheEvictionPolicy create dependencies between existing cache items, a master dependency enables grouping multiple cache entries. When a master key is specified, the cache either confirms the existence of an entry with this key or inserts a placeholder object with an indefinite timeout. This approach allows for the entire group of entries to be removed simultaneously.

Conclusion

Managing cache in Optimizely CMS requires strategic approaches, especially when dealing with a large number of cache entries or dynamic keys. By understanding how to interact with ISynchronizedObjectInstanceCache and leveraging reflection to access MemoryCache, you can maintain a clean, efficient cache system. This not only enhances performance but also ensures your web application remains responsive and up-to-date with the latest data. 
Oct 28, 2024

Comments

Please login to comment.
Latest blogs
Make Global Assets Site- and Language-Aware at Indexing Time

I had a support case the other day with a question around search on global assets on a multisite. This is the result of that investigation. This co...

dada | Jun 26, 2025

The remote server returned an error: (400) Bad Request – when configuring Azure Storage for an older Optimizely CMS site

How to fix a strange issue that occurred when I moved editor-uploaded files for some old Optimizely CMS 11 solutions to Azure Storage.

Tomas Hensrud Gulla | Jun 26, 2025 |

Enable Opal AI for your Optimizely products

Learn how to enable Opal AI, and meet your infinite workforce.

Tomas Hensrud Gulla | Jun 25, 2025 |

Deploying to Optimizely Frontend Hosting: A Practical Guide

Optimizely Frontend Hosting is a cloud-based solution for deploying headless frontend applications - currently supporting only Next.js projects. It...

Szymon Uryga | Jun 25, 2025

World on Opti ID

We're excited to announce that world.optimizely.com is now integrated with Opti ID! What does this mean for you? New Users:  You can now log in wit...

Patrick Lam | Jun 22, 2025

Avoid Scandinavian Letters in File Names in Optimizely CMS

Discover how Scandinavian letters in file names can break media in Optimizely CMS—and learn a simple code fix to automatically sanitize uploads for...

Henning Sjørbotten | Jun 19, 2025 |