Reputation: 6579
I'm just wondering why storing session in database? Is there any advantage to storing session in database?
Upvotes: 13
Views: 6973
Reputation: 21
another advantage is to handle session expiry on the server side as described in section 2.9:
http://guides.rubyonrails.org/security.html
"However the client can edit cookies that are stored in the web browser so expiring sessions on the server is safer."
class Session < ActiveRecord::Base
def self.sweep(time = 1.hour)
if time.is_a?(String)
time = time.split.inject { |count, unit| count.to_i.send(unit) }
end
delete_all "updated_at < '#{time.ago.to_s(:db)}' OR
created_at < '#{2.days.ago.to_s(:db)}'"
end
end
Upvotes: 2
Reputation: 2244
one less obvious and small advantage to having the sessions in the database is that if you need to count current sessions and see the names of other logged in users it is easier to implement than if you were using cookies only to store session data or memcached.
Upvotes: 3
Reputation: 146
There are at least three reasons I can think of. If you save the session in the DB you can:
Upvotes: 8
Reputation: 34340
The advantage to the database or memcached is that session data cannot be tampered with on the client side and that you can store a larger amount of data than you would with cookies (4kB).
If your session is stored in cookies or the database and the web service is restarted then the session data is not lost. It may only be lost if it is stored in memcached.
If the server is load balanced then the session data is passed to the web server that is serving the request, so this is not an issue with cookies, database, or memcached sessions.
The advantage of cookies over memcached or the database is that the client stores the session data, so the server is not responsible for it.
Keep in mind that either way cookies will be passed to and from the client because a session reference still needs to be maintained.
Upvotes: 27
Reputation: 2028
The two reasons I can think of are that:
1) If the web service is restarted, the session data is not lost
2) In a load balanced environment, the session data is stored in a central location, meaning any server can serve the request and have access to the session data.
Upvotes: 19