Flash messages and cookie overflow

Cookie overflow

The problem

In Rails, flash messages are persisted among requests thanks to session storage. This is commonly used to persist feedback that needs to be sent to the user after a redirect. Pretty useful stuff!

If you are using cookie storage for your session, which is the default storage strategy for sessions, you are under some limitations. Specifically the cookies have a limit of 4kb.

Now, let’s imagine that you want to store feedback for the user, but actually you want to store a lot. For example, imagine that you have an endpoint that allows processing a batch of unlimited things, and you want to give feedback for each of them. It happens to be that you are not giving the feedback on the same page, but you are actually redirecting somewhere else. Like this:

def process_batch_form
# This returns an array of messages, such as: [“Team 1 could not be updated”, “Team 2 updated properly”, ...]
results = FormTeamProcessor.process(params[:batch_of_teams])
flash[:message] = results.join(“, “)
redirect_to :somewhere

If that batch of things is big, you are in trouble. Your session might already be storing some stuff, and if you are putting all that information into the flash message, you are likely to overflow your cookies.

The solution

The solution really depends on the nature of the problem you are trying to solve by using the flash message. In my case, returning instant feedback to the user wasn’t that critical, so I was able to just add a summary of the feedback into the flash hash, and send an email with more detailed information to the end user.

The most important thing to take into account is the fact that if you are using cookie based session storage, you have limited amount even though from a code perspective it might thing you have unlimited amount of memory to play with that hash.