skip to content

In an Active Record belongs_to, what do counter_cache: true and touch: true keep in sync on the parent, and what bypasses them?

level: middleimportance: must knowfreq 60%

answer

  1. a column on the parent, not the child
  2. boards.cards_count, atomic increment
  3. size reads it, count still queries
  4. delete_all and update_column skip it
  5. touch sets updated_at, no validations

basics

~20 s

counter_cache: true keeps boards.cards_count up to date on card create, destroy and board change, so board.cards.size needs no COUNT query. touch: true sets the board's updated_at whenever a card changes. Both are callbacks, so delete_all, update_column and insert_all bypass them.

solid answer

~30 s

Both options go on the child's `belongs_to`. `counter_cache: true` maintains a `cards_count` column on `boards` (added by a migration): an atomic increment on card create, a decrement on destroy, and both when a card moves boards. `board.cards.size`, `empty?` and `any?` then read the column, while `count` still runs `COUNT(*)`. `touch: true` sets the board's `updated_at` whenever a card is created, updated or destroyed, without running the board's validations, which is what cache keys rely on. Because both are callbacks, `delete`, `delete_all`, `update_column`, `insert_all` and raw SQL leave them stale; fix counts with `Board.reset_counters(board.id, :cards)`.

code

ruby · 8 lines
ruby
card = board.cards.create!(title: "Fix login")
# UPDATE boards SET cards_count = COALESCE(cards_count, 0) + 1, updated_at = ... WHERE id = 7

board.reload.cards.size      # reads boards.cards_count, no COUNT query
board.cards.count            # always SELECT COUNT(*)

Card.where(board_id: board.id, done: true).delete_all   # counter now stale
Board.reset_counters(board.id, :cards)                  # recount with SQL

go deeper

for a junior

Recall where each option is declared, which column counter_cache maintains on the parent, and that touch updates updated_at.

for a middle

Explain which operations move the counter, why size and count differ, and how touch is deferred and chained without running validations.

for a senior

Plan for drift and contention: bulk writes bypass both options, reset_counters repairs them, and a hot parent row can become a lock hotspot.

for a principal

Decide whether denormalised counts and touch chains are worth their write amplification, or whether periodic recounts or another store serve the read path better.

## Two ways a child keeps its parent current A kanban board shows "42 cards" on every board tile, and caches its own rendering keyed on `updated_at`. Two `belongs_to` options on `Card` serve those needs: ```ruby class Card < ApplicationRecord belongs_to :board, counter_cache: true, touch: true end ``` - `counter_cache: true` keeps a **count** column on the parent current. - `touch: true` keeps the parent's **timestamp** current. Both are declared on the child's `belongs_to`, and both are implemented as callbacks on the child. ## counter_cache in detail The column lives on the **parent** and is named after the child's table: `boards.cards_count`. Rails does not add it; a migration adds it, usually as `integer, default: 0, null: false`. Then: 1. Creating a card increments it, with an atomic SQL update of the form `SET cards_count = COALESCE(cards_count, 0) + 1`, so concurrent inserts do not lose counts. 2. Destroying a card decrements it. 3. Moving a card to another board (changing `board_id` and saving) decrements the old board and increments the new one. 4. Reading `board.cards.size`, `empty?` or `any?` uses the column instead of a `COUNT(*)` query. `board.cards.count` still runs `COUNT(*)` every time, and `board.cards.length` loads every card. A custom column name goes in the option: `counter_cache: :open_cards_count`. The API docs also suggest `attr_readonly :cards_count` on `Board`, so ordinary attribute writes in application code cannot overwrite it. ## What bypasses the counter The counter moves only through the callbacks above. Anything that skips Active Record callbacks leaves it stale: | Operation | Updates cards_count? | |---|---| | `card.save` (new), `board.cards.create` | yes | | `card.destroy`, `board.cards.destroy(card)` | yes | | `card.update(board: other_board)` | yes, both boards | | `card.delete` | no | | `Card.where(board_id: 1).delete_all` | no | | `card.update_column(:board_id, 2)` | no | | `Card.insert_all(rows)` | no | | raw SQL | no | Repair a drifted value with `Board.reset_counters(board.id, :cards)`, which recounts with SQL. For adding a counter to a large existing table, `counter_cache: { active: false }` keeps the column updated while reads still query the database, until you have backfilled it and switch to `true`. ## touch in detail `touch: true` sets the parent's `updated_at` to the current time whenever the child is created, updated or destroyed. `touch: :last_card_activity_at` sets that column as well as `updated_at`. Mechanics worth knowing: - Touching skips **validations** and runs only `after_touch`, `after_commit` and `after_rollback` callbacks on the parent; it is not a save. - When a card is updated, the touch from its `belongs_to` is **deferred** until just before the transaction commits, so ten card updates in one transaction produce one `UPDATE` of the board. - It **chains**: if `Board` itself `belongs_to :workspace, touch: true`, touching the board touches the workspace. - `has_one` accepts `touch:` too; `has_many` does not. - `ActiveRecord::Base.no_touching { ... }` suppresses touches for bulk work. Its usual purpose is cache invalidation: a fragment keyed on the board changes when any card changes. Building the cache keys is a caching topic. ## Reading the counter The counter is used only when the association is not already loaded. Once `board.cards` has been loaded, `size` simply counts the loaded array, so a stale column cannot mislead it. Before loading, `size`, `empty?` and `any?` trust the column, which is the point: a board index page can show "42 cards" for fifty boards without fifty `COUNT(*)` queries. The `has_many` side normally needs no option at all; its `counter_cache:` option exists only to name a custom column when Rails cannot infer it from the `belongs_to`. ## The two together With both options, creating or destroying a card adjusts `cards_count` and touches `updated_at` in the same `UPDATE` statement. A card edit that does not move it to another board only touches. ## Costs - **Hot rows.** Every card write updates the same board row. On a very busy board that row becomes a lock hotspot; consider updating counts asynchronously or periodically. - **Drift.** Bulk operations bypass both options; anything that bypasses callbacks must also reset counters. - **Write amplification.** A touch chain three levels deep turns one card edit into several updates.

  • How do you add a counter cache to a boards table that already has millions of cards?
    Add the column without the option, then declare `counter_cache: { active: false }` so new writes keep it updated while reads still query the database. Backfill in batches with `Board.reset_counters` or an SQL update, then switch to `counter_cache: true` so `size` and `any?` start trusting it.
  • Does touch: true on Card run Board's validations and save callbacks?
    No. A touch writes the timestamp directly, skipping validations and running only `after_touch`, `after_commit` and `after_rollback` on the board. From a `belongs_to` it is also deferred until just before commit, so many card writes in one transaction touch the board once.

A counter cache is a turnstile count at the door: accurate as long as everyone walks through it, wrong as soon as people climb in through a window such as delete_all or raw SQL.

  • counter_cache: true adds the cards_count column for you.
  • board.cards.count reads the counter cache column.
  • Card.where(...).delete_all keeps cards_count correct.
  • touch: true saves the parent and runs its validations.
  • counter_cache is declared on the parent's has_many.