Grails 3 -store session data in controller with scope='session'? - grails

Somehow it seems like it might be a bad idea, but wondering if it recommended or not when you are using session scope in a controller to store session data in controller fields, say for example, as a kind of caching for user data so you have don't have to keep hitting the db to get frequently requested information for a particular user?
And, by the way, just wondering how long the server holds on to the controller instance in that case. If someone leaves the browser tab open for a week, not using it, does the controller instance for that session hang around indefinitely consuming resources on the server?

You could, use a controller like that, but why not just simply use a cache instead? There are lots of really good caches out there (Spring cache for instance) which will likely be more extensible than this approach.
Session management (and when they expire) is handled by your application container (e.g. Tomcat, JBoss, Websphere, etc.). In most cases without interaction with the server (e.g. hitting a URL or page) they expire after a default of 20 minutes. So once a session expires, the session scoped controller instance becomes a candidate for being cleaned up and removed.

Related

is Sessionscope put any impact on the application performance?

In many of my bean classes, I've used session scope. I just want to know does it cause any performance issue like server overhead, memory issues etc.
Abusing session scope and putting beans which should live only in view or request is not good idea for at least two reasons:
User experience - as user will see some old data stayed on pages that he visited during that session, which is in most cases bad behavior (almost always when you enter some inputs leave page and return to that page you expect that data to be reset but you will see old data)
Memory consumption - as it is obvious session scoped beans will live as long as session lives and they will occupy some memory. This is maybe not really huge memory consumption but it can be important especially when sessions is old (for example few hours). Session data in that case will be bigger during the time
I don't have to say anything new, you should see few more links:
How to choose the right bean scope?
Managed bean scopes
I would just add note for another answer. As long as cookies in your browser are enabled size of HTTP request will not increase. Session is kept just on server, on client is just added JSESSIONID cookie which keep ID of current session.

What is the lifespan of each data storage area in ASP .net MVC

I've seen some explanations of these, but nothing that really compares where they start, end, or overlap, or good examples of their use.
What is the life span of each of the following data collections? And am I missing any?
Application
Session
ViewData
TempData
application: as long as your application is running. your application may be automatically shutdown and restarted by the server for various reasons
session: as long as the user is actively using your site. this is generally determined by cookies that ASP.NET sends down to give each user a unique ID that expires after a while. there are lots of ways to customize & tweak this to meet various needs
viewdata: as long as the current request is being processed. this is used for sending data from a controller to a view for immediate rendering and thus not persisted
tempdata: until the value is read back out OR until the end of processing the next request in the session OR when the session ends/expires - whichever is sooner. this is meant to be used for moving data from one controller to another when you are issuing a Redirect
Application : This get initiated at the time when an application start and end when the application stops the execution.If user leaves the application domain or application gets restarted then also the application based data is lost.
Session : This is application based storage. This ends when user leaves the current request or the session get expired. It can be stored in several modes like application cookie or client side cookie.
ViewBag & ViewData : This storage method hold the data for the current request. It transport the data between view and controller.
TempData : Lifespan of this storage type depends on, at which request the Tempdata is read. Once it is read by program it gets destroyed. But we can increase its lifespan using peek or keep methods.

Is it possible for Rails sessions to be created 'just in time'?

My understanding of the session lifecycle in Ruby on Rails (specifically v3 and upwards) is that a session is created at the start of a request, for each and every request, and if that request doesn't carry an existing session cookie a new one will be created, otherwise the session cookie is deserialized and stored in the session hash.
The purpose of this, of course, supports a number of security features such as CSRF etc.
However, this poses a bit of an issue when it comes to caching of pages in a site with HTTP cache services and proxies such as Varnish, as most of the configurations tend to strip out these (generally all) cookies on both the request and response end (as the cache is usually intended for a generalized audience).
I know that it is possible to setup Varnish etc to create the object hash with the cookie details included, and this would scope the cached data to that session (and therefor that user), however I am wondering if this is completely necessary.
I have an application which is fairly 'static' in nature - content is pulled from a database, rendered into a page which can then be cached - there are a few elements (such as comment count, 'recent' items etc) which can be added in with an ESI, but for every request Rails still tends to want to setup a new session, and when a user already has a session this stuff is stripped out by the cache server.
I am wondering if it might be possible (via pre-existing functionality, or building the functionality myself) to allow the developer to control when a session is required, and only when that is specified is the back-and-forwards with cookies, session initialization/deserialization etc necessary.
That, or I am thinking about this problem the wrong way and need to address the issue from another angle...
From what I know rails sessions can be controlled fairly in-depth via ActionController::SessionManagement
http://ap.rubyonrails.org/classes/ActionController/SessionManagement/ClassMethods.html#M000070
There are examples in the API docs of disabling it per action, per controller, etc.
If your site is mostly static then you may want to use full page caching. This takes Rails out of the request entirely and let's the web server deal with it once the content has been generated. Might cause some serious headaches depending on your exact needs as far as the comment counts and user-specifics though.

what is the best way to cache user information in my basecontroller in asp.net mvc

on each controller call i have a code that gets some user properties from a webservice. I want to cache these for each user so i only hit the webservice once.
what is the best way to cache code in a controller method so it will allow me to avoid hitting the database on every URL request but also not cache one users info when another user logs on?
You could use the ASP.NET session to store per user values.
Check out the caching piece of the Enterprise library. We use it at work to cache lookups, so you only hit our WCF services once, instead of thousands of times for the exact same data.
You can also use Session, which I highly advise against unless your user is very small.
if (Session("user") == null)
{
Session("user") = CallWebService.GetUser(userId);
}
Why you should keep Session small, for this webpage:
Avoid storing too much data in session variables, and make sure your session timeout is reasonable. This can use a significant amount of server memory. Keep in mind that data stored in session variables can hang out long after the user closes the browser. Too many session variables can bring the server on its knees.

My Rails session is getting reset when I have concurrent requests

I think I might be misunderstanding something about Rails sessions, so please bear with me, I might not be phrasing my question the best way.
I'm working on an iPhone app with a Ruby on Rails backend. I have a web view which by default goes to the index action of one controller (and uses sessions), and in the background a bunch of API calls going to a different controller (and which don't need to use sessions).
The problem is, the sessions set by my web view seem to be overwitten by the API calls. My staging server is pretty slow, so there's lots of time for the requests to overlap each other - what I see in the logs is basically this:
Request A (first controller) starts. Session is empty.
Request B (second controller) starts. Session is empty.
Request A finishes. Request A has done authentication, and stored the user ID in the session. Session contains user ID.
Request B finishes. Session is empty.
Request C starts. Session is empty - not what I want.
Now, the strange thing is that request B should NOT be writing anything to the session.
I do have before and after filters which READ from the session - things like:
user = User.find_by_id(session[:id])
or
logger.debug session.inspect
and if I remove all of those, then everything works as expected - session contents get set by request A, and they're still there when request C starts.
So. I think I'm missing something about how sessions work. Why would reading from the session overwrite it? Should I be accessing it some other way? Am I completely on the wrong track and the problem is elsewhere?
Thank you for any insights!
This is the result of a race condition caused by how rails handles session. See http://www.paulbutcher.com/2007/05/race-conditions-in-rails-sessions-and-how-to-fix-them/
It seems like you can't have concurrent requests modifying session reliable. The solution is to use a different method of storing session (e.g. active_record or redis) or you could eliminate the concurrent requests.
Your sessions are maybe cookie based. If that's the case then each of request is starting with the same cookie(session). The cookie holds the session content. Try switching the storage to be on the server. But I in your case with the authentication I think it would be much better to not do this async.
Request A (first controller) starts. Session is empty.
Request B (second controller) starts. Session is empty.
Request A finishes. Request A has done authentication, and stored the user ID in the session. Session contains user ID
.....AND returning the session content in a cookie.
Request B finishes. Session is empty.
THIS one is setting blank session.
Request C starts. Session is empty - not what I want.
Thats because B has set reset the session
It's possible this is because you are storing the user id as ":id" in the session object. :id may be a reserved key in the object. Try using a different name such as session[:user_id].
Good luck!

Resources