"IndexOutOfRangeException" is thrown during in-memory caching


Description

Under heavy load, when the memory cache gets modified concurrently, IndexOutOfRangeException might be thrown. The following message can be found in the logs:

System.IndexOutOfRangeException: Index was outside the bounds of the array.
   at System.Collections.Generic.List`1.Add(T item)
   at Sitecore.Commerce.Engine.Connect.CommerceMemoryCacheStore.Set(String key, ICachable value, CacheEntryOptions entryOptions)
   at Sitecore.Commerce.Engine.Connect.CommerceMemoryCacheStore.<>c__DisplayClass7_0.b__0(KeyValuePair`2 value)
   at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
   at System.Threading.Tasks.Task.WhenAll(IEnumerable`1 tasks)
   ...

The issue occurs intermittently.

Solution

To resolve the issue, consider one of the following options: