0

I have web app using a .net API with a controller Filter that gets the token and grabs the user out of the database every time. I am trying to eliminate the same database call, so I have used MemoryCache.

 public ObjectCache cache = MemoryCache.Default;

 // setting it, and only calling database again if cache is empty
 cache.Set("cachedUser", userFromDB, policy);

My problem is I opened another browser and logged in as a different user and I can see the first user still being cached in the debugger. Is the debugger scope causing this to happen, or will multiple users on their own browser sessions each have their own cache object? I am unsure if user A will stay cached locally and User B will stay cached locally, or user A will stay cached and user B will be mistaken for User A.

brett
  • 261
  • 1
  • 5
  • 16
  • Interesting, perhaps keying by session ID might be helpful? – IronMan Feb 05 '20 at 23:44
  • i thought of that, but I may have thousands of users. So I would assume thousands of Cache keys would be too many. – brett Feb 05 '20 at 23:45
  • 1
    MemoryCache lives on the server, it is stored in memory. If you put something in MemoryCache, it is going to stay there until it expires or until the server restarts, or you manually remove it. – JohanP Feb 05 '20 at 23:59
  • @JohanP So caching a database user with a key like "user" would persist across multiple sessions? Would you recommend caching each user with a different key? – brett Feb 06 '20 at 00:02
  • @brett Yes, if you don't have a unique key for setting a user in your cache, you will end up with one user in your cache that will constantly change out under you. – JohanP Feb 06 '20 at 00:04
  • 1
    @brett Also keep in mind that a MemoryCache is for one server. If your app runs in a server farm or multiple containers, they will not persist across. – JohanP Feb 06 '20 at 00:06
  • @JohanP Thank you, for some reason I thought the key persisted only on each session. It is ok if another server does not have the cache because if it doesn't it just fetches it again. I just hope having potentially thousand of keys (with 20 minute expiration) isn't over doing it. – brett Feb 06 '20 at 00:12

1 Answers1

1

Your cache key is "cachedUser". Since the key is not unique for every user, the same result will be retrieved.

Once fix would be to cache on a unique field such as UserId. Something along the lines of -

cache.Set(userFromDB.Id, userFromDB, policy);

This is assuming that each user has a unique Id

Tejas Parnerkar
  • 201
  • 1
  • 5