This is an excerpt from my senior engineering project on how we use sessions for mealmate.co
A session is a small bit of information that a web application is able to store on the server side. For the purposes of mealmate we use them to store information across http requests. A general example of this could be storing a logged in user’s secret key across requests so they are able to access restricted pages.
As we were developing the application a design feature we wanted to implement was allowing users to use the application whether they are signed in or not. We believed that this would be a great way to set us apart from many of the applications that already exist in the market. Most of the current applications only allow users to view a small subset of their application and require logging in to view the rest. What we accomplished was allowing users to freely use the site up until anything needs to be saved our database, at which point sign in is required.
A use case for this can be observed when a user wants to create a new meal plan. The user creating the meal plan could be in one of two states, either logged in or not logged in. Users who are logged in have user_stats associated to them, this is where we store information such as height, weight, age, calorie intake…etc. If they are signed in we can grab that information from the database and place it into a session. If the user is not logged in then we will present them a ‘stats’ form which will be used to calculate their daily nutrition. This information will then be stored into a session.
From the chart we can see that the meal plan logic does not need to know if the user is signed in or not. It will be passed the session hash and perform the same no matter what the users current state is.
Drawbacks of sessions and simulating ‘sudo’ sessions
A Rails design we were not familiar with prior creating this design was that a session is only able to hold 4kb of information at a time. Our sessions were storing user information as well as recipes to be added for a given day of the week. We began seeing overflow errors when users added too many recipes to a meal plan. To combat this we needed to create a ‘sudo’ session, a block of code that acts as a session but is stored and retrieve from the database as opposed to memory. In order to achieve this we created methods to serialize and unserialize a ruby hash. Adding to the session would work in the following way,
This pattern allowed us to create hashes very large in size without the need to worry about overflow errors. It does however, have the drawback of being slower than an in memory hash. However for our needs, we believe that the time tradeoff is well worth it for the extra amount we are able to store.