---
title: "Rails 5 Discard some flash messages to trim storage"
description:
  "Rails 5 trims down session storage by removing discarded flash messages
  before persisting into the session"
canonical_url: "https://www.bigbinary.com/blog/rails-5-trims-session-storage-by-discarding-some-flash-messages"
markdown_url: "https://www.bigbinary.com/blog/rails-5-trims-session-storage-by-discarding-some-flash-messages.md"
---

# Rails 5 Discard some flash messages to trim storage

Rails 5 trims down session storage by removing discarded flash messages before
persisting into the session

- Author: Abhishek Jain
- Published: August 23, 2016
- Categories: Rails 5, Rails

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.

### Cookie overflow issue with Rails 4.x

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.

```ruby

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]` .

### Rails 5 removes discarded flash messages

In Rails 5,
[discarded flash messages are removed](https://github.com/rails/rails/pull/18721)
before persisting into the session leading to less consumption of space and
hence, fewer chances of `CookieOverflow` being raised.

```ruby

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`.

## Links

- [Human page](https://www.bigbinary.com/blog/rails-5-trims-session-storage-by-discarding-some-flash-messages)
