skip to content

In Rails, what happens when a cookie-store session outgrows 4 KB, and when would you switch config.session_store to :cache_store instead?

level: seniorimportance: should knowfreq 40%

answer

  1. ActionDispatch::Cookies::CookieOverflow
  2. checked after encryption and encoding
  3. only an id in the cookie
  4. Rails.cache decides durability
  5. :null_store in the test environment

basics

~20 s

Rails raises ActionDispatch::Cookies::CookieOverflow when the encrypted session cookie exceeds 4096 bytes. First move bulky data into tables; switch to :cache_store when sessions must be large or revocable, accepting that cache eviction or a non-persistent cache store loses sessions.

solid answer

~40 s

The cookie store checks the cookie's name plus its encrypted, Base64-encoded value against `MAX_COOKIE_SIZE` (4096 bytes) when the session is written at the end of the request, and raises `ActionDispatch::Cookies::CookieOverflow` ("_bakery_session cookie overflowed with size ... bytes"), so the user gets an error. Encryption overhead means the usable payload is well under 4 KB. The usual fix is to stop putting records or long lists in `session[]` and keep an id. If you truly need server-side sessions, `config.session_store :cache_store` puts only a session id in the cookie and the data in `Rails.cache` (or a `cache:` you pass), with `expire_after` defaulting to the cache's `expires_in`. The price is that sessions are as durable as that cache: evictions empty sessions, and in a new app development uses `:memory_store` and test uses `:null_store`.

code

ruby · 10 lines
ruby
# config/application.rb
config.session_store :cache_store,
  key: "_bakery_session",
  expire_after: 2.weeks

# config/environments/test.rb
# The default :null_store would drop every session between requests.
config.session_store :cache_store,
  key: "_bakery_session",
  cache: ActiveSupport::Cache::MemoryStore.new

go deeper

for a junior

Recall that the cookie session is limited to about 4 KB and that Rails raises ActionDispatch::Cookies::CookieOverflow when it is exceeded.

for a middle

Explain that the size check runs on the encrypted cookie, why ids beat records in session, and what :cache_store's key, cache and expire_after options do.

for a senior

Show you trace an overflow to the data that grew, keep sessions small, and know the cache store's eviction, per-environment cache and test :null_store traps.

for a principal

Decide between a stateless cookie session and server-side storage by weighing revocation, size, operational durability and the cost of signing users out on eviction.

## How the 4 KB limit is enforced With `:cookie_store`, the session hash is serialized, encrypted and written as one cookie when the request finishes. Action Dispatch's encrypted cookie jar then runs a size check: - it adds the cookie **name** (`_bakery_session`) to the **final** value, which is the ciphertext plus nonce and authentication tag, Base64-encoded; - if the total is over `ActionDispatch::Cookies::MAX_COOKIE_SIZE`, **4096 bytes**, it raises **`ActionDispatch::Cookies::CookieOverflow`** with a message naming the cookie and its size. Because the check runs on the encrypted form, the plaintext budget is noticeably smaller than 4 KB. The flash is part of the session, so long flash messages count too. ## What the failure looks like A bakery pre-order app starts storing the whole basket in the session: ```ruby session[:basket] = current_basket.line_items.map(&:attributes) ``` It works for three items and fails for twelve. The error is raised while the response is being finished, after the action has run, so the customer sees an error page and the basket change is not saved in the cookie. It only appears for **some** users, the ones with big baskets, which is why it is often found in production. ## First fix: store less | Instead of | Store | |---|---| | the basket's line items | `session[:basket_id]` and a `baskets` table | | a search form's full filter set | a short query string in the URL | | a cached API response | `Rails.cache`, keyed by user or basket | | a long flash message | a short one, or a page that explains | The session should hold **identifiers and small flags**. This keeps every request's `Cookie` header small as well, since the cookie is sent with each request, assets included. ## Second option: a server-side store When the session itself must hold more, or must be revocable on the server, change the store: ```ruby # config/application.rb config.session_store :cache_store, key: "_bakery_session", expire_after: 2.weeks ``` `ActionDispatch::Session::CacheStore` keeps an opaque **session id** in the cookie and the hash in the cache under a key built from it (`"_session_id:"` plus a hashed form of the id). Its options: - `cache:` picks the cache; by default it is `Rails.cache`. - `expire_after` sets the entry's lifetime; by default the cache's own `expires_in`. - `check_collisions` makes it verify a new id is unused, at the cost of an extra write. Other choices: `:mem_cache_store` (`ActionDispatch::Session::MemCacheStore`), or a store gem such as `activerecord-session_store`, which keeps sessions in a database table. ## What the cache store costs 1. **Durability is the cache's.** The Rails guide puts it plainly: such sessions "could disappear at any time". An eviction under memory or size pressure empties that user's session, signing them out if sign-in state lives there. 2. **Environment differences.** A new app sets `config.cache_store = :memory_store` in development, which is per process and lost on restart, and `:null_store` in **test**, which stores nothing, so sessions vanish between requests in integration tests unless you give the session store its own `cache:`. 3. **Production setup.** Production uses whatever `config.cache_store` the app configures; Rails 8 apps install Solid Cache for it, which keeps entries in a database, so the session's life depends on that store's size and age limits. 4. **One more lookup per request** that reads the session. ## Choosing | Need | Store | |---|---| | small data, no server state, simplest deploy | `:cookie_store` (default) | | larger sessions, or `reset_session` that removes the server copy | `:cache_store` on a durable cache | | sessions as rows you can query and audit | a store gem with a table | Signing users in with server-side records, as Rails' authentication generator does, is a separate design and does not require changing the session store.

  • Why can a 3 KB session still raise CookieOverflow?
    The 4096-byte check runs on the cookie name plus the final value: the JSON payload after encryption adds a nonce and authentication tag, and Base64 encoding grows it by about a third. A few kilobytes of plaintext can therefore exceed the limit.
  • Why do integration tests sign users out after switching to :cache_store?
    A new app's `config/environments/test.rb` sets `config.cache_store = :null_store`. The cache session store defaults to `Rails.cache`, so every write is thrown away and each request starts with an empty session. Give the session store its own `cache:` in the test environment, or use a real store there.

  • Rails truncates an oversized session cookie and carries on without an error
  • the 4 KB limit applies to the plaintext session hash before encryption
  • :cache_store sessions are as durable as database rows
  • switching to :cache_store needs no change for the test environment
  • the cookie store keeps a server copy, so reset_session can revoke stolen cookies