Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Caching user data to avoid excess database trips

After creating a proof of concept for an ASP.NET MVC site and making sure the appropriate separation of concerns were in place, I noticed that I was making a lot of expensive redundant database calls for information about the current user.

Being historically a desktop and services person, my first thought was to cache the db results in some statics. It didn't take much searching to see that doing this would persist the current user's data across the whole AppDomain for all users.

Next I thought of using HttpContext.Current. However, if you put stuff here when a user is logged out, then when they log in your cached data will be out of date. I could update this every time login/logout occurs but I can't tell if this feels right. In the absence of other ideas, this is where I'm leaning.

What is a lightweight way to accurately cache user details and avoid having to make tons of database calls?

like image 392
Dinah Avatar asked Jan 15 '10 20:01

Dinah


People also ask

What is the best caching strategy that ensures that data is always fresh?

Write-through ensures that data is always fresh, but can fail with empty nodes and can populate the cache with superfluous data. By adding a time to live (TTL) value to each write, you can have the advantages of each strategy. At the same time, you can and largely avoid cluttering up the cache with extra data.

What is the best caching strategy?

A cache-aside cache is the most common caching strategy available. The fundamental data retrieval logic can be summarized as follows: When your application needs to read data from the database, it checks the cache first to determine whether the data is available.

When should you cache data?

Caches are generally used to keep track of frequent responses to user requests. It can also be used in the case of storing results of long computational operations. Caching is storing data in a location different than the main data source such that it's faster to access the data.


2 Answers

If the information you want to cache is per-user and only while they are active, then Session is the right place.
http://msdn.microsoft.com/en-us/library/system.web.sessionstate.httpsessionstate.aspx

like image 85
AUSteve Avatar answered Oct 21 '22 20:10

AUSteve


What you're looking for is System.Web.Caching.Cache

http://msdn.microsoft.com/en-us/library/system.web.caching.cache.aspx

like image 35
willbt Avatar answered Oct 21 '22 20:10

willbt