Scaling Ruby on Rails is mostly about fixing a few specific bottlenecks in the right order, not about changing frameworks: slow database queries first, then slow work inside web requests, then repeated work you could cache, and only then more servers and databases. Rails runs some of the largest web apps on the internet, and most Rails apps that feel slow are slow because of a handful of queries, not because of Ruby.
This guide is a stage-by-stage plan for startups that built on Rails and are starting to feel growth: pages getting slower, the database working harder, deploys getting scary. For each stage you’ll see the signal that says it’s time, what to change, and Rails 8 code for it. It’s for founders and CTOs deciding where to spend engineering time, and for the Rails developers doing the work.
I ran the examples on Rails 8.1.4, Ruby 4.0.8, Puma 8.0.2 and PostgreSQL 18, with 200,000 tasks across 500 projects. The timings are from my laptop and show the size of the difference, not production numbers.
Does Rails scale?
Yes. Shopify’s core app is a Rails monolith; in 2020 Shopify said it had over 2.8 million lines of Ruby and hundreds of developers working on it. GitHub says GitHub.com has been a Rails monolith since the beginning, with nearly two million lines of code and more than 1,000 engineers working on it daily (2023, updated 2024).
Your app isn’t Shopify, and it doesn’t need to be. The useful lesson is that both companies scaled one Rails codebase with careful database work, caching, background jobs and clear internal boundaries, rather than rewriting it. A startup can follow the same path in small steps.
Measure before you change anything
Most scaling mistakes come from guessing. Before you add servers or rewrite code, find out where the time goes. Track these for every important endpoint and job queue:
| Metric | What it tells you |
|---|---|
| p95 response time | How slow the app feels for the unlucky 5% of requests |
| Time in database vs Ruby | Whether to fix queries or code |
| Queries per request | N+1 problems (more on these below) |
| Job queue latency | How long jobs wait before they start |
| Database CPU and connections | How close the database is to its limits |
| Memory per Puma process | How many processes fit on a server |
Your Rails log already shows time in Active Record vs views for each request. An APM tool (Application Performance Monitoring) collects the same data across all requests and ranks your slowest endpoints. For one slow query, ask Postgres how it runs it, from the console:
Task.where(status: "overdue").order(created_at: :desc).limit(20)
.explain(:analyze)explain(:analyze) runs the query and shows the real plan and timing. A Seq Scan on a large table is usually the first thing to fix.
The scaling plan at a glance
Work up from the cheapest fixes. Each stage has a signal that says it’s time:
| Stage | What to do | Signal that it’s time |
|---|---|---|
| 1 | Fix database queries | Slow pages; many queries per request; Seq Scan in plans |
| 2 | Move slow work to jobs | Requests that send email, call APIs or build files |
| 3 | Cache expensive results | The same slow query or partial runs again and again |
| 4 | Tune Puma and add app servers | CPU busy on app servers; requests waiting for a thread |
| 5 | Add read replicas | Database CPU high from reads, after stages 1–3 |
| 6 | Build a modular monolith | Teams slowing each other down, not servers |
Stages 1–3 usually cost days, not months, and they often remove the need for stages 4–5 for a long time.
Stage 1: Fix the database queries
The database is where most Rails apps spend their time, and query problems grow with your data: a page that’s fine with 1,000 rows can time out with a million.
Remove N+1 queries
An N+1 query happens when you load a list and then run one more query for each item. This dashboard code looks innocent:
Project.limit(25).each do |project|
project.account.name
project.tasks.count
endIn my test it ran 51 queries: 1 for the projects, then 25 for accounts and 25 for task counts. Preloading the associations brings it to 3:
Project.includes(:account, :tasks).limit(25).each do |project|
project.account.name
project.tasks.size # counts the preloaded records, no query
endTo stop new N+1 queries from creeping in, make lazy loading raise an error in development and test:
# config/environments/development.rb (and test.rb)
config.active_record.strict_loading_by_default = trueOr turn it on for one query with Project.strict_loading. Any association you forgot to preload raises ActiveRecord::StrictLoadingViolationError, so you find the problem in a test instead of in production.
Add the indexes your queries need
A missing index makes Postgres read the whole table. This “overdue tasks” query on 200,000 rows took 13.1 ms with a sequential scan. After adding an index that matches both the filter and the sort, it took 0.044 ms:
class AddStatusCreatedAtIndexToTasks < ActiveRecord::Migration[8.1]
disable_ddl_transaction!
def change
add_index :tasks, %i[status created_at], algorithm: :concurrently
end
end13 ms doesn’t sound like much, but it grows with the table, and a dashboard may run that query for every visitor. algorithm: :concurrently builds the index without locking writes, which matters once the table is large and the app is live. It can’t run inside a transaction, hence disable_ddl_transaction!.
Use counter caches for counts you show often
Showing “385 tasks” next to every project runs a COUNT query per project. A counter cache stores the number on the parent row and keeps it updated:
class AddTasksCountToProjects < ActiveRecord::Migration[8.1]
def change
add_column :projects, :tasks_count, :integer, default: 0, null: false
up_only do
execute <<~SQL
UPDATE projects SET tasks_count = (
SELECT COUNT(*) FROM tasks WHERE tasks.project_id = projects.id
)
SQL
end
end
endclass Task < ApplicationRecord
belongs_to :project, counter_cache: true
endNow project.tasks.size reads the column, so the dashboard only needs includes(:account). In my test, creating a task moved the count from 385 to 386, and the dashboard loop ran 2 queries without loading any tasks. The up_only block fills the column for existing rows; on a very large table, run that backfill in batches from a job instead.
Stage 2: Move slow work to background jobs
Anything that doesn’t need to finish before the user sees a response belongs in a job: sending email, calling payment or AI APIs, generating PDFs and CSV exports, processing uploads, syncing with other systems.
# Inside the request: the user waits for the mail server
InvoiceMailer.with(invoice: invoice).paid.deliver_now
# In a job: the request returns right away
InvoiceMailer.with(invoice: invoice).paid.deliver_laterRails 8 uses Solid Queue by default: jobs are stored in the database, in their own queue database in the default production config, so you don’t need Redis to start. Sidekiq with Redis is still a good choice when you already run Redis or need very high job throughput.
Watch job queue latency, not just job duration. If jobs wait minutes before they start, add worker threads or processes, or split slow and urgent work into separate queues so a big export can’t delay password-reset emails.
Stage 3: Cache expensive results
Caching helps when the same expensive work runs again and again with the same result. It doesn’t fix a slow query that runs once; fix that in Stage 1.
For a slow calculation, cache the result for a few minutes:
def task_stats(account)
Rails.cache.fetch(["task-stats", account.id], expires_in: 10.minutes) do
Task.joins(:project)
.where(projects: { account_id: account.id })
.group(:status).count
end
endIn my test, three calls ran the query once; the other two came from the cache. For views, wrap expensive partials in cache blocks keyed on the record, so they expire automatically when the record changes:
<% @projects.each do |project| %>
<% cache project do %>
<%= render project %>
<% end %>
<% end %>Rails 8 uses Solid Cache in production by default. It stores the cache in a database table instead of memory, which makes a large cache affordable. Static assets should go through a CDN, so your Rails servers never serve them.
Stage 4: Tune Puma and add app servers
When app servers run out of CPU, or requests wait for a free thread, it’s time to add capacity. First make sure each server is configured well. Rails’ deployment tuning guide recommends:
- Threads: the generated
config/puma.rbuses 3 threads per process, and the guide says most apps won’t benefit from more. More threads can hurt response times. - Processes (workers): one per CPU core. Puma reads
WEB_CONCURRENCY, so setWEB_CONCURRENCY=4on a 4-core server.automatches the core count, but it can be wrong on shared cloud CPUs. - YJIT: Ruby’s JIT compiler. Apps on
load_defaults "8.1"get it outside development and test automatically. - jemalloc: a memory allocator that reduces memory growth with threaded Puma. The Dockerfile Rails generates already uses it.
Then add servers behind a load balancer. Rails apps are stateless by default (sessions live in cookies, cache and jobs in the database), so adding a second server is usually a deploy-config change. With Kamal, the default deploy tool in Rails 8, it’s another host in config/deploy.yml. One exception to check first: a new Rails app stores Active Storage uploads on the server’s local disk (config.active_storage.service = :local). With two servers, a file uploaded to one isn’t on the other, so move uploads to S3 or another object store before you add the second server.
Count your database connections before you add servers. Every Puma thread can hold one database connection, so:
| Setup | Connections |
|---|---|
| 1 server × 4 workers × 3 threads | 12 |
| 3 servers × 4 workers × 3 threads | 36 |
| + Solid Queue workers, console, cron | a few more |
Postgres allows 100 connections by default, and managed plans often allow fewer. Keep max_connections in database.yml (called pool before Rails 8.1) at least equal to the threads per process. When the total gets close to the database limit, put a connection pooler such as PgBouncer in front of Postgres.
Stage 5: Add read replicas
If the database is still the bottleneck after stages 1–3, and most of its work is reads, add a read replica: a copy of the database that receives every change from the primary and serves read queries. Rails supports this directly:
# config/database.yml
production:
primary:
<<: *default
database: app_production
primary_replica:
<<: *default
database: app_production
host: <%= ENV["REPLICA_HOST"] %>
replica: true# app/models/application_record.rb
class ApplicationRecord < ActiveRecord::Base
primary_abstract_class
connects_to database: { writing: :primary, reading: :primary_replica }
endThen let Rails choose the database per request. Run bin/rails g active_record:multi_db and enable the settings it generates:
# config/initializers/multi_db.rb
Rails.application.configure do
config.active_record.database_selector = { delay: 2.seconds }
config.active_record.database_resolver =
ActiveRecord::Middleware::DatabaseSelector::Resolver
config.active_record.database_resolver_context =
ActiveRecord::Middleware::DatabaseSelector::Resolver::Session
endIn my test, a GET request used the replica, a POST used the primary, and a GET right after the POST stayed on the primary. That last part is the delay: replicas lag slightly behind the primary, so for 2 seconds after a user writes something, Rails reads from the primary and the user sees their own change. Writing on the replica raises ActiveRecord::ReadOnlyError, so a mistake fails loudly instead of losing data. For reports or exports that can tolerate a small delay, you can also choose the replica explicitly:
ActiveRecord::Base.connected_to(role: :reading) do
MonthlyReport.generate(account)
endSharding, splitting data across several primary databases, is supported by Rails too, but it adds complexity to every query and migration. Most startups never need it. A bigger database server, good indexes and replicas go a long way.
Stage 6: Scale the team with a modular monolith
At some point the bottleneck is people, not servers: deploys conflict, a change in billing breaks reporting, and new developers take weeks to find their way around. This is when teams reach for microservices, and it’s usually too early.
Microservices replace method calls with network calls. That brings retries, timeouts, partial failures, data that drifts out of sync, and an operations workload a small team rarely has time for. Shopify’s approach was different: keep one codebase, split it into components with clear boundaries, and extract a service only “for good reasons”. In a Rails app that means:
- Group code by business area (
billing,reporting,accounts), for example as Rails engines or namespaced folders. - Make each area expose a small public API and keep its internals private. Packwerk can check those boundaries in CI.
- Extract a separate service only when one part has clearly different needs, such as a different scaling profile, language or release cycle.
Mistakes that make scaling harder
- Adding servers before fixing queries. More app servers send more queries to the same database and can make it worse.
- Caching around a slow query. The first visitor still waits, the cache expires, and invalidation bugs show users old data.
- Raising Puma threads to 10 or more. Ruby runs one thread at a time per process for Ruby code, so extra threads mostly add waiting time and database connections.
- Kubernetes or microservices for a small team. They solve problems you probably don’t have yet, and they cost engineering time every week.
- Rewriting in another language. It pauses product work for months, and the new system meets the same database problems.
Most of the startups I talk to don’t need a new architecture; they need a week of focused work on queries, jobs and caching, and the monitoring to see what changed. That’s what my performance audit covers.
Scaling checklist
- p95 response time, queries per request and job latency are tracked for key endpoints.
-
strict_loadingcatches N+1 queries in development and tests. - Every slow query has been checked with
explain(:analyze), and indexes are added concurrently. - Email, API calls, exports and uploads run in background jobs.
- Expensive, repeated results are cached with clear expiry.
- Puma uses about 3 threads and one worker per core, with YJIT and jemalloc.
- Total database connections fit under the database limit.
- Read replicas are added only after the cheaper fixes, with automatic role switching.
- Code is grouped by business area with clear boundaries.
Newer releases matter here too: my Rails 8.1 upgrade guide covers the performance-relevant changes.
Conclusion
Scaling Ruby on Rails is a sequence, not a rewrite. Measure first. Then fix N+1 queries and missing indexes, move slow work into Solid Queue jobs, and cache what repeats. When servers are genuinely busy, tune Puma and add more of them, keeping an eye on database connections. Add read replicas when reads overload the database, and organize the codebase into a modular monolith when the team, not the traffic, is what’s slowing you down.
If your Rails app is getting slower as you grow, I can help you find the real bottlenecks, fix them in order, and set up the monitoring that shows the next one before your users notice. Send me a short brief and book a discovery call.
Frequently asked questions
Is Ruby on Rails scalable?
Yes. Shopify and GitHub both run large Rails monoliths with hundreds to over a thousand engineers. For most apps, the limits come from database queries, caching and architecture decisions, not from Rails itself, and those are fixable without changing frameworks.
How many users can a Rails app handle?
There’s no single number, because it depends on what each request does, not on Rails. An app that serves cached pages handles far more traffic per server than one that builds large reports on every request. Measure your own p95 response time and throughput under load, then scale the part that limits you.
Is Rails slower than Node.js or Go?
For raw speed on small benchmarks, often yes. In real web apps, most of the time is spent waiting on the database and other services, so the framework’s speed matters less than your queries and caching. YJIT has also made Ruby noticeably faster in recent versions. Choose the stack your team can ship and maintain well.
When should a Rails startup move to microservices?
Usually later than people think, and often never for most of the app. Start with a modular monolith, with clear boundaries inside one codebase. Extract a service only when one part has clearly different needs, such as a separate scaling profile, a different language, or a team that must release independently.
How many Puma workers and threads should I use?
Rails’ deployment guide recommends 3 threads per process, the generated default, and one worker per CPU core. Set workers with WEB_CONCURRENCY. Then make sure your database can accept servers × workers × threads connections, plus your job workers.
Do I need Redis to scale a Rails 8 app?
Not to start. Rails 8 uses Solid Queue for jobs, Solid Cache for caching and Solid Cable for Action Cable, all backed by the database. Redis is still useful at high job volumes or if you already run it, but it’s no longer required.
Should I upgrade Rails before scaling?
Often, yes. Newer Rails and Ruby versions bring YJIT by default, Solid Queue and Solid Cache, better multi-database support and security fixes. Running an old version also makes every other change riskier. A Rails upgrade is often the first step in a scaling plan.


