website logo

← All articles

Scaling a Rails Monolith to 10M+ Requests/Day Without a full rewrite

How we scaled a Rails monolith from 800K to 10M+ requests/day the boring way: without a rewrite or microservices, same codebase, and resisting every shiny architectural temptation along the way.

This is the story of what actually worked, in the order we did it: cheapest fix first, including the mistakes I’d avoid if I did it again.

The Night I Realized We Were Fighting the Wrong Battle

Our P95 latency on the main dashboard hit nine seconds. The CEO already decided to double our web servers the week before expecting a quick win. Then came the frontline people asking in the incident channel why the “scale-up” hadn’t worked.

I pulled up the slow query log and felt genuinely stupid. The top query ran on every dashboard load and joined eight tables. It had no index on the join column. We had been buying more servers to run the same broken query faster. That’s the moment I stopped thinking about infrastructure and started treating the database as the real ceiling.

The lesson I keep coming back to: profile before you buy. A five-minute look at the slow query log would have saved us two weeks of infrastructure spend.

The Order I’d Do It Again, and Why

Here’s the sequence I now follow instinctively, and it’s I do whenever I take ownership of a new project. Cheapest fix first, most expensive last:

  1. Fix the queries. Hours. Free.
  2. Add caching. Days. Cheap.
  3. Move blocking work to background jobs. Days. Cheap.
  4. Scale web processes horizontally. Minutes. Ongoing cost.
  5. Add read replicas and a connection pooler. Weeks. Some complexity.

PS: I put illustrative code snippets for all the following, to make the concepts easy to grasp for the reader.

Step 1: Fix the Queries

The missing index

The dashboard query that started this whole journey had no index on its join column. Adding one took the query from nine seconds to under 200ms. Adding a single add_index is always the highest-ROI line of code I’ve ever shipped.

class AddIndexToPostsUserId < ActiveRecord::Migration[8.0]
  def change
    add_index :posts, :user_id
  end
end

The materialized view that saved my weekend

Some queries can’t be saved by indexes: their shape is rather the problem. Our feed query was four seconds. I threw indexes at it like a man possessed. Nothing. Eight joins on tables that grew every day.

I remember the specific moment I gave up on making the query fast and decided to make it not run live. A materialized view refreshed every five minutes. Eighty milliseconds. The team thought I was a genius. The truth is I just got tired of optimizing the wrong thing.

Sometimes denormalization is the right answer, and it took me too long to accept that.

class CreateFeedMaterializedView < ActiveRecord::Migration[7.1]
  def up
    execute <<~SQL
      CREATE MATERIALIZED VIEW feed_items AS
      SELECT
        posts.id AS post_id,
        posts.user_id,
        posts.created_at,
        users.name AS author_name,
        COUNT(comments.id) AS comment_count,
        COUNT(reactions.id) AS reaction_count
      FROM posts
      JOIN users ON users.id = posts.user_id
      LEFT JOIN comments ON comments.post_id = posts.id
      LEFT JOIN reactions ON reactions.post_id = posts.id
      GROUP BY posts.id, users.name;
    SQL

    add_index :feed_items, :post_id, unique: true
    add_index :feed_items, :created_at
  end
end
# Refresh every 5 minutes via cron
class RefreshFeedViewJob < ApplicationJob
  def perform
    ActiveRecord::Base.connection.execute(
      "REFRESH MATERIALIZED VIEW CONCURRENTLY feed_items"
    )
  end
end

The CONCURRENTLY keyword is the detail that actually matters. Without it, the refresh locks the view and the feed goes blank for users during the refresh window. With it, reads keep flowing while the view rebuilds. Slower refresh, zero downtime. For a feed that tolerates five-minute staleness, that’s the obvious trade, and it’s the kind of trade you can only make confidently after you’ve been spending a few nights at the alternative.

Step 2: Add Caching

Fragment caching for partials that don’t change per user was our biggest single win. An entire sidebar component cached by an updated_at timestamp. One Redis call replaced fifteen queries per page load. I think we cut our average database load by 40% with one cache block.

<%# app/views/layouts/_sidebar.html.erb %>
<% cache [current_account, "sidebar", current_account.updated_at] do %>
  <%= render partial: "sidebar/navigation" %>
  <%= render partial: "sidebar/recent_activity" %>
<% end %>

Then we added HTTP caching with surrogate keys and finally understood what people mean by “cache at the edge.” Fastly purged by entity type. When a product updated, one API call purged product-123 across thousands of cached pages. Origin traffic dropped 70%. I remember the look on our SRE’s face when the graph went vertical.

class ProductsController < ApplicationController
  def show
    @product = Product.find(params[:id])
    response.headers["Surrogate-Key"] = "product-#{@product.id}"
    fresh_when(@product)
  end
end
class Product < ApplicationRecord
  after_commit :purge_cdn_cache, on: :update

  private

  def purge_cdn_cache
    CdnPurgeJob.perform_later("product-#{id}")
  end
end

The layering is what I’d emphasize to any lead: CDN for static and public, Redis for expensive application data, HTTP headers for browser-side. One endpoint of ours averaged 900ms until we pushed work to the right layer. Dropped to 180ms. Database traffic fell another 40%. We didn’t write better code; we stopped asking the wrong layer to do the work.

Step 3: Move Blocking Work to Background Jobs, separately

Sidekiq queues were originally one queue. Under load, password reset emails queued behind image processing. I’m not proud of how long it took me to notice. Split by priority and resource profile and the “email takes 20 minutes to deliver” tickets disappeared overnight.

# config/sidekiq.yml
:queues:
  - [critical, 6]    # password resets, payment webhooks
  - [default, 3]     # user-facing async work
  - [mailers, 2]     # email delivery
  - [low, 1]         # analytics, cleanup
class PasswordResetJob < ApplicationJob
  queue_as :critical
end

class ImageProcessingJob < ApplicationJob
  queue_as :low
end

Then came the day a single database update enqueued 50,000 jobs because we did it per-record. Redis memory spiked. Workers choked. I spent a Saturday morning watching Sidekiq drain a queue at 40 jobs per second and calculating how long until morning. Batching and rate-limiting at the enqueue level fixed it permanently.

# Before: 50,000 jobs, 50,000 Redis entries, very bad Saturday
User.find_each { |u| RecalculateStatsJob.perform_later(u.id) }

# After: 50 jobs, each handling 1,000 records
User.in_batches(of: 1_000) do |batch|
  RecalculateStatsBatchJob.perform_later(batch.pluck(:id))
end

Sidekiq concurrency is not a “more is better” dial. The GVL means threads in one process contend for one CPU core. Five threads per process is a sane start. Add processes, not threads, when you need throughput. That advice alone would have saved me a weekend.

Step 4: Scale Web Processes Horizontally

Puma tuning is boring and that’s why it works. Workers and threads matched to the database pool. Pool sized to threads. This is the cheap, fast lever ie. more Puma processes across more servers, but only once you’ve stopped wasting cycles on steps 1–3.

# config/puma.rb
workers ENV.fetch("WEB_CONCURRENCY", 3).to_i
threads_count = ENV.fetch("RAILS_MAX_THREADS", 5).to_i
threads threads_count, threads_count

But horizontal web scaling only stays cheap if your database can absorb the extra connections. Which brings us to the step that almost took us down.

Step 5: Add Read Replicas and a Connection Pooler

Read replicas

Read replicas bought us roughly six months of headroom. Rails’ native connected_to made the routing almost boring, which is exactly what you want. The hard part wasn’t the routing, it was replication lag. A user updates their profile, hits refresh, and sees the old data. Support tickets. Angry Slack messages. Me explaining “eventual consistency” to a product manager at 7pm.

So we got careful about read-your-writes paths. Anything that followed a mutation went to primary explicitly. Everything else stayed on replicas.

# config/database.yml
production:
  primary:
    <<: *default
    database: app_production
  primary_replica:
    <<: *default
    database: app_production
    replica: true
# ApplicationController: default reads to replica
class ApplicationController < ActionController::Base
  around_action :route_reads

  private

  def route_reads
    ActiveRecord::Base.connected_to(role: :reading) do
      yield
    end
  end
end

# Explicit primary read where the user must see their own write
ActiveRecord::Base.connected_to(role: :writing) do
  @dashboard = current_user.dashboard.reload
end

The connection pool thing

This almost took us down. I didn’t understand it for longer than I want to admit. Active Record’s pool is per process, not per app. We had 3 Puma workers at pool 5 and 2 Sidekiq processes at concurrency 10. One app server needs 35 connections. Three servers and Postgres is screaming about max_connections. I learned this the hard way on a Friday.

The fix was PgBouncer in transaction mode plus prepared_statements: false. Raising the pool doesn’t add capacity, it just changes how long a thread waits before it times out. I wish someone had told me that two years earlier.

The formula I keep on a sticky note:

(Puma workers × pool) + (Sidekiq processes × concurrency) + headroom

If that number exceeds your Postgres limit, PgBouncer is the answer. Raising the pool just shifts where the queue forms.

The Things I Chose Not to Do, and Why

I didn’t shard. Sharding changes your migrations, your cross-tenant queries, your whole mental model. It’s right when a single primary can’t handle your write volume. Our writes were fine. Our reads were the problem, and steps 1–5 solved them. Sharding would have been solving a problem we didn’t have.

I didn’t extract services. Every consultant I talked to told me the monolith was the problem. It wasn’t. Adding caching and replicas took three weeks. Splitting into services would have taken six months, and I’d have traded slow queries for distributed tracing at 2am. No thank you.

I didn’t optimize everything. We fixed the feed, the sidebar, the email queue, and the dashboard. Everything else waited until it appeared in the slow query log or the latency dashboard. The discipline of not optimizing prematurely is the thing I’m proudest of in hindsight.

What I Actually Measured

Not requests per second. Not server count. P95 latency on the endpoints real users touch. I watched that graph after every deploy. Flat? Roll it back and profile again. Down? Ship the next step.

That’s the whole trick. The monolith handled 10M requests/day after all these changes because we treated the database as the bottleneck it was, fixed the cheapest things first, and honestly because I stopped trying to build the system I thought I should build and started fixing the one I actually had.

If you’re a lead staring at the same graphs I was, my advice is unglamorous: open the slow query log before you open your cloud billing console. The answer is almost always already there.