Rails 5 Discard some flash messages to trim storage

Abhishek Jain

Abhishek Jain

August 23, 2016

This blog is part of our  Rails 5 series.

Rails, by default, stores session data in cookies.

The cookies have a storage limit of 4K and cookie overflow exception is raised if we attempt to store more than 4K of data in it.

Flash messages are persisted across requests with the help of session storage.

Flash messages like flash.now are marked as discarded for next request. So, on next request, it gets deleted before reconstituting the values.

This unnecessary storage of discarded flash messages leads to more consumption of data in the cookie store. When the data exceeds 4K limit, Rails throws ActionDispatch::Cookies::CookieOverflow.

Let us see an example below to demonstrate this.

1
2class TemplatesController < ApplicationController
3def search
4@templates = Template.search(params[:search])
5flash.now[:notice] = "Your search results for #{params[:search]}"
6flash[:alert] = "Alert message"
7p session[:flash]
8end
9end
10
11#logs
12
13{"discard"=>["notice"],
14"flashes"=>{"notice"=>"Your search results for #{Value of search params}",
15"alert"=>"Alert message"}}
16

In the above example, it might be possible that params[:search] is large amount of data and it causes Rails to raise CookieOverflow as the session persists both flash.now[:notice] and flash[:alert] .

Rails 5 removes discarded flash messages

In Rails 5, discarded flash messages are removed before persisting into the session leading to less consumption of space and hence, fewer chances of CookieOverflow being raised.

1
2class TemplatesController < ApplicationController
3def search
4@templates = Template.search(params[:search], params[:template])
5flash.now[:notice] = "Your search results for #{params[:search]} with template #{params[:template]}"
6flash[:alert] = "Alert message"
7p session[:flash]
8end
9end
10
11#logs
12
13{"discard"=>[], "flashes"=>{"alert"=>"Alert message"}}
14

We can see from above example, that flash.now value is not added in session in Rails 5 leading to less chances of raising ActionDispatch::Cookies::CookieOverflow.

If this blog was helpful, check out our full blog archive.

Stay up to date with our blogs.

Subscribe to receive email notifications for new blog posts.