The thing about Session is you read some articles about how it works. You think you understand it well but you are still struggled to apply that effectively.
I have also struggled to manage and apply Sessions in my Session sensitive web apps.
Then I just made an abstract pattern to memorize how the session works for myself.
[“SessionName”, “BrowserId”] = Value(The value that we want to store in Session)
Let’s say our program is already deployed in web server and there is one user who logins and it’s Id would be stored in Session[“UserId”].
For that user, the program will check there is already session name with “UserId” and if it is, it will keep on checking it’s “Browser Id”, if both “Session Name” which is “UseId” and “BrowserId” are already there, it will override the existing value otherwise it will create a new value.
[“UserId”, “b1”] = 1
Even though all the users access the Session Name “UserId” parallel , that doesn’t make the values overwrote because they access from different browsers.
So the values would be like
[“UserId”, “b1”] = 1
[“UserId”, “b2”] = 2
[“UserId”, “b3”] = 3
If one different user try to access the same program with the same browser (let’s say “b3” and it’s UseId is 5).
[“UserId”, “b3”] = 3 (Already existed one)
[“UserId”, “b3”] = 5 (The value 3 would be overwritten because both “UserId” and “browserId” are the same.)
The most distinct example in real life is FaceBook. We try to login Facebook with one user(Eg. Ken) then open another tab and try to login with different user(Eg.John). When you try to refresh the page of “Ken” , it will be updated to “John” page. Because it is overwritten by userId of “John” and they just used the same browser.
[“UserId”, “b1” ] = 1 (Id of “Ken”) is overwritten by
[“UserId”, “b1” ] = 2 (Id of “John”)
I just want to point out again that this is just an abstract pattern that I came up with just try to avoid mistakes and not to mess up if your app use so many sessions and depends on it a lot. This does not necessarily mean Session works exactly that way.
Even though it is OK that we could make an abstract pattern and use that to memorize, it is still very important to know how it really works behind and I suggest you guys keep reading about that.
Thanks and any suggestion is welcomed.
Edited : Thomas Junk explained really well how it really works behind in the comment.