In Active Record, how do cache_key, cache_version and cache_key_with_version differ for a record and for a relation, and why are they split?
answer
- stable key, moving version
- products/42 vs updated_at in usec
- relation: query digest, count plus max
- recyclable keys, no dead entries
- cache_versioning since 5.2 defaults
basics
~20 scache_key is a stable name (products/42), cache_version is the changing part (updated_at, or count plus newest updated_at for a relation), and cache_key_with_version joins them. Splitting them lets one entry be overwritten instead of piling up dead keys.
solid answer
~40 sOn a record, `cache_key` is the model's collection name plus id, `products/42` (or `products/new` before saving), and it never changes. `cache_version` is `updated_at` formatted to the microsecond; `cache_key_with_version` glues them with a hyphen for APIs that need one string. A relation answers too: its `cache_key` is `products/query-<digest of the SQL>`, and its `cache_version` is the matching row count plus the newest `updated_at`, which costs one `COUNT`/`MAX` query if the relation is not loaded. They are split because the store keeps the version inside the entry and treats a mismatch as a miss, so a changed record overwrites the same key rather than leaving the old one to be evicted. In a Rails 8.1 app both `cache_versioning` and `collection_cache_versioning` are on through `load_defaults`.
code
ruby · 8 linestent = Product.find(42)
tent.cache_key # => "products/42"
tent.cache_version # => "20261006093015123456"
tent.cache_key_with_version # => "products/42-20261006093015123456"
tents = Product.where(category: "tents")
tents.cache_key # => "products/query-1850ab3d302391b85b8693e941286659"
tents.cache_version # => "24-20261006093015123456" (runs COUNT and MAX)go deeper
Recall that cache_key looks like products/42 and that updated_at feeds the version that makes cached output refresh.
Explain recyclable keys: stable key, version stored in the entry, mismatch treated as a miss, and how a relation computes count plus newest updated_at.
Show the costs and blind spots: the extra COUNT/MAX query, writes that skip updated_at, and old load_defaults that turn versioning off.
Judge when the default updated_at version is not the true freshness signal and how to define one a whole codebase can trust.
## Three methods on every record Active Record's `ActiveRecord::Integration` module gives each model instance three cache-related methods. For a product in an outdoor-gear shop: | Method | Saved product 42 | Unsaved product | |---|---|---| | `cache_key` | `"products/42"` | `"products/new"` | | `cache_version` | `"20261006093015123456"` | `nil` | | `cache_key_with_version` | `"products/42-20261006093015123456"` | `"products/new"` | - `cache_key` is `model_name.cache_key`, the plural collection name, followed by the id. It is **stable** for the life of the row. - `cache_version` is built from `updated_at`, formatted with `cache_timestamp_format` (`:usec` by default), so two saves in the same second still produce different versions. It returns `nil` when the class has `cache_versioning` turned off or the model has no `updated_at` column. - `cache_key_with_version` joins the two with a hyphen, for places that accept only one string. ## Why the key and the version are separate Before Rails 5.2, `cache_key` itself carried the timestamp, along the lines of `products/42-<updated_at>`. Every save produced a brand-new key, the previous entry stayed in the store until something evicted it, and a busy model filled the store with entries nobody would read again. **Recyclable cache keys** replaced that scheme: 1. The store writes the entry under the stable `cache_key`. 2. It records the `cache_version` inside the entry. 3. On read, `ActiveSupport::Cache::Store` compares the stored version with the version supplied by the caller or derived from the key object. A mismatch returns `nil`, exactly as a miss would. 4. The caller recomputes the value and writes it to the **same** key, overwriting the stale entry. The result is one entry per record per use, however often the record changes. That matters most on size-capped stores such as Solid Cache with a `max_size` or `:memory_store` with its size limit, where dead entries would otherwise push out live ones. ## Relations have a key and a version too An `ActiveRecord::Relation` responds to the same three methods, so `cache @products` or `cache [category, category.products]` work in a view: - `cache_key` is the collection name plus a digest of the relation's SQL, for example `"products/query-1850ab3d302391b85b8693e941286659"`. A different `where`, `order` or `limit` gives a different key. - `cache_version` is the **row count** plus the **newest `updated_at`** among the matching rows, for example `"24-20261006093015123456"`. If the relation is already loaded it is computed in Ruby; otherwise Active Record runs one extra query shaped like `SELECT COUNT(*), MAX(updated_at)`, wrapped in a subquery when the relation has a limit or offset. Adding a matching row, deleting one or updating one changes the version. What the version cannot see is a write that leaves `updated_at` alone while the count stays the same, such as `update_all` or `update_columns` without `touch: true`. ## The switches behind it Two class attributes control this, and both are on in a newly generated app: - `cache_versioning` for records, enabled by `load_defaults 5.2`; - `collection_cache_versioning` for relations, enabled by `load_defaults 6.0`. With either off, the version is folded back into `cache_key` and `cache_version` returns `nil`. A Rails 8.1 app runs `config.load_defaults 8.1`, which includes both. An upgraded app that still pins an old defaults version may not, and its fragments then behave the old, key-per-version way. ## Where each one is used - The `cache` view helper takes the **record or relation itself**; the store asks it for `cache_key` and `cache_version` separately, so you rarely call either by hand. - `cache_key_with_version` is for APIs that take one string: a composite string key assembled by hand, or a value for an HTTP validator. - You may **override** `cache_version` in a model when freshness depends on something other than `updated_at`, for example a product whose card shows stock synced from a warehouse feed into an `inventory_synced_at` column. - Loading a record with `select` that omits `updated_at` makes `cache_version` raise `ActiveModel::MissingAttributeError`, a common surprise when a slim query feeds a cached view. ## Mistakes interviewers listen for - Building string keys by hand from `cache_key` alone, as in `"#{product.cache_key}/card"`: the version is lost, so the entry never refreshes. Either pass the record itself or use `cache_key_with_version`. - Assuming the key changes on save and then wondering why the store holds only one entry per product: that is the recyclable design working. - Expecting `cache @products` to notice an `update_all` that leaves `updated_at` untouched: the count and the newest timestamp are unchanged, so the version is too. - Forgetting that every unsaved record shares `products/new`, so a cached block around a new-record form serves one rendering to everyone.
- Why does cache_version raise on a record loaded with Product.select(:id, :name)?The class has an `updated_at` attribute but this instance was loaded without it, so `cache_version` raises `ActiveModel::MissingAttributeError` rather than silently returning `nil`. Include `updated_at` in the `select`, or avoid passing slim records to `cache`.
- When would you override cache_version in a model?When the rendered output depends on data that does not move `updated_at`, such as a column written by a sync job through `update_columns`. Returning a value built from that column, or from both timestamps, makes every cached fragment keyed on the record notice the change without touching the row.
- cache_key changes every time the record is saved.
- A relation's cache_version is a digest of its SQL.
- Recyclable keys mean the store deletes old entries when a row changes.
- cache_key_with_version is what the cache helper puts in its key string.
- Computing a relation's cache_version is free because it reuses loaded rows.
Assumes Rails 8.1 with load_defaults 8.1, which keeps cache_versioning (on since the 5.2 defaults) and collection_cache_versioning (on since the 6.0 defaults) enabled.