---
title: When the N+1 fix becomes the problem
teaser: |-
  I fixed an ActionText N+1 by preloading rich text bodies. Then I deleted that preload, and the home page went from 10 seconds to 360 ms.
  Both changes were correct.
tags: rails,database,performance,development
author: Trésor Bireke
published_on: 2026-12-02
---

I fixed an ActionText N+1 by preloading rich text bodies. Later I deleted that preload, and the home page went from around 10 seconds to 360 ms.

Both changes were correct.

## The first fix: Preload everything

Our list pages show a card per article, with a short excerpt on each card. The card partial had one line for that:

```erb
<%= rich_text_preview(article.body, length: 120) %>
```

The helper renders the body with `to_s`, strips the HTML with Nokogiri, and truncates the text to 120 characters.

Without a preload, every card loads its rich text row in its own query. In a list view, that is an N+1. So I added a scope that preloads the full chain:

```ruby
scope :with_full_body, -> {
  includes(rich_text_body: { embeds_attachments: :blob })
}
```

Rails generates the same scope for you as `with_rich_text_body_and_embeds`.

The rich text rows now loaded in one query, and I moved on.

## What that one line really costs

The preload made one query efficient. It did nothing about the work itself.

That helper call still hides three costs, per card, per request:

1. **Load it.** The full rich text body and its attachment blobs come out of Postgres. Our production bodies average 275KB, and the largest is 7.1MB.
2. **Render it.** Calling `to_s` on an ActionText body goes through ActionView. It resolves every embedded attachment, builds variant URLs, and renders a partial per image.
3. **Parse it.** Nokogiri parses the rendered HTML, only to keep 120 characters of text.

The second cost has a catch. Rails finds each embedded attachment through its signed ID, one blob lookup at a time. The preloaded embeds are not used for rendering, which is a [known limitation](https://github.com/rails/rails/issues/37249). So part of my preload was loading rows that nothing read.

The home page has 49 cards. It loaded about 13MB of HTML from the database and took around 10 seconds to produce 49 short strings.

## The second fix: Stop doing the work at read time

An excerpt only changes when the body changes. So we can compute it once, on save, and store it.

Every model with a rich body got an `excerpt` column, filled by a `before_save` callback:

```ruby
module RichBody
  extend ActiveSupport::Concern

  BLOCK_TAGS = "p, div, br, li, h1, blockquote, pre"

  included do
    has_rich_text :body

    before_save :set_excerpt, if: -> {
      association(:rich_text_body).loaded? && rich_text_body&.changed?
    }
  end

  private

  def set_excerpt
    html = rich_text_body.body&.to_html.to_s
    fragment = Nokogiri::HTML5.fragment(html)

    # Keep words apart: "<h1>Title</h1><p>First</p>" => "Title First"
    fragment.css(BLOCK_TAGS).each do |node|
      node.add_next_sibling(Nokogiri::XML::Text.new(" ", fragment.document))
    end

    self.excerpt = fragment.text.squish.first(300)
  end
end
```

The generator reads `to_html`, not `to_s`. `to_html` returns the content as it is stored, with attachments still as bare `<action-text-attachment>` tags. `to_s` is the one that renders them. This means even the write path skips attachment rendering.

The migration that adds the column also backfills it from the stored HTML, so old rows are not blank.

The view becomes:

```erb
<%= truncate(article.excerpt, length: 120) %>
```

Then I deleted every `with_full_body` call on the list queries. List pages no longer load rich text at all.

The home page now responds in 360 ms.

## Two details worth copying

### Guard the callback with `loaded?`

Without the `loaded?` check, every save of an article lazy-loads its rich text just to ask if it changed. Toggling `published` would pull a multi-megabyte body out of the database for nothing.

If the association was never loaded, it can't have changed. Assigning `article.body` always loads it first, so the guard never misses a real edit.

### Store more than you display

The column holds 300 characters, and the card shows 120. The slack lets different views truncate to different lengths without touching the database again.

## Considerations

* The callback runs when you save the parent record. If you update the rich text record directly, the excerpt goes stale.
* If you change how the excerpt is built, you need to backfill again.
* Switching the helper to `to_plain_text` would not have saved us. It skips the ActionView render, but it still loads the body and resolves every attachment.
* For a `show` page, or for small bodies with no attachments, the preload is fine. This only pays off when a value is read far more often than it is written.

## Conclusion

Excerpts are read thousands of times per edit. Any computation with that read/write ratio belongs at write time.

The N+1 fix and the real fix are the same lesson at two altitudes. Preloading made one query efficient, but nobody asked whether the data should be fetched at all. The next time you fix a slow query, ask one more question: does this page need that data in the first place?
