You deploy a Rails 7 app on Puma in a 2 GiB PaaS container. The default WEB_CONCURRENCY=2, RAILS_MAX_THREADS=5. Memory climbs steadily after boot — 300 MiB, 600 MiB, 1.4 GiB, OOM. You read about preload_app! and copy-on-write, set it, restart, and the picture looks better for an hour. Then memory climbs again. The puzzle is real and the answer is specific: copy-on-write works, but Ruby’s memory allocator and Rails’s autoloading defeat it unless you configure both.
What’s happening
Puma’s process model is one master + N worker processes. With preload_app!, the master loads Rails before forking workers. Workers inherit pages shared via copy-on-write — if nobody writes, no memory is copied. The trouble is that Ruby’s GC and the default glibc malloc both do write across many pages early, undoing the sharing within minutes:
- GC marks. Mark bits live alongside object headers. Marking touches almost every page eventually.
- Heap fragmentation.
mallocarenas grow unpredictably; long-lived processes accumulate fragmented heap that doesn’t return to the kernel. - Threaded allocation. Each thread asks
glibcmallocfor its own arena. Five threads per worker × four workers = twenty arenas competing for the same address space, never compacting. - Lazy autoload. Rails 7 with Zeitwerk loads constants on first reference. If you didn’t
eager_load = true, each worker reloads classes after fork — defeating preload entirely.
Two changes recover most of the lost sharing: jemalloc instead of glibc malloc, and config.eager_load = true in production so the master loads everything before forking. After those, the typical Rails app sees 30-50% less RSS per worker.
How to verify
Check the four signals.
# 1. Are workers actually sharing pages with the master?
for pid in $(pgrep -f 'puma.*worker'); do
echo -n "pid=$pid shared="; \
awk '/^Shared_Clean|^Shared_Dirty/ {s+=$2} END {print s" kB"}' /proc/$pid/smaps_rollup
done
After a fresh boot you should see hundreds of MiB shared. If after 30 minutes of traffic that number has collapsed to 50-80 MiB per worker, copy-on-write is broken.
# 2. Which allocator is in use?
cat /proc/$(pgrep -f 'puma master')/maps | grep -E 'libjemalloc|libtcmalloc|libc\.so' | head -5
If only libc.so appears, you’re on glibc malloc. Switch.
# 3. Is autoload still doing work after fork?
# (look for "autoload_paths" or "load_dependency" in stack traces)
rbtrace -p $(pgrep -f 'puma.*worker' | head -1) -e 'Thread.list.map(&:backtrace)' | head -30
# 4. The kernel's view of the container
cat /sys/fs/cgroup/memory.current
cat /sys/fs/cgroup/memory.max
If memory.current exceeds 90% of memory.max consistently, no amount of CoW tuning will save you — the workload genuinely needs more memory or fewer workers.
The fix
Three pieces. The puma.rb, the config/environments/production.rb change, and the Dockerfile.
config/puma.rb:
# config/puma.rb
require "concurrent"
# Threads per worker — Rails 7 default of 5 is too high for most apps.
# Database pool size MUST be >= threads + 1 (the +1 is for the reaper).
threads_count = ENV.fetch("RAILS_MAX_THREADS", 3).to_i
threads threads_count, threads_count
# Worker count — start with cores and adjust by memory budget
workers ENV.fetch("WEB_CONCURRENCY", 2).to_i
# Preload the app in the master process so workers fork from a warm Rails
preload_app!
# Bind
port ENV.fetch("PORT", 3000)
environment ENV.fetch("RAILS_ENV", "production")
# Plugin hooks
plugin :tmp_restart
# Worker lifecycle hooks
on_worker_boot do
# Reconnect ActiveRecord — connections from the master must not be shared
ActiveRecord::Base.establish_connection if defined?(ActiveRecord)
# Reconnect Redis, Sidekiq client, etc.
Redis.current = Redis.new(url: ENV["REDIS_URL"]) if defined?(Redis)
end
before_fork do
# Disconnect AR in the master to avoid post-fork warnings
ActiveRecord::Base.connection_pool.disconnect! if defined?(ActiveRecord)
end
# Restart workers on a schedule to bound memory growth from C-extension leaks
worker_timeout 60
worker_boot_timeout 60
worker_shutdown_timeout 30
# Phased restart support — graceful redeploys
queue_requests true
wait_for_less_busy_worker 0.005
# Bind a separate control socket for graceful operations
activate_control_app "unix:///tmp/puma-control.sock", { auth_token: ENV["PUMA_AUTH_TOKEN"] }
# Lower-overhead logging to STDOUT/STDERR; let the platform collect it
stdout_redirect "/dev/stdout", "/dev/stderr", true
config/environments/production.rb — the line that makes preload work:
# config/environments/production.rb
Rails.application.configure do
config.eager_load = true # MUST be true for preload_app! to share pages
config.cache_classes = true
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Logging
config.log_level = :info
config.log_tags = [:request_id]
config.logger = ActiveSupport::TaggedLogging.new(Logger.new($stdout))
# Asset host, force_ssl, etc.
config.force_ssl = true
end
eager_load = true is non-negotiable. Without it, Zeitwerk autoloads classes on first reference inside each worker, which writes to pages that should have been shared, and your CoW savings disappear in the first ten minutes of traffic.
Database pool — the half of the bug nobody talks about:
If threads = 3 and workers = 2, you have 6 threads asking for connections. config/database.yml:
production:
adapter: postgresql
encoding: unicode
pool: <%= (ENV.fetch("RAILS_MAX_THREADS", 3).to_i) + 2 %>
prepared_statements: false # mandatory if you're behind pgBouncer in transaction mode
advisory_locks: false # same reason
url: <%= ENV.fetch("DATABASE_URL") %>
timeout: 5000
checkout_timeout: 5
pool = threads + 2 covers the reaper plus a buffer. prepared_statements: false is mandatory if your Postgres is behind pgBouncer in transaction-pool mode — otherwise you’ll get prepared statement "a1" already exists randomly. We document this trade-off in Postgres connection-pool exhaustion.
Dockerfile with jemalloc:
FROM ruby:3.3-slim-bookworm AS builder
RUN apt-get update \
&& apt-get install -y --no-install-recommends \
build-essential libpq-dev libssl-dev libyaml-dev git curl pkg-config \
libjemalloc-dev libjemalloc2 nodejs \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /app
COPY Gemfile Gemfile.lock ./
RUN bundle config set without 'development test' \
&& bundle config set deployment 'true' \
&& bundle install --jobs 4 --retry 3
COPY . .
RUN SECRET_KEY_BASE=dummy bundle exec rake assets:precompile
FROM ruby:3.3-slim-bookworm AS runtime
RUN apt-get update \
&& apt-get install -y --no-install-recommends \
libpq5 libjemalloc2 libyaml-0-2 curl tini \
&& rm -rf /var/lib/apt/lists/* \
&& groupadd -g 1001 app \
&& useradd -u 1001 -g app -m -d /app app
# Load jemalloc as the malloc implementation for everything in this image
ENV LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libjemalloc.so.2 \
MALLOC_CONF=narenas:2,background_thread:true,metadata_thp:auto,dirty_decay_ms:5000 \
RUBY_YJIT_ENABLE=1 \
RUBY_GC_HEAP_GROWTH_FACTOR=1.1 \
RUBY_GC_OLDMALLOC_LIMIT=33554432 \
RUBY_GC_MALLOC_LIMIT=16777216 \
BUNDLE_PATH=/app/vendor/bundle \
BUNDLE_WITHOUT=development:test \
RAILS_LOG_TO_STDOUT=1 \
RAILS_SERVE_STATIC_FILES=1
COPY --from=builder --chown=app:app /app /app
WORKDIR /app
USER app
EXPOSE 3000
HEALTHCHECK --interval=10s --timeout=3s --start-period=30s --retries=3 \
CMD curl -fsS http://127.0.0.1:3000/up || exit 1
ENTRYPOINT ["/usr/bin/tini", "--"]
CMD ["bundle", "exec", "puma", "-C", "config/puma.rb"]
The MALLOC_CONF line is what most people get wrong. narenas:2 matches the worker count; dirty_decay_ms:5000 returns dirty pages to the OS aggressively (the default of 10 seconds keeps the kernel from reclaiming them, which looks like a “leak”). background_thread:true lets jemalloc do this work off the request path.
RUBY_YJIT_ENABLE=1 turns on YJIT, the in-tree Ruby JIT — a free 15-30% on Rails workloads in Ruby 3.3. There is a memory cost (~50-100 MiB of cached compiled code), so account for it in your sizing.
RUBY_GC_HEAP_GROWTH_FACTOR=1.1 slows the rate at which Ruby’s heap expands after a major GC, so you don’t get a sawtooth between 600 MiB and 1.2 GiB.
Verifying the change landed
After redeploying:
# Should show ~2× the previous shared memory
for pid in $(pgrep -f 'puma.*worker'); do
awk '/^Shared_Clean|^Shared_Dirty/ {s+=$2} END {print s/1024" MiB shared"}' /proc/$pid/smaps_rollup
done
# Should show libjemalloc loaded
ldd $(which ruby) | grep jemalloc || echo "WARNING: jemalloc not loaded — check LD_PRELOAD"
Two workers at 3 threads with jemalloc and eager_load = true typically sit at 500-650 MiB total RSS for a medium Rails app — versus 1.4 GiB on the same workload with glibc malloc and eager_load = false. That’s the gap.
We tune Ruby and Rails runtimes for memory-tight PaaS containers — jemalloc, YJIT, Puma sizing, eager-load discipline — as part of Cloud PaaS. If your Rails containers are OOM-killing and preload_app! “should have fixed it,” book a deeper review.