anantbhandarkar/make-it-right/mir-backend-ruby

Claude Code and agent skill by anantbhandarkar/make-it-right

Trust tier 3
  • community
Source check pending

Checking that the SKILL.md file is still in the repository.

Make It Right (Ruby runtime tier). YARV/MRI Ruby 4.0 runtime reliability footguns shared across EVERY Ruby backend framework (Rails, Sinatra, Hanami, Sidekiq/Solid Queue workers) — distinct from the generic backend gates and from any one framework's mechanics. Covers: the GVL (threads give no CPU parallelism, like Python's GIL), the reworked Ractor API in Ruby 4.0, YJIT/ZJIT enablement, Puma's forked-worker + thread model, fork-safety of DB/Redis connections, copy-on-write memory and per-worker bloat, background job hygiene (idempotency, retries), GC/string-literal pressure, and the Rack/Puma/Bundler security layer every Ruby web app inherits. TRIGGER when the backend runtime is Ruby — sits between mir-backend (generic) and the framework module (e.g. mir-backend-ruby-rails). SKIP for Node/JVM/Go/Rust/.NET/Python/PHP/BEAM runtimes (each has its own mir-backend-<runtime> tier), and for Rails/ActiveRecord library mechanics — N+1, strong parameters, callbacks, migrations, Active Storage — which belong to mir-backend-ruby-rails, not here.

Install

npx vskill@latest install anantbhandarkar/make-it-right/mir-backend-ruby

SKILL.md

The same SKILL.md was published earlier as anantbhandarkar/make-it-right/mir-backend-ruby.

/mir-backend-ruby · Make It Right (Ruby runtime)

The middle tier. mir-backend decides what is correct (any language). The framework module (e.g. mir-backend-ruby-rails) knows the library's mechanics. This tier owns what's true for all Ruby backends because they run on YARV (MRI) and speak Rack — the concurrency model, the process model, and the HTTP/dependency layer that Rails, Sinatra, Hanami, and every job worker inherit.

Runtime assumed: MRI Ruby 4.0 under Puma. Current stable is Ruby 4.0.6; 3.4.x, 3.3.x and 3.2.x are still maintained, 3.1 is EOL (verified against ruby-lang.org on 13 Aug 2026). Notes hold for JRuby except where GVL specifics differ (JRuby has no GVL; true thread parallelism is available). Load order: mir-backend → mir-backend-ruby → <framework module>.

What changed in Ruby 4.0 (check this before trusting older Ruby advice)

Ruby 4.0.0 shipped 25 Dec 2025. It is the release that was planned and written about as "Ruby 3.5" — blog posts and AI training data referring to 3.5 mean this.

ChangeWhat breaksWhat to write instead
Ractor.yield, Ractor#take, #close_incoming, #close_outgoing removedEvery Ractor pipeline written against Ruby 3.x raises NoMethodErrorRactor::Port for message passing; Ractor#join / #value to wait for termination
--rjit removedBoot flags / Dockerfiles carrying --rjit fail to startDrop the flag; use YJIT
Kernel#open / IO with a leading `\` removedCode that relied on `open("\cmd")` to spawn a processIO.popen explicitly (and see Security — this removal kills one command-injection path, not all of them)
ObjectSpace._id2ref removedObject-id-keyed caches and some debug toolingHold real references, or ObjectSpace::WeakMap
cgi stdlib removed (only cgi/escape remains)Legacy code calling CGI.parse, CGI::CookieRack::Utils.parse_nested_query, CGI.escapeHTML (still present via cgi/escape)
Set is now a core C classSubclasses that poked at the internal @hash ivarUse the public API; Set::SubclassCompatible is the escape hatch
Bundler/RubyGems 4 (4.0.3 ships with Ruby 4.0.0)Gemfile.lock gains a CHECKSUMS section and re-indents 3→2 spaces; lockfile-parsing tooling and some deploy paths breakRegenerate the lockfile deliberately, commit it, and pin CI to Bundler ≥ 4 — see Security

The YARV footguns AI walks into (framework-agnostic)

1. The GVL — threads are NOT CPU parallelism

Ruby's Global VM Lock (GVL, formerly GIL) allows only one thread to execute Ruby bytecode at a time. CPU-bound work does not run in parallel across threads — multiple threads serialize on the GVL and you pay context-switch overhead on top. This is still true in Ruby 4.0; no M:N scheduler and no GVL removal landed.

  • CPU-bound (image processing, crypto, heavy computation): use multiple processes (Puma workers), a C extension that releases the GVL (bcrypt, openssl, libvips-backed image work release it internally), or offload to a background worker. Adding more threads will not help — it will make things worse.
  • I/O-bound (DB queries, HTTP calls, disk reads): threads are fine — the GVL releases during blocking I/O syscalls, so other threads run while one waits.
  • This is the runtime-level reason the runtime-map says "SKIP Ruby for high-frequency data pipelines or intense processing."
ruby
# WRONG — adding threads to speed up CPU-bound work; GVL serializes them
threads = data.map { |chunk| Thread.new { heavy_cpu_transform(chunk) } }
threads.each(&:join)
# RIGHT — for CPU-bound parallelism, use processes.
# Do NOT hand-roll this with bare `fork`: in the parent it returns a PID, not the
# block's value, so results are lost, and an unwaited child becomes a zombie.
# Use a pool that marshals results back and reaps (gem "parallel")…
results = Parallel.map(data.each_slice(chunk_size).to_a, in_processes: 4) { |s| compute(s) }
# …or push the work to a job runner — Sidekiq, Solid Queue, GoodJob.
2. Ractors give real parallelism — and the Ruby 3.x Ractor API no longer exists

Ractors run Ruby code in parallel because each has its own GVL. Ruby 4.0 reworked them substantially (lock-free frozen-string sets, per-ractor counters) but they are still marked experimental — every Ractor.new prints a warning, and most gems are not ractor-safe. Do not put a Ractor on a request path without a load test.

The API change is a hard break, not a deprecation:

ruby
# WRONG on Ruby 4.0 — NoMethodError; these were removed
r = Ractor.new { Ractor.yield(compute) }
r.take
# RIGHT — Ractor::Port, or #value for a single result
port = Ractor::Port.new
Ractor.new(port) { |p| p << compute }
port.receive
r = Ractor.new { compute }
r.value # waits for termination and returns the result
r.join # waits without taking a value
  • Only the ractor that created a port may read from it; any ractor holding the port may write. Ractor.select now accepts ports as well as ractors.
  • Objects crossing a ractor boundary must be shareable (frozen and deeply immutable) or they are copied. Ractor.shareable_proc / Ractor.shareable_lambda exist for procs.
  • If your workload is CPU-bound and you were about to reach for Ractors: processes are still the boring, correct answer.
3. YJIT is not on by default — and Rails turns it on for you

Ruby ships YJIT compiled in but not enabled at VM start. ZJIT, new in 4.0, is also compiled in and also off; upstream says it is faster than the interpreter but still slower than YJIT and should not be deployed to production yet.

GoalDo this
Rails appNothing. Rails ≥ 7.2 sets config.yjit = true under load_defaults and calls RubyVM::YJIT.enable after boot, so boot-only code is never compiled
Non-Rails Ruby process (plain Rack app, standalone worker, CLI)Call RubyVM::YJIT.enable yourself after initialization
AnythingDo not set RUBY_YJIT_ENABLE=1 or --yjit on a Rails process — it compiles initialization code that runs once and inflates memory
Experiment with ZJIT--zjit / RUBY_ZJIT_ENABLE / RubyVM::ZJIT.enable. Build needs Rust 1.85+. Not production
  • YJIT costs memory per worker. The code-region cap is --yjit-mem-size (default 128 MiB). Multiply by Puma worker count before sizing a container.
  • Verify it is actually on: RubyVM::YJIT.enabled?. A binary built without Rust has no YJIT at all — ruby -v will not show +YJIT.
  • Measure with RubyVM::YJIT.runtime_stats. In Ruby 4.0 the ratio_in_yjit metric requires a build configured with --enable-yjit=stats.
4. Puma's process × thread model — pool sizing must match DB connections

Puma = N forked worker processes × M threads per worker. Each thread can hold one DB connection at a time. If RAILS_MAX_THREADS (thread count) does not equal the database connection pool pool setting, threads starve waiting for a connection at load spikes.

yaml
# config/database.yml — pool must be at least RAILS_MAX_THREADS (default 5)
production:
pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  • Total DB connections consumed = workers × threads × databases, per host. Compare that number against Postgres max_connections (default 100) or your PgBouncer pool before deploying.
  • The pool is per process and per database. An app with four database entries (Rails 8 generates primary, cache, queue, cable) opens four pools in every Puma worker and every job process. AI copies the same RAILS_MAX_THREADS value into all four and blows past max_connections before serving a request. Size the non-primary pools explicitly for their real concurrency.
  • AI commonly generates a pool much smaller than thread count (e.g. pool: 2 with 5 threads), causing ActiveRecord::ConnectionTimeoutError under any real load.
  • Puma's current lines are 8.0.2 and 7.2.1 (both 27 May 2026). Older Puma is a security problem, not just a stale dependency — see Security.
5. Fork-safety — connections created before fork are invalid in children

When Puma forks worker processes, any DB connection, Redis socket, or file handle opened before the fork is shared at the OS level. The child process ends up with a corrupted or multiplexed connection. This causes silent data corruption, PG::UnableToSend, or deadlocked sockets.

Never open DB/Redis connections at boot time before forking. Initialize them lazily or reconnect in the Puma hook:

ruby
# config/puma.rb
on_worker_boot do
ActiveRecord::Base.establish_connection # reconnect DB pool in child
# If using Redis directly:
# $redis = Redis.new(url: ENV["REDIS_URL"])
end
  • The same applies to any persistent socket: Elasticsearch clients, gRPC stubs, SMTP connections, custom TCP sockets. Audit every initializer that opens a connection — move connection establishment to on_worker_boot or lazy first-use.
  • AI routinely writes $redis = Redis.new(...) in config/initializers/redis.rb without an on_worker_boot reconnect, producing a race condition that only surfaces intermittently under load.
6. Memory: copy-on-write and per-worker bloat

Puma's forked workers share memory pages read-only (copy-on-write, CoW) until a page is modified. Once a worker writes to a page — mutating a shared object, updating a class variable, running the GC — that page is copied into the worker's own address space. Memory use grows per worker over time.

  • Don't mutate shared objects after boot. Memoize with ||= only on thread-local or request-scoped objects, not on class-level constants or module variables that will be written during requests.
  • Frozen string literals reduce object churn and help CoW; add # frozen_string_literal: true to every file.
  • Memory bloat mitigation: use jemalloc (link Puma against it with LD_PRELOAD) to reduce fragmentation. Use puma-worker-killer to restart workers that exceed a memory threshold, preventing unbounded bloat. Budget for YJIT's per-worker code memory on top (§3).
ruby
# Gemfile — memory management
gem "puma-worker-killer"
# config/puma.rb — NOT an initializer. In clustered mode the killer has to run in
# the master (it restarts workers), and a thread started before fork is not
# inherited by the children. before_fork is the supported hook.
before_fork do
PumaWorkerKiller.config do |config|
config.ram = 1024 # MB — restart worker above this
config.frequency = 5 # seconds between checks
config.percent_usage = 0.98
end
PumaWorkerKiller.start
end
7. Background jobs — async/durable work belongs in a worker, not the request thread

A request thread lives for the duration of one HTTP request. Any work that must survive a deploy, be retried on failure, or take longer than ~100ms should run in a background worker (Solid Queue, Sidekiq, GoodJob). AI commonly writes inline work in the controller that should be a job.

  • Idempotency is mandatory. Workers retry on failure — a job may run more than once. Guard side effects with a unique key, a DB uniqueness constraint, or an idempotency check before executing.
ruby
class SendReceiptJob < ApplicationJob
queue_as :default
def perform(order_id)
order = Order.find(order_id)
return if order.receipt_sent? # collapses the common retry
ReceiptMailer.send_receipt(order).deliver_now
order.update!(receipt_sent: true)
end
end

A check-then-flag guard closes the common case, not the real one: a crash between deliver_now and update! sends the receipt twice. For anything that costs money or is externally visible, the guard has to be the side effect's own dedup key — a provider idempotency key on the charge, a Idempotency-Key header on the send, or a unique index on an outbox row written in the same transaction as the state change.

This is the start of the file. Read the full SKILL.md on GitHub.

Security

  • Security scanPassed, 95 of 100Pattern checks on the skill's files.
  • Model reviewPassed

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

Repository stars
15
7-day trend score
14

Stars and forks are for the whole GitHub repository, not this skill alone. Not refreshed yet.

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/anantbhandarkar/make-it-right/mir-backend-ruby/badge)](https://verified-skill.com/skills/anantbhandarkar/make-it-right/mir-backend-ruby)

Something wrong with this skill or its page? Tell us.