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.
class TemplatesController < ApplicationController
def search
@templates = Template.search(params[:search])
flash.now[:notice] = "Your search results for #{params[:search]}"
flash[:alert] = "Alert message"
p session[:flash]
end
end
#logs
{"discard"=>["notice"],
"flashes"=>{"notice"=>"Your search results for #{Value of search params}",
"alert"=>"Alert message"}}
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]
.
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.
class TemplatesController < ApplicationController
def search
@templates = Template.search(params[:search], params[:template])
flash.now[:notice] = "Your search results for #{params[:search]} with template #{params[:template]}"
flash[:alert] = "Alert message"
p session[:flash]
end
end
#logs
{"discard"=>[], "flashes"=>{"alert"=>"Alert message"}}
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.