Growing a Rails application without it turning into a mess

TL;DR

Difficulty: Advanced

A growing Rails application gets slow in two ways that need opposite cures: slow to change (fix it with boundaries) and slow to run (fix it with measurement). Never use one to fix the other.

  • Score proposed boundaries against your own change history: the share of changes that cross a boundary should be around 20% or less.
  • Namespaces that follow the business come first, packwerk checks them, engines and separate services only when a real difference in team, language or runtime demands it.
  • Untangle callback chains behind a characterisation test, and pass plain data, not records, across boundaries.
  • For speed: measure with the log, rack mini profiler and an APM, then fix in order. Queries, indexes, caching, replicas. In the example the day overview goes from 2.8 seconds to under half a second.

"The app has become slow" can mean two very different things, and they need opposite cures. Here is how to keep a Rails 7.1 application fast to change and fast to run as it grows, worked through on a chain of bicycle workshops two years after launch: boundaries scored against the change history, packwerk, untangled callbacks, and one slow page profiled from 2.8 seconds to under half a second.

Big is not the problem. Two different kinds of slow are.

"My Rails application is getting big" is usually said by someone who feels one of two pains. Changes take longer than they used to: a small feature touches 14 files, breaks something unrelated, and nobody wants to deploy on a Friday afternoon. Or pages take longer than they used to: the screen everyone opens at 8am now takes three seconds to appear.

From the outside the two look alike. Both are "the app has become slow". Inside, they have opposite cures. Slow to change is a design problem, and you fix it with boundaries. Slow to run is a measurement problem, and you fix it with a profiler. The most expensive mistakes I see in growing applications come from using one cure on the other disease: splitting the code into services to fix a slow page, or bolting caching onto a tangled codebase to make it feel faster.

So the rule for this whole chapter fits in one line. Boundaries for change, measurement for speed, and never one to fix the other.

This chapter takes both in turn, on the same example application the whole Rails series has built. It assumes you know how a Rails application is put together and the everyday habits from building Rails applications efficiently. Everything here is written for Rails 7.1 on Ruby 3.3, the current versions as I write.

Example: two complaints from the same founder

The example is invented. Freewheel Cycles, a chain of bicycle repair workshops in Limerick, replaced its spreadsheets with its own Rails application two years ago. Since then it has grown from six workshops to 14, from 38 mechanics to 95, and from about 1,150 to about 3,100 repair bookings a week. The application grew with it: bookings, repairs, parts, customers, invoicing, reporting, and a JSON API for the mechanics' mobile app.

Niamh, the founder, brings two complaints to the developers, Aisling and Cian, in the same week:

  1. "Every small change takes a week now, and last month the parts stock went wrong after a change to invoices."
  2. "The day overview takes forever. My workshop managers open it 20 times a day."

The day overview really is slow: it takes 2.8 seconds. Aisling's first instinct is to answer both complaints with one project, "let's break the app up". This chapter shows why complaint 1 is a boundaries job and complaint 2 is a profiler job, and how each is done.

Where Freewheel stands after two years

Before any advice, the facts on the table. Numbers in the first block are the example's fixed facts. The second block is my own derivation for the example, labelled so you can follow it.

FactValue
Workshops14
Mechanics95
Repair bookings a weekabout 3,100
Modules the business talks aboutbookings, repairs, parts, customers, invoicing, reporting, plus the JSON API
Slowest pagethe manager's day overview, 2.8 seconds
Test suite1,450 tests, 38 of them system tests, 19 minutes in continuous integration (CI)
Developers (my assumption)four: Aisling and Cian, plus two hires in the second year
Bookings on an average day (derived)3,100 ÷ 6 opening days, about 517
Rows in the bookings table (my estimate)a little over 200,000 after two years of growth

Hold on to those numbers. Every calculation below uses them.

The signs that a codebase is tangling

Size alone tells you nothing. A 200 model application with clean edges is easier to work in than a 40 model one where everything knows everything. What matters is whether a change stays local. These are the warning signs I look for, with a way to measure each one, because "it feels messy" is not something you can fix on a Monday morning.

SignHow to see itWhen I start to worry (my rule of thumb)
Fat models with many callbackscount the callback lines per model (command below)more than eight callbacks on one model
A God objectthe one model every other file mentionsone class referenced from more than half of app/
Slow test suitethe CI durationover 10 minutes, so people stop running it
Fear of deployingdeploys per week, and days with nonethe team avoids deploying on certain days
Changes spill across areasthe change radius (next section)more than a third of changes cross an area

Counting callbacks takes one line in the terminal:

# callback declarations per model file, most first
grep -cE "^\s*(before|after|around)_" app/models/*.rb | sort -t: -k2 -rn | head

The callback sign deserves a word. Active Record callbacks are methods that run automatically around saving, creating, updating or destroying a record1. They are a fine tool for keeping a record consistent with itself, normalising a phone number for example. They become a problem when they reach outside the record: a save on a job card that also deducts stock, drafts an invoice and sends a text message. Nobody reading job_card.update!(status: :ready) can see that three other areas just changed.

The God object is the class that has become the centre of the world. In a booking business it is almost always Booking. Every feature has a reason to add one more method to it, and two years later it is 1,400 lines long.

Example: Freewheel's health check

Cian runs the checks on a Tuesday afternoon. The numbers below are invented for the example:

  • JobCard has 23 callbacks. Eleven of them do something in another area: stock, invoices, notifications.
  • Booking is 1,400 lines and is referenced from 61% of the files in app/.
  • CI takes 19 minutes. Developers have started pushing several changes at once to avoid waiting, which makes each failure harder to trace.
  • The team has not deployed on a Saturday in a year, because Saturday morning is the booking peak and nobody trusts a deploy.

Four of the five signs are lit. That is a codebase that is still working but is getting harder to change every month. The fifth sign, the change radius, needs its own section, because it is the one that tells you where to cut.

Draw boundaries from your history, not from a whiteboard

The usual advice is to split the code "along business domains". It is correct and close to useless, because every whiteboard produces a plausible set of domains, and they are not all equally good. Domain driven design calls such an area a bounded context: a part of the system inside which a model and its words mean one thing2. The hard question is where exactly one context ends and the next begins.

My answer is to let the repository tell you. You already have the best evidence there is: every change the team made in the last few months, and which files moved together. A good boundary is one that most changes do not cross. So before you move a single file, you score a proposed set of boundaries against your own history.

I call this the change radius. For each merged change (a pull request, or a commit on the main branch), count how many of the proposed areas its files touch:

rˉ=1N∑i=1Nric=∣{ i:ri>1 }∣N\bar{r} = \frac{1}{N}\sum_{i=1}^{N} r_i \qquad\qquad c = \frac{\left|\{\, i : r_i > 1 \,\}\right|}{N}

where NN is the number of changes you look at, rir_i is the number of areas change ii touches, rˉ\bar{r} is the mean radius (1.0 means every change stays inside one area), and cc is the crossing share, the fraction of changes that touch more than one area. The mean is explained in Foundations: the mean, and a share like cc in Foundations: ratios and rates.

My rule of thumb: a crossing share under about 20% means the boundaries fit the way the business actually changes. Above a third, the boundary is in the wrong place, and enforcing it will make every third change harder instead of easier. This is my judgement from how teams work, not a published threshold.

The reason this works is old and well documented. Melvin Conway observed in 1968 that the structure of a system mirrors the communication structure of the organisation that builds it3. Your change history is that communication structure written down: which things Niamh asks for together, which things the mechanics complain about together.

Example: scoring two proposals with a short script

Cian writes a small script that maps file paths to proposed areas by the words in them. The areas are the four the business changes most: bookings, repairs, parts, invoicing. Reporting and the API are left out on purpose, because they read from everything by design (more on that in the boundaries table below).

# script/change_radius.rb
# Usage: ruby script/change_radius.rb 2023-12-18
# For every change on main since the date, count how many business areas
# its files touch. Areas are recognised by words in the file path.
AREAS = {
  "bookings"  => /\b(booking|customer|bike)/,
  "repairs"   => /\b(job_card|board|repair)/,
  "parts"     => /\b(parts?\b|part_usage|reorder|stock)/,
  "invoicing" => /\b(invoice|vat)/
}.freeze

since = ARGV.fetch(0)
shas = `git log main --first-parent --since=#{since} --format=%H`.split

radii = shas.map do |sha|
  files = `git diff --name-only #{sha}^1 #{sha}`.split("\n")
  AREAS.count { |_area, pattern| files.any? { |path| path.match?(pattern) } }
end

touched = radii.reject(&:zero?) # ignore changes outside these areas
crossing = touched.count { |r| r > 1 }

puts "changes:     #{touched.size}"
puts "mean radius: #{(touched.sum.to_f / touched.size).round(2)}"
puts "crossing:    #{(100.0 * crossing / touched.size).round}%"

--first-parent walks only the main line, so each merged pull request counts once whether the team merges or squashes. #{sha}^1 is the commit before it, so the diff is exactly what that change brought in.

The first proposal treats customers as an area of its own, as the founder's list does. Cian adds "customers" => /\bcustomer/ and removes customer from bookings. Over the last 120 changes the script reports (invented numbers): 71 changes touch one area, 33 touch two, 16 touch three.

rˉ=71×1+33×2+16×3120=185120≈1.54c=33+16120≈41%\bar{r} = \frac{71 \times 1 + 33 \times 2 + 16 \times 3}{120} = \frac{185}{120} \approx 1.54 \qquad c = \frac{33 + 16}{120} \approx 41\%

Here N=120N = 120 changes, the mean radius is rˉ≈1.54\bar{r} \approx 1.54 and the crossing share is c≈41%c \approx 41\% (the same formulas as above, from Foundations: the mean). Four in ten changes cross a boundary. Looking at them, the reason is plain: almost every change to customers is a change to how customers book. "Add a second phone number", "let customers save two bikes", "remember the preferred workshop". In this business a customer is part of the booking story.

The second proposal folds customers and bikes into bookings, which is the mapping in the script above. Same 120 changes: 96 touch one area, 19 touch two, five touch three.

rˉ=96+38+15120=149120≈1.24c=19+5120=20%\bar{r} = \frac{96 + 38 + 15}{120} = \frac{149}{120} \approx 1.24 \qquad c = \frac{19 + 5}{120} = 20\%

Again N=120N = 120, but now rˉ≈1.24\bar{r} \approx 1.24 and c=20%c = 20\%, worked as in Foundations: ratios and rates. The crossing share halves. Proposal two is the one to build. Nobody had to argue about it in a meeting.

Bar chart for the invented Freewheel example over 120 changes. Proposal A with customers as its own area: 41% of changes cross a boundary. Proposal B with customers inside bookings: 20%. Tap or click to enlarge

Majestic monolith, microservices, and the ground in between

Once you know where the boundaries are, the next question is how hard to make them. There are three broad answers, and the debate around them is loud, so it helps to separate what each side actually said.

The majestic monolith. In February 2016 David Heinemeier Hansson, who created Rails, argued that microservices suit very large organisations, and that small teams who copy them take on the costs of a distributed system for little gain. His alternative is one well designed, integrated application, "Embrace the monolith and make it majestic."4 The Rails Doctrine makes the same case under the heading "value integrated systems"5. That is an opinion from the framework's author, and he says so.

Microservices. James Lewis and Martin Fowler described the style in 2014: an application built as a suite of small services, each running in its own process, deployed independently, owning its own data, talking over the network6. They were explicit that this buys independent deployment and scaling at the price of distributed complexity.

Monolith first. A year later Fowler wrote that almost every successful microservice system he knew of started as a monolith that was split later, and that systems built as services from day one usually ran into serious trouble7. The reason he gives is the one this chapter is built on: you cannot draw stable service boundaries until you understand the system.

The middle ground is what people now call a modular monolith: one application, one deploy, one database, but with internal boundaries that are named, owned and checked by a tool. Shopify, which runs a very large Rails monolith, described exactly this path in 2020: it grouped its code into components by business area, and then built a tool to enforce the boundaries between them8.

My view: for a team under about 20 developers, a separate service is worth it only when something genuinely needs a different team, a different language or runtime, or a different scaling and failure profile. "The code is messy" is never on that list. A network call does not tidy up a model, it just makes the mess slower and harder to debug.

Tap or click to enlarge

Example: the one service Freewheel does split out

When Freewheel chose Rails, the plan already included one exception: a small Python service for the parts demand forecast, because forecasting is data science work and that ecosystem lives in Python (the decision chapter tells that story). That service passes every test in the flow: different language, different runtime, a nightly batch with its own failure profile. It reads a nightly export and writes back one table of suggested reorder quantities.

Everything else stays in the monolith. Complaint 1 does not come from a missing network boundary. It comes from missing boundaries inside the code.

Step one: namespaces that follow the business, not the layers

A new Rails application is organised by technical layer: app/models, app/controllers, app/views, app/jobs. That is the right default when the application is small, and how a Rails application is structured explains why. It stops helping once there are 300 files in app/models, because the folders tell you what kind of thing a file is, never which part of the business it belongs to.

The least expensive boundary Rails offers is a namespace, a Ruby module that groups classes under one name. The Rails autoloader, Zeitwerk, maps folders to namespaces: the guide's own example is that app/controllers/admin/payments_controller.rb must define Admin::PaymentsController9. So moving a file into app/models/repairs/ and wrapping it in module Repairs is all it takes to create Repairs::JobCard. No configuration, no gem.

Three details make the difference between a namespace that helps and one that hurts.

Table names stay the same. For a model inside a plain module, Active Record still derives the table name from the class name alone, so Repairs::JobCard keeps reading the job_cards table. No data migration. (A module that defines table_name_prefix would change that, so don't add one.)

Stored class names must move with the class. Anything that writes a class name into the database breaks silently: polymorphic associations, single table inheritance and Active Storage attachments all store a type column. Freewheel's before and after photos are Active Storage attachments on job cards, stored with record_type = 'JobCard'. After the move that has to say Repairs::JobCard, or every photo disappears from the board.

Each namespace gets a small public front door. Other areas call a handful of methods on the module, never reach into its models. That is what makes the boundary real.

Example: the boundaries table

After the change radius exercise, Freewheel settles on four business namespaces, plus two that are not business areas at all. Shared master data (workshops, mechanics, users) stays in the root of app/.

NamespaceOwns these tablesFront door for othersMay depend on
Bookingsbookings, customers, bikesBookings.book, Bookings.for_dayroot
Repairsjob_cards, photo attachmentsRepairs.open_for(booking), Repairs::MarkReadyroot, Bookings, Parts, Invoicing
Partsparts, part_usagesParts.consume_for, Parts.used_lines, Parts.reorder_reportroot
Invoicinginvoices, invoice_linesInvoicing.draft_forroot, Bookings
Reporting (read side)none, reads from allreport objectseverything above
Api (delivery)none/api/v1 JSON endpointsthe front doors above

Two choices in that table carry the design. Dependencies only point one way, so there is no cycle: Repairs may call Parts and Invoicing, but Parts and Invoicing never call Repairs. And Reporting and the API are allowed to depend on everything, because nothing depends on them. A read side is a leaf, so it cannot tangle anything.

Example: moving the job card

The move itself, with the parts that are easy to forget:

# app/models/repairs/job_card.rb  (was app/models/job_card.rb)
module Repairs
  class JobCard < ApplicationRecord # still the job_cards table
    belongs_to :booking, class_name: "Bookings::Booking", touch: true
    belongs_to :mechanic                       # root model, no class_name needed
    has_many_attached :photos                  # before and after photos

    enum :status, { waiting: 0, in_repair: 1, ready: 2, collected: 3 }
  end
end
# db/migrate/20240318090000_rename_job_card_attachment_type.rb
class RenameJobCardAttachmentType < ActiveRecord::Migration[7.1]
  def up
    # Active Storage stores the class name; keep the photos attached.
    execute <<~SQL
      UPDATE active_storage_attachments
      SET record_type = 'Repairs::JobCard'
      WHERE record_type = 'JobCard'
    SQL
  end

  def down
    execute <<~SQL
      UPDATE active_storage_attachments
      SET record_type = 'JobCard'
      WHERE record_type = 'Repairs::JobCard'
    SQL
  end
end

The routes can keep the old web addresses while the controllers move. scope module: changes where Rails looks for the controller without changing the path, so no bookmark on a workshop tablet breaks:

# config/routes.rb
Rails.application.routes.draw do
  scope module: :repairs do
    resources :job_cards, only: %i[index show update] # Repairs::JobCardsController, still /job_cards
  end
end

And the test fixtures need to know the new class, because the fixture file is still named after the table:

# test/fixtures/job_cards.yml
_fixture:
  model_class: Repairs::JobCard

in_repair_with_chain:
  booking: saturday_service
  mechanic: lead_mechanic
  status: in_repair

Aisling moves one namespace per week, smallest first (Invoicing, then Parts), each in its own pull request with the full suite green. Repairs goes last because it has the most callbacks to untangle, which is the next section but one.

Step two: make the boundary checked, with packwerk

A namespace is a convention. Nothing stops a developer in a hurry from writing Repairs::JobCard.where(...) inside the Parts code, and after a few months of that the boundary is decoration. Ruby itself has no way to forbid it.

Packwerk is Shopify's open source answer, released in September 20208. It reads your code without running it, finds every reference to a constant, works out which package defines that constant, and reports a violation when a package uses one it has not declared as a dependency. A package is simply a folder with a package.yml file in it10.

Two facts about the current version matter. Since packwerk 3.0 (March 2023) it checks dependencies only, and the older privacy checks live in a separate extension gem11. And in January 2024 two Shopify engineers published an honest retrospective: packwerk helped them see and cut dependencies, but a package with zero violations still needed months of work before it could actually run on its own, because packwerk cannot see everything (routes, initialisers, code loaded through require)12. Their conclusion, that running code is a better measure of progress than any single tool, is the right way to hold it. Packwerk is a smoke alarm, not a firewall.

Because a package must be one folder, packwerk works best with each namespace in its own folder tree rather than spread across app/models, app/controllers and app/views. The packs-rails gem from the Ruby at Scale community sets that up: put code in packs/repairs/app/models/repairs/job_card.rb and it adds the right autoload paths, so the class is still Repairs::JobCard13. That is why I do the namespacing first. When the class names are already right, moving folders into packs is mechanical.

Example: Freewheel turns on the checks

# Gemfile
gem "packs-rails"                  # needed in every environment

group :development, :test do
  gem "packwerk", require: false
end
bundle install
bundle binstub packwerk
bin/packwerk init                  # writes packwerk.yml and the root package.yml

Then one package.yml per pack, listing what it is allowed to use. The root package is called .:

# packs/repairs/package.yml
enforce_dependencies: true
dependencies:
  - .
  - packs/bookings
  - packs/parts
  - packs/invoicing
metadata:
  owner: Aisling
# packs/parts/package.yml
enforce_dependencies: true
dependencies:
  - .
metadata:
  owner: Cian

The first bin/packwerk check finds the dependencies nobody intended. Parts turns out to reference Repairs::JobCard in three places, because PartUsage had a belongs_to :job_card and the nightly reorder report joined through it. The fix keeps the database honest and the Ruby dependency one way: part_usages.job_card_id keeps its foreign key constraint in PostgreSQL, but Parts only ever handles the id, never the Repairs class.

Existing violations that cannot be fixed this week are recorded with bin/packwerk update-todo, which writes them to a package_todo.yml in the pack. From then on bin/packwerk check runs in CI and fails on anything new. The todo file is a debt list with a visible size, and it should only ever shrink.

Step three: an engine, when a boundary needs walls

The strongest boundary Rails has without leaving the process is an engine. The Rails Guides describe engines as miniature applications that add functionality to a host application, and note that a Rails application is itself a "supercharged" engine14. A mountable engine generated with rails plugin new name --mountable gets its own routes, controllers, models, migrations, assets and tests, and isolate_namespace keeps all of it in its own namespace.

That isolation has a price that surprises people: isolate_namespace gives the engine's tables a prefix, so a model Invoice inside an Invoicing engine reads invoicing_invoices. Turning an existing namespace into an engine therefore means renaming tables, copying migrations into the engine and mounting its routes. For a fresh, separable feature that cost is low. For a two year old core area it is a project.

My view: engines are excellent for things that are genuinely separable or reusable, such as an admin area you want to share between two applications, or a feature you may hand to another team as a gem. They are a poor first step for untangling a codebase, because they add the cost of a hard wall before you know the wall is in the right place.

Example: what each option would cost Freewheel

OptionWhat changesDeploysCost for Freewheel's Repairs area (my estimate)
Namespacefolders and class namesonetwo to three days, mostly callbacks and fixtures
Pack with packwerkfolder layout plus a CI checkoneone day on top of the namespace
Enginetables renamed, routes mounted, own migrationsonetwo to three weeks, plus risk on live data
Separate serviceits own database, an API between, two deploystwomonths, plus a permanent operations cost

Freewheel does the first two for all four areas and stops there. Nothing in the business asks for an engine yet.

Untangle the callbacks behind a characterisation test

Complaint 1 named a specific bug: a change to invoices broke parts stock. That is the signature of a callback chain. When saving a job card quietly drafts an invoice and deducts stock, a change to the invoice code can change the order or the outcome of the stock code, and nothing in either file says they are connected.

The safe way to change code you do not fully trust is the one Michael Feathers described in "Working Effectively with Legacy Code" (2004): first write a characterisation test, a test that pins down what the code does today, right or wrong, then change the structure while that test stays green15. You do not argue about what the behaviour should be until the structure is fixed.

Then replace the hidden chain with one explicit operation. In building Rails applications efficiently I gave my view on where such objects live: a plain Ruby class in app/models, named after the business event, not a generic "service". The operation reads like the sentence a mechanic would say: mark this card ready.

Example: from three callbacks to one operation

Before. Three of the 23 callbacks on the job card, all firing on the same status change:

# app/models/job_card.rb  (before)
class JobCard < ApplicationRecord
  belongs_to :booking
  has_many :part_usages
  enum :status, { waiting: 0, in_repair: 1, ready: 2, collected: 3 }

  after_update :use_parts,       if: -> { saved_change_to_status? && ready? }
  after_update :draft_invoice,   if: -> { saved_change_to_status? && ready? }
  after_commit :notify_customer, on: :update, if: -> { saved_change_to_status? && ready? }
  # ... and 20 more
end

Step 1, the characterisation test, written against the code as it is. It pins the three effects of "ready": one invoice, one chain out of stock, one message queued.

# test/models/job_card_ready_test.rb
require "test_helper"

class JobCardReadyTest < ActiveSupport::TestCase
  test "a card marked ready uses its parts, drafts an invoice and queues the message" do
    card = job_cards(:in_repair_with_chain)

    assert_difference "Invoice.count" => 1, "parts(:chain_11_speed).reload.stock" => -1 do
      assert_enqueued_with(job: ReadyNotificationJob) do
        card.update!(status: :ready) # the act line: the only line that will change
      end
    end
  end
end

It passes against the old code. Now the behaviour is pinned.

Step 2, the explicit operation. One transaction for the database work, and the message queued only after the transaction has committed, so a rollback can never send a customer a "your bike is ready" text for a bike that is not (background jobs, email and files in Rails explains why that order matters):

# packs/repairs/app/models/repairs/mark_ready.rb
module Repairs
  class MarkReady
    LABOUR_RATE_CENTS_PER_HOUR = 5_200 # €52 an hour

    def initialize(job_card)
      @job_card = job_card
    end

    def call
      JobCard.transaction do
        @job_card.ready!
        Parts.consume_for(job_card_id: @job_card.id)
        Invoicing.draft_for(customer_id: @job_card.booking.customer_id, lines: invoice_lines)
      end
      ReadyNotificationJob.perform_later(@job_card) # runs only after the commit
    end

    private

    # Plain data crosses the boundary, never a Repairs record.
    def invoice_lines
      labour = {
        description: "Labour",
        amount_cents: @job_card.labour_minutes * LABOUR_RATE_CENTS_PER_HOUR / 60
      }
      [labour] + Parts.used_lines(job_card_id: @job_card.id)
    end
  end
end

Step 3, remove the three callbacks and change only the act line of the test:

Repairs::MarkReady.new(card).call # replaces card.update!(status: :ready)

The assertions do not change. If the test is green, the behaviour is the same and the structure is new. Notice that Invoicing.draft_for receives a customer id and plain hashes, never a job card. That is what keeps Invoicing free of any dependency on Repairs, and it is the reason the parts bug cannot happen again: invoices no longer run inside a job card's save.

One thing worth saying to the person paying for this: none of those steps adds a feature, and all of them cost little compared with the bug they prevent. That is what refactoring behind tests buys.

Performance: measure before you touch anything

Now complaint 2, which is a different job entirely. The first rule of performance work is that the slow part is almost never where you guess it is. So before changing a line, find out where the 2.8 seconds go. Rails gives you more than most people use.

The log. Every request in the development and production log ends with a line like Completed 200 OK in 2800ms (Views: 1300.0ms | ActiveRecord: 1250.0ms | Allocations: ...). That already splits the time into database, view rendering and the rest.

Server Timing. New Rails 7.1 applications set config.server_timing = true in development, which sends the same breakdown to the browser's developer tools16.

rack mini profiler. The rack-mini-profiler gem puts a small badge on every page with the time and every SQL query, and with the stackprof gem it draws a flame graph when you add ?pp=flamegraph to the address. It is designed to be safe in production as long as you authorise only staff to see it17.

Query log tags. Setting config.active_record.query_log_tags_enabled = true writes the controller and action into a comment on every SQL statement, so a slow query in the database's own log tells you which page sent it16.

N+1 detection. An N+1 is one query for a list plus one more query for each item in it. The Bullet gem detects them and can fail the test suite when a new one appears18. Rails' own strict_loading makes a relation raise an error the moment something on it is lazily loaded19. Active Record done well explains the N+1 from first principles.

An application performance monitoring (APM) service in production, because development data never looks like Saturday morning. AppSignal, New Relic, Scout APM, Skylight and Datadog all instrument Rails and show the slowest pages, the slowest queries and their trend over time. They differ in pricing, where they host your data and how deep they go, so compare them against your own needs and your data protection duties. Any of them does the measuring job.

A simple model of a page's time keeps the investigation honest:

T=nq⋅tˉq+Tview+TotherT = n_q \cdot \bar{t}_q + T_{\text{view}} + T_{\text{other}}

where TT is the total server time for the page, nqn_q is the number of SQL queries, tˉq\bar{t}_q is the average time per query, TviewT_{\text{view}} is the time spent rendering templates and partials, and TotherT_{\text{other}} is everything else (controller code, object allocation, garbage collection). See Foundations: ratios and rates for working with averages like tˉq\bar{t}_q. The model shows the two classic levers at once: cut nqn_q, or cut tˉq\bar{t}_q.

Example: profiling the day overview

Aisling opens the day overview locally with a copy of production data (personal details masked) and rack mini profiler on. The numbers are invented for the example but consistent with the facts above.

The log line says 2,800ms: views 1,300ms, Active Record 1,250ms. The profiler counts the queries: 2,083 for one page. The code explains why:

# app/controllers/manager/day_overviews_controller.rb  (before)
class Manager::DayOverviewsController < ApplicationController
  def show
    @date = params[:date] ? Date.iso8601(params[:date]) : Date.current
    @workshops = Workshop.order(:name)
  end
end
<%# app/views/manager/day_overviews/show.html.erb  (before) %>
<% @workshops.each do |workshop| %>
  <h2><%= workshop.name %></h2>
  <% workshop.bookings.where(starts_at: @date.all_day).order(:starts_at).each do |booking| %>
    <%= render "booking_row", booking: booking %> <%# reads customer, bike, mechanic, job card %>
  <% end %>
<% end %>

One query for the workshops, one per workshop for its bookings (14), and four per booking for the customer, bike, mechanic and job card. On an average day of about 517 bookings:

nq=1+14+4×517=2,083n_q = 1 + 14 + 4 \times 517 = 2{,}083

Here nqn_q is the query count from the model above: 11 for the workshops, 1414 for the bookings per workshop, and 44 for each of the 517517 bookings. At an average of 0.6ms per query, the database part is:

nq⋅tˉq=2,083×0.6 ms≈1,250 msn_q \cdot \bar{t}_q = 2{,}083 \times 0.6\,\text{ms} \approx 1{,}250\,\text{ms}

with tˉq=0.6 ms\bar{t}_q = 0.6\,\text{ms}, the average from Foundations: ratios and rates. Add 1,300ms of view rendering and 250ms of everything else, and the model gives exactly the 2.8 seconds Niamh complained about. Each query is fast. There are just two thousand of them.

Fix the queries: eager loading that respects the boundaries

The fix for an N+1 is eager loading: load each kind of record once, for the whole list, and stitch them together in memory. includes does this for associations19.

There is a twist here that a modular codebase adds. In the boundaries table, Bookings must not depend on Repairs, so Bookings::Booking has no has_one :job_card. The day overview lives in the manager's read side, which may depend on everything, so it loads the job cards itself, in one query, and indexes them by booking. The boundary costs one line, not one query.

Example: from 2,083 queries to six

# app/controllers/manager/day_overviews_controller.rb  (after)
class Manager::DayOverviewsController < ApplicationController
  def show
    @date = params[:date] ? Date.iso8601(params[:date]) : Date.current
    @workshops = Workshop.order(:name).to_a

    bookings = Bookings::Booking
      .where(starts_at: @date.all_day)
      .includes(:customer, :bike, :mechanic) # three queries, whatever the count
      .order(:starts_at)
      .strict_loading                        # any lazy load now raises at once
      .to_a

    @bookings_by_workshop = bookings.group_by(&:workshop_id)
    @job_cards_by_booking = Repairs::JobCard
      .where(booking_id: bookings.map(&:id))
      .index_by(&:booking_id)               # one query, read side may use Repairs
  end
end

The view loops over @bookings_by_workshop.fetch(workshop.id, []) instead of querying, and reads the job card from @job_cards_by_booking[booking.id]. The query count is now fixed at six: workshops, bookings, customers, bikes, mechanics, job cards. It no longer grows with the number of bookings, which is the property that matters when Freewheel opens its 20th workshop.

strict_loading is the guard rail. If a developer later adds booking.customer.preferred_workshop.name to the row partial, the page raises an error in development and in the tests instead of quietly adding 517 queries.

The log now reads about 1,690ms: views still 1,300ms, Active Record 140ms. And 110ms of those 140 are one query, the bookings for the day. That is the next lever.

Fix the slow query: an index, added without locking the table

With six queries left, one is slow because the database reads the whole bookings table to find one day. EXPLAIN shows it. In the Rails console:

Bookings::Booking.where(starts_at: Date.current.all_day).explain
# => Seq Scan on bookings ... Filter: starts_at >= ... AND starts_at <= ...

"Seq Scan" means a sequential scan, every row read. On a little over 200,000 rows that is the 110ms. An index on starts_at lets PostgreSQL jump straight to the day.

On a live table, how you add the index matters. A normal CREATE INDEX blocks writes to the table while it builds. PostgreSQL's CONCURRENTLY option builds it without blocking, but it cannot run inside a transaction, and Rails wraps each migration in one by default20. So:

Example: the index migration

# db/migrate/20240318100000_add_starts_at_index_to_bookings.rb
class AddStartsAtIndexToBookings < ActiveRecord::Migration[7.1]
  disable_ddl_transaction! # CONCURRENTLY cannot run inside a transaction

  def change
    add_index :bookings, :starts_at, algorithm: :concurrently
  end
end

After the deploy, EXPLAIN shows an index scan, the bookings query drops to about 4ms, and the database part of the page is about 30ms in total. The page is at about 1,580ms. Database time is now a rounding error. What is left is rendering.

Fix the rendering: Russian doll caching, and what it cannot do

Rendering 517 rows of HTML takes time even when the data is already in memory. Rails' answer is fragment caching: wrap part of a template in cache, and Rails stores the rendered HTML under a key built from the record and a digest of the template. When the record changes, its updated_at changes, the key changes, and the fragment is rendered fresh. When the template changes, the digest changes too21.

Russian doll caching nests fragments: an outer fragment per workshop, inner fragments per booking. When one booking changes, the outer fragment renders again but reuses every unchanged inner one. For a child record to expire its parent, the child's belongs_to gets touch: true, which is why the job card above has belongs_to :booking, touch: true: a job card moving to "ready" updates the booking's updated_at, which expires that row.

For the production cache store, Rails 7.1 ships Memcached and Redis stores, plus memory and file stores for development and small setups21. Freewheel already runs Redis for its background jobs, so it adds a separate Redis database for the cache.

There is one honest limit, and it is worth knowing before you start. Caching saves rendering, not queries. To know whether a fragment is still fresh, Rails needs the key, and the key needs the records. That is why the eager loading came first. A cache on top of 2,083 queries would still run 2,083 queries.

Example: caching the day overview

<%# app/views/manager/day_overviews/show.html.erb  (after) %>
<% @workshops.each do |workshop| %>
  <% bookings = @bookings_by_workshop.fetch(workshop.id, []) %>
  <%# key: workshop, day, newest change, and the count (so a deletion also expires it) %>
  <% cache [workshop, @date, bookings.map(&:updated_at).max, bookings.size] do %>
    <h2><%= workshop.name %></h2>
    <%= render partial: "booking_row", collection: bookings, as: :booking, cached: true %>
  <% end %>
<% end %>

cached: true on the collection fetches all the inner fragments in one read from the cache store, and renders only the missing ones21.

Cian also notices a business decision hidden in the key. A customer who changes their name will see the old name on today's board until their booking changes, because the customer is not part of the key. He asks Niamh, who says that is grand for an internal screen. That is the right way round: the developer finds the trade off, the business decides it.

How fast is it now? It depends on how many workshop fragments changed since the last view. A fragment that is still fresh costs about 2ms to fetch, a stale one about 93ms to render (1,300ms spread over 14 workshops). Between two views a few minutes apart, typically one or two workshops have a change, so say 1.5 of the 14 fragments are stale on average:

Tview=12.5×2 ms+1.5×93 ms≈165 msT_{\text{view}} = 12.5 \times 2\,\text{ms} + 1.5 \times 93\,\text{ms} \approx 165\,\text{ms}

Here 12.512.5 fresh fragments cost 2 ms2\,\text{ms} each and 1.51.5 stale ones cost 93 ms93\,\text{ms} each. This is an expected value, an average over many page views, explained in Foundations: expected value. The page total is now about 30 + 165 + 250 = 445ms, down from 2,800. The remaining 250ms of "other" is the next thing to look at, with a flame graph, if it ever matters. For now it does not: Niamh's complaint is closed.

Stacked bars of server time in milliseconds for the invented Freewheel day overview. Before: database 1,250, views 1,300, other 250, total 2,800. After eager loading: 140, 1,300, 250, total 1,690. After the index: 30, 1,300, 250, total 1,580. After fragment caching: 30, 165, 250, total 445. Tap or click to enlarge

Low level caching for numbers that are expensive to compute

Not everything worth caching is HTML. Rails.cache.fetch takes a key and a block: on a hit it returns the stored value, on a miss it runs the block and stores the result21. The guide's advice is to cache plain values, numbers and ids, rather than Active Record objects.

Example: the totals at the top of the day overview

The day overview shows each workshop's booked hours and expected takings at the top. They are aggregate queries over bookings and quotes, and a manager does not need them to the second.

# app/models/reporting/day_totals.rb
module Reporting
  class DayTotals
    def self.for(workshop, date)
      Rails.cache.fetch(["day_totals", workshop.id, date], expires_in: 10.minutes) do
        bookings = Bookings::Booking.where(workshop: workshop, starts_at: date.all_day)
        {
          booked_minutes: bookings.sum(:planned_minutes),
          expected_cents: bookings.sum(:quoted_price_cents)
        }
      end
    end
  end
end

Ten minutes of staleness is a business choice, not a technical one. If Niamh wanted the totals live, the right tool would be a key that changes with the data, like the fragments above, not a shorter expiry.

Move heavy reads to a replica, and heavy work out of the request

Two more levers become useful as the database gets busier. Neither is needed for the day overview, and both are worth knowing before the day you need them.

Read replicas. A replica is a copy of the database that follows the primary and accepts only reads. Rails has supported several databases natively since 6.0, and the 7.1 guide shows the setup: a second entry in config/database.yml marked replica: true, and connects_to in ApplicationRecord22. Rails can switch to the replica automatically for GET requests, with a short delay after a user's own write so they always see what they just saved. The guide is clear about the limits: Rails does not balance load across several replicas, and another user may briefly read data slightly behind the primary.

Background work and pagination. Anything slow that the user does not need to wait for belongs in a job: invoice PDFs, the nightly reorder report, exports. Any list that grows with the business needs pagination, because a page that renders "all invoices" is fast in the first month and unusable in the third year. Gems such as Pagy and Kaminari both do this well.

Example: the monthly report on the replica

Freewheel's monthly revenue report scans two years of invoices. It runs on the replica, so it cannot slow a Saturday morning booking:

# config/database.yml (production, shortened)
production:
  primary:
    <<: *default
    url: <%= ENV["DATABASE_URL"] %>
  primary_replica:
    <<: *default
    url: <%= ENV["DATABASE_REPLICA_URL"] %>
    replica: true
# app/models/application_record.rb
class ApplicationRecord < ActiveRecord::Base
  primary_abstract_class
  connects_to database: { writing: :primary, reading: :primary_replica }
end
# app/models/reporting/monthly_revenue.rb
module Reporting
  class MonthlyRevenue
    def self.for(month)
      ActiveRecord::Base.connected_to(role: :reading) do # every query in here hits the replica
        Invoicing::Invoice
          .where(issued_on: month.all_month)
          .group(:workshop_id)
          .sum(:total_cents)
      end
    end
  end
end

And the invoice list in the back office, which had quietly grown to 140,000 rows, is paginated with Pagy:

# app/controllers/invoicing/invoices_controller.rb
module Invoicing
  class InvoicesController < ApplicationController
    include Pagy::Backend

    def index
      @pagy, @invoices = pagy(Invoice.order(issued_on: :desc), items: 50)
    end
  end
end

Multi tenancy, in outline

One growth question deserves a mention even though Freewheel does not face it yet: what if Niamh decides to sell the software to other bicycle chains? Then the application must keep each chain's data apart. This is multi tenancy, and there are three broad ways to do it in Rails.

ApproachHow it worksStrengthsCosts
Row basedan account_id column on every table, every query scopedone schema, simple migrations, easy reporting across tenantsone forgotten scope leaks data, so it needs a guard such as the acts_as_tenant gem23
Schema per tenantone PostgreSQL schema per tenant, switched per request, for example with the Apartment gem (maintained as ros-apartment)24strong separation inside one databaseevery migration runs once per tenant, which gets slow with many tenants
Database per tenanta separate database per tenant, using Rails' horizontal sharding22the strongest separation, per tenant backupsthe most operations work and the highest running cost

My view: row based is the right default for almost every SaaS product, and the decision is much less expensive to take early than late. Adding an account_id to nine tables in the first month is an afternoon. Adding it in year three, with every query and every cache key to check, is a project. Scoping every query to the current account is also a security matter, covered in authentication, authorisation and security in Rails.

Example: what selling the software would mean for Freewheel

If Niamh sold the software, Freewheel would add an accounts table, an account_id to the nine core tables (workshops, mechanics, customers, bikes, bookings, job cards, parts, part usages, invoices), and every cache key above would gain the account. The boundaries would not change at all, which is a good sign that they follow the business: another chain repairs bikes the same way.

For the person paying for this

If you commission or own a Rails application that is two or more years old, you do not need to read the code to know whether it is growing well. Ask for five numbers, every quarter:

QuestionA healthy answer
How long does CI take?under 10 minutes, and trending down
How often do you deploy?several times a week, on any working day
What share of changes cross an area boundary?around 20% or less
What are the five slowest pages, and how slow?named, measured, each with a plan
How big is the boundary todo list?shrinking every quarter

A team that can answer all five without a week of preparation is in control of the codebase. A proposal to "rewrite it as microservices" that cannot point to a measured problem in one of these numbers is a proposal to spend money on a feeling.

If you want a second pair of eyes on an application that is starting to feel heavy, that is the kind of web application development work I do: I build and look after Rails applications, I write the tests first, and the code, the accounts and the data stay yours. The easiest start is the free workshop, where we look at your change history and your slowest page together.

Conclusion

A Rails application that gets big gets slow in two ways, and they need two different tools. Slow to change is fixed with boundaries: score them against your own change history, make them namespaces that follow the business, check them with packwerk, and only reach for an engine or a separate service when a real difference in team, language or runtime demands it. Untangle callback chains behind a characterisation test, and let plain data, not records, cross the boundaries.

Slow to run is fixed with measurement: the log line, rack mini profiler and an APM tell you where the time goes, and the fixes follow in order. Queries first, then indexes, then caching, then replicas and background work. In the example, that order took the day overview from 2.8 seconds to under half a second without a single new server.

Freewheel's two complaints were closed by two different projects, neither of which was "break the app up". The Django series takes the same application through the same growth in its own chapter later in the programme, with apps instead of namespaces and its own profiling tools, so you can compare the two like for like. And the suite that took 19 minutes gets its own chapter at the end of the testing series.

If your Rails application is starting to feel heavy, book the free workshop: we look at your change history and your slowest page together, and the first two weeks of work are on me.

Sources

  1. 1.

    Rails Core Team, "Active Record Callbacks", Rails Guides for Rails 7.1, 2023. https://guides.rubyonrails.org/v7.1/active_record_callbacks.html

  2. 2.

    Martin Fowler, "BoundedContext", martinfowler.com, 15 January 2014 (summarising Eric Evans, Domain Driven Design, Addison Wesley, 2003). https://martinfowler.com/bliki/BoundedContext.html

  3. 3.

    Melvin E. Conway, "How Do Committees Invent?", Datamation, April 1968. https://www.melconway.com/Home/Committees_Paper.html

  4. 4.

    David Heinemeier Hansson, "The Majestic Monolith", Signal v. Noise, 29 February 2016. https://signalvnoise.com/svn3/the-majestic-monolith/

  5. 5.

    David Heinemeier Hansson, "The Rails Doctrine", rubyonrails.org, 2016. https://rubyonrails.org/doctrine

  6. 6.

    James Lewis and Martin Fowler, "Microservices", martinfowler.com, 25 March 2014. https://martinfowler.com/articles/microservices.html

  7. 7.

    Martin Fowler, "MonolithFirst", martinfowler.com, 3 June 2015. https://martinfowler.com/bliki/MonolithFirst.html

  8. 8.

    Maple Ong, "Enforcing Modularity in Rails Apps with Packwerk", Shopify Engineering, 23 September 2020. https://shopify.engineering/enforcing-modularity-rails-apps-packwerk

  9. 9.

    Rails Core Team, "Autoloading and Reloading Constants", Rails Guides for Rails 7.1, 2023. https://guides.rubyonrails.org/v7.1/autoloading_and_reloading_constants.html

  10. 10.

    Shopify, "Packwerk usage" (USAGE.md), packwerk repository on GitHub, version 3.2, February 2024. https://github.com/Shopify/packwerk/blob/main/USAGE.md

  11. 11.

    Shopify, packwerk releases (v3.0.0, 1 March 2023), GitHub. https://github.com/Shopify/packwerk/releases

  12. 12.

    Gannon McGibbon and Chris Salzberg, "A Packwerk Retrospective", Rails at Scale, 26 January 2024. https://railsatscale.com/2024-01-26-a-packwerk-retrospective/

  13. 13.

    Ruby at Scale, "packs-rails" README, GitHub, version 0.0.5, December 2023. https://github.com/rubyatscale/packs-rails

  14. 14.

    Rails Core Team, "Getting Started with Engines", Rails Guides for Rails 7.1, 2023. https://guides.rubyonrails.org/v7.1/engines.html

  15. 15.

    Michael C. Feathers, Working Effectively with Legacy Code, Prentice Hall, 2004. https://www.informit.com/store/working-effectively-with-legacy-code-9780131177055

  16. 16.

    Rails Core Team, "Configuring Rails Applications" (config.server_timing, config.active_record.query_log_tags_enabled), Rails Guides for Rails 7.1, 2023. https://guides.rubyonrails.org/v7.1/configuring.html

  17. 17.

    MiniProfiler project, "rack-mini-profiler" README, GitHub. https://github.com/MiniProfiler/rack-mini-profiler

  18. 18.

    Richard Huang and contributors, "Bullet" README, GitHub. https://github.com/flyerhzm/bullet

  19. 19.

    Rails Core Team, "Active Record Query Interface" (eager loading, strict_loading), Rails Guides for Rails 7.1, 2023. https://guides.rubyonrails.org/v7.1/active_record_querying.html

  20. 20.

    Rails Core Team, "add_index" (algorithm: :concurrently), Rails API documentation 7.1. https://api.rubyonrails.org/v7.1/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html

  21. 21.

    Rails Core Team, "Caching with Rails: An Overview", Rails Guides for Rails 7.1, 2023. https://guides.rubyonrails.org/v7.1/caching_with_rails.html

  22. 22.

    Rails Core Team, "Multiple Databases with Active Record", Rails Guides for Rails 7.1, 2023. https://guides.rubyonrails.org/v7.1/active_record_multiple_databases.html

  23. 23.

    ErwinM and contributors, "acts_as_tenant" README, GitHub. https://github.com/ErwinM/acts_as_tenant

  24. 24.

    Rails on Services, "Apartment" (ros-apartment) README, GitHub. https://github.com/rails-on-services/apartment

Shelter

I’m running the London Marathon for Shelter. Sunday 25 April 2027

My personal fundraiser. Shelter, the National Campaign for Homeless People Limited, registered charity 263710 (England and Wales) and SC002327 (Scotland), registered with the Fundraising Regulator.

Donate to Shelter