eShopOnWeb Architecture (8/16) – uses in memory caching to avoid sending unnecessary queries to the DB

To improve performance eShopOnWeb uses IMemoryCache to implement in memory caching to prevent queries being sent to the Database for data that doesn’t change at all or often.

In the case of the GetCatalogItems method below, we can see it will only call the non cached version of GetCatalogItems if the catalog items are not already cached. Each time we hit the cache we ‘save’ the three queries below… Depending on the amount of users and the exact queries used, implementing caching can make a big difference to the performance of an app but don’t implement it if you don’t need it.

IMemoryCache in a distributed environment?

eShopOnWeb uses IMemoryCache which is a local in memory cache, does this mean we can’t use IMemoryCache in a multi-host environment? Not necessarily, it will depend on what kind of data we are actually caching.

If for example we are caching static items which rarely change for display in dropdowns such as Brands or Types as shown above using local in memory caching may be OK. The only downside is that the first request for an item on a new host will hit the DB but this is a small price to pay for a simpler architecture.

If on the other hand we are caching data which might change, for example a product description the problem of invalidating that products entries in all local in memory caches will likely make using a centralized cache like Redis more appropriate.

Do we need both CachedCatalogViewModelService and CatalogViewModelService?

eShopOnWeb has two implementations of ICatalogViewModelService, CachedCatalogViewModelService which implements caching and is basically a wrapper (or decorator) around CatalogViewModelService which doesn’t implement caching. One advantage this gives us is that we can easily turn off caching for this service by swapping out the implementations in our DI configuration..

Of course an alternative is to have no interfaces and a single catalog ViewModel service class which takes in an instance IMemoryCache and has the caching code embedded. There is no right or wrong answer, I’m just thinking out loud… what would you do?

One thought on “eShopOnWeb Architecture (8/16) – uses in memory caching to avoid sending unnecessary queries to the DB”

Leave a Reply

Your email address will not be published. Required fields are marked *