When a user logs in to our website, there are some things we wish to check:
Now, currently, it's a rather dumb implementation. At first, all of this was checked on every page. Rather expensive, so now only on the critical pages. Multiple trips to the database, etc etc...
In profiling, I found that the most time is spent here. So I want to speed this up. So far, I see two options:
Add a couple of columns to the user table, namely LastCheckedOpenTasksTimeStamp
and LastOpenTask
and ForceReCheck
. Downside: Anytime anything happens in the application that is related to such a task (e.g. paying) we have to set ForceReCheck
or some other invalidation mechanism. Seems prone to errors to me.
Some kind of database view that computes what needs to be done. But this is very low level for something that is essentially business logic.
I'm sure there must be a better way that I'm not seeing. What may be better alternatives to do this?
Use a session.
Person logs in, you hit the DB one time and set:
Session["emailVerified"] = checkEmailVerified();
Session["licenseType"] = getLicenseType();
Session["expirationDate"] = getSubExpDate();
// etc.
Then when the person performs any action, you can reference the session instead of making more round trips to the database.
You can go back to the DB if any of the session variables don't evaluate the way you want them to.
I specifically would not use Cache because your data is tied to the user, for each person who is logging in. Fuller explanation here, but the most important bit is:
The first main difference between session and caching is: a session is per-user based but caching is not per-user based, So what does that mean? Session data is stored at the user level but caching data is stored at the application level and shared by all the users.
You can use Cache for this kind of info. You retrieve it from database, and you invalidate that cache once you update any of their fields.
And the logic to retrive that will see if the cache variable is null, you recalculate it.
Here you can see several approaches, depending in what robust or extensible you want it to be: How to cache data in a MVC application