Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deal with session left open

I am implementing a session structure.

I have a ConcurrentDictionary on server side holding on to all the <SessionId, UserSession> pairs.

When a new connection is established a cookie is assigned to a client browser, perm or temp depending on the RememberMe option.

When clients call the LogOut function it removes the session from the dictionary.

However, when the client browser is simply closed or crashed, and cookie was lost or expired or deleted, the server side session object in memory is remained in dictionary and becomes a ghost. Over time these ghosts will stack up.

My question is, how to improve the design so that the dead sessions can be cleaned up after they are expired?

I thought about making a timer service running a cleaning schedule, but it feels not elegant. Is there a simpler way to do this without depending on an external service?

like image 303
Tom Avatar asked Sep 27 '13 23:09

Tom


1 Answers

i have similar situation in one of my project.

instead of dictionary, i used cache with a short absolute expiration and session id of user as my cache key:

HttpContext.Current.Cache.Insert(sessionID, userEntity, null, DateTime.Now.AddSeconds(30), TimeSpan.Zero);

and in the client side, i make an ajax call,every 15 seconds, to notify the server and renew the cache for that session id.

so whenever a user close his browser window, server doesn't recieve any notification and session id of user expired automatically.

like image 132
Emad Feiz Avatar answered Sep 21 '22 23:09

Emad Feiz