activerecord-session_store icon indicating copy to clipboard operation
activerecord-session_store copied to clipboard

Resolving "session not found" on server running puma in clustered mode

Open nkokkos opened this issue 1 year ago • 0 comments

Hello, this is not really an issue but something I found that resolved the problem I had. So I wanted to share it with you. Probably, there has been talk in forums and this is not a issue with active record store, but with other frameworks too (other languages and frameworks running servers in clustered mode)

Problem:

I signed in users using active record store on a server that ran about 12 puma server in clustered mode. I looked at my logs and I saw that after signing in my users, some users would lose their session and be directed back to the sign in page. I saw that these users were handled by a different puma server(cold start maybe). That caused that these users could not load their session correctly. Probably race condition with database? First puma server handled the assignment of the session key but did not save in the database immediately. And the second puma server that handled the user could not load the session key fast enough. So, I searched the net and I found out this code fixed my problem. This is kind of paranoid but it ensures that when you assign a session key, you just make sure it gets saved into the database, so any other puma server (even the ones just cold starting) can pick up the changes.

Set my session key here:

session[:my_session_variable] = some value

Force immediate DB write

session_id = session.id.to_s ActiveRecord::Base.transaction do session_record = ActiveRecord::SessionStore::Session.find_or_initialize_by( session_id: session_id ) session_record.data = session.to_hash session_record.updated_at = Time.current session_record.save! end

Force connection to sync (ensures commit is flushed)

ActiveRecord::Base.connection.execute("SELECT 1")

nkokkos avatar Oct 13 '25 07:10 nkokkos