Rails Sessions
I was doing some maintenance on my blog, and was devastated to find that Typo was taking 225 megabytes of resident RAM. Yikes! After some creative debug thinking and digging I figured out it was due to sessions. Typo now stores sessions in the database, so my maintenance cron job to delete old sessions didn’t clean up old sessions. (Ha! had you going for a second!)
Well I could write a cron job to run a script to clean the sessions out of the db, like:
#!/bin/sh
sqlite3 /path/to/typo/db/production.db 'delete from sessions'
Ok, that’s a bit extreme, but you get the idea. But when I deleted the sessions in this manner the memory usage didn’t drop at all until I had restarted the server, which seems unnecessary. So instead I changed typo’s configuration to use a different session store. I commented out this line in config/environment.rb:
- config.action_controller.session_store = :active_record_store
+ #config.action_controller.session_store = :active_record_store
Then I restarted the server and fired up a browser. “Huh, that’s odd… no sessions in tmp/sessions or /tmp or anywhere I can see. No, they’re not in the database…” What I was seeing didn’t match up with what all the stuff Google said. The default session store was PStore, aka file system, so they said. But apparently that recently changed in Rails, and now the default is CookieStore. From ActionController::Base documentation:
Sessions are stored in a browser cookie that‘s cryptographically signed, but unencrypted, by default. This prevents the user from tampering with the session but also allows him to see its contents.
Do not put secret information in session!
Well a quick grep -ri session app lib told me that typo wasn’t storing
anything secret, so I decided that default was alright with me. Now I don’t
have to set up any session cleanup script at all. Sweet.
Now, don’t stop there. You should set your session key and secret while you’re
hanging out in config/environment.rb. Add the following lines in the same
place as the line you commented out above:
config.action_controller.session['session_key'] = 'something unique'
config.action_controller.session['secret'] = 'get this from rake secret'