1

Can In-Memory caching and Distributed Cache be used together in the same application? Does it make sense after all?

A logic scenario that comes to my mind is to manager Session state (on top of In-Memory, taking advantage of sticky sessions ) and Distributed for other caching. However I don't know if this makes sense after all.

mdebeus
  • 1,928
  • 3
  • 18
  • 27
VMh
  • 1,300
  • 1
  • 13
  • 19
  • Of course you can. You just need to manage cache invalidation which may be a little bit trickier than just using a distributed cache – Tseng Aug 27 '17 at 16:13

1 Answers1

1

Yes, you can. One implements IMemoryCache, other implements IDistributedCache.

IMemoryCache will not work properly if you have non-sticky sessions and multiple servers.

Also you may want to use service.AddDistributedMemoryCache(); instead of service.AddMemoryCache();

cilerler
  • 9,010
  • 10
  • 56
  • 91
  • can you please clear a little both the session? If I use both memory cache and distributed cache. Where the session will store? – sina_Islam Jan 14 '23 at 11:32
  • 1
    To ensure that your cache works properly in a distributed environment, it is recommended to use `IDistributedCache` and `AddDistributedMemoryCache()` instead of `AddMemoryCache()`. This allows you to use the same code for both development and production and switch between different cache providers (such as using memory for local development and Redis for production) without changing the code. Again, `IMemoryCache` is intended for use in a single server environment. – cilerler Jan 17 '23 at 14:09
  • "IMemoryCache is intended for use in a single server environment" this part is very clear to me. But I want to use both memory and distributed cache at production. I can not choose, stand alone Redis (IDistributedCache) for production server because of performance issues. so I want to use distributed cache for a certain portion of the application and a memory cache for other portions. To resolve the inconsistency of the memory cache I am using the pub/sub pattern(Rabbitmq) to clear all the instances. So far no issue but confused about the application session. – sina_Islam Jan 17 '23 at 14:45
  • You can use both as long as you know that `IMemoryCache` won't allow you to distribute. `AddDistributedMemoryCache()` does not implement the distributed memory alternative of `IMemoryCache`; it is there just so people can test their code without needing SQL, Redis, etc. – cilerler Jan 18 '23 at 17:12