What does a Rails engine actually give you, and what does it not enforce?

A Rails engine is a miniature application that a host app loads at boot. For a modular monolith, the useful parts are:

  • isolate_namespace: Called in the engine class, it scopes the engine's controllers, helpers, route helpers and models under a module such as Billing. ActiveRecord models get a table name prefix (billing_invoices), and the engine's routes live in their own route set instead of merging into the host's.
  • Its own app/ tree: Models, controllers, jobs and views sit under the engine's directory and are autoloaded like the host's.
  • Routes: The engine defines its own config/routes.rb, and the host mounts it at a path.
  • Migrations: Schema changes live in the engine's db/migrate. They are either copied into the host with the engine's install:migrations task or added to the host's migration paths.
  • Gemspec: Each engine declares its dependencies explicitly. The host references it by path in the Gemfile.

None of this enforces a boundary. The autoloader resolves constants globally, so code anywhere in the process can call Billing::Invoice.where(...) and Ruby will not object. An engine packages code. It does not control who depends on it.

Teams use engines anyway because the packaging still pays off in a large codebase:

  • Ownership: A directory maps cleanly to a team.
  • Navigability: A newcomer can understand one domain without reading all of app/models.
  • Change safety: The engine's surface becomes something you can name, review and eventually lock down with tooling.

This guide is for backend and platform teams whose application has outgrown a single flat app/ directory and who need boundaries that are enforced, not only conventional.

bin/rails plugin new engines/billing --mountable

(cd engines/billing && bin/rails generate model Invoice amount_cents:integer)

echo 'gem "billing", path: "engines/billing"' >> Gemfile
bundle install

bin/rails billing:install:migrations
bin/rails db:migrate

bin/rails runner 'puts Billing::Invoice.table_name'
bin/rails runner 'puts Billing::Invoice.where(amount_cents: 0).count'

Creating and wiring a mountable Billing engine gives you a namespace, routes, migrations and a gemspec, but host code can still query Billing::Invoice directly because nothing enforces the boundary.

Who should use engines and Packwerk for a modular monolith?

This approach fits a specific situation. It is a good match when most of the following are true:

  • Several teams work in one Rails codebase. Merge conflicts, unclear code ownership and changes that land in someone else's area are regular problems. Boundaries matter most when the people changing code are not the people who wrote it.
  • The domain has stable, nameable areas. You can point at clusters such as billing, fulfillment or notifications that the business already talks about, and those areas have not been redrawn recently.
  • You want separation without new operational load. You do not need independent deploys or per-component scaling. You want the code organization of separate units while keeping one deploy, one database and in-process calls.
  • Someone owns the tooling. A platform team or a few senior engineers can maintain package.yml files, review dependency changes and keep the CI checks healthy.

It is a poor fit for a single small team that already understands the whole app, for products whose domain model is still changing every few weeks, and for teams whose real problem is deploy independence or scaling. Those cases are covered in more detail in the final section.

How do engines and Packwerk work together?

The two tools operate at different times and do different jobs.

At runtime, engines and Zeitwerk organize and load the code. Bundler requires each engine gem listed in the Gemfile. Each engine is a railtie, so its initializers run during boot, and its app/ subdirectories are added to the autoload paths. Zeitwerk maps file paths to constant names, so engines/billing/app/models/billing/invoice.rb defines Billing::Invoice. Once loaded, every constant is visible to every other piece of code in the process. Runtime does not enforce any boundary.

Before runtime, Packwerk checks the source statically. It does not boot your app's request path or execute your code. In outline:

  1. It finds every package.yml in the repository. Each file marks its directory, minus any nested package directories, as one package.
  2. It parses the Ruby files in each package and collects constant references, such as Billing::Invoice appearing inside a Fulfillment class.
  3. It resolves each reference to the file that would define it, using the same path-to-constant conventions Zeitwerk uses, and from that file to the package that owns it.
  4. If the referencing package has enforce_dependencies: true and the owning package is not listed under dependencies, and the reference is not already recorded in the package's package_todo.yml, Packwerk reports a violation.

Combined, the engine or namespaced directory gives each component a physical home and a namespace. The package.yml declares what that component may depend on. A CI step runs Packwerk on every pull request, which turns the declaration into a rule. Because the check is static, it only sees references written as constants in source. Dynamic lookups need separate review, as covered in the Packwerk section below.

How do you find domain boundaries before moving any files?

Start from the code's actual dependencies, not from the org chart. Teams get reorganized every year or two, but the coupling in your models stays the same until someone changes it.

Build a rough dependency map from four sources:

  • Associations. Every belongs_to, has_many and has_and_belongs_to_many is a hard edge between two models.
  • Callbacks. An after_save on Order that updates Inventory couples the two at runtime, often invisibly.
  • Shared concerns. A module mixed into a dozen models usually means either real shared behavior or a dumping ground. Find out which.
  • Cross-table joins. Search scopes, raw SQL and reporting queries for joins that cross what you think are domain lines.

Look for clusters where models reference each other heavily but have only a few edges leading out. A cluster with that shape is a candidate component. Name it in the business's own language, such as "Billing" or "Fulfillment," not "Core" or "Shared." If the business has no name for the cluster, you probably haven't found a real boundary yet.

When to hold off

Drawing a boundary too early, or along team lines, splits concepts that change together. Each feature then touches several packages, and every call has to cross an interface that didn't need to exist. You pay for the boundaries and get no benefit from them, which leaves you worse off than the original monolith. If your map shows no clear clusters, or the domain is still changing quickly, wait. Delete dead code, untangle callbacks, and redraw the map in a few months.

#!/usr/bin/env bash
set -euo pipefail
mkdir -p tmp/coupling

cat > tmp/coupling/assoc_map.rb <<'RUBY'
Rails.application.eager_load!
ApplicationRecord.descendants.sort_by(&:name).each do |model|
  model.reflect_on_all_associations.each do |assoc|
    # Polymorphic associations have no single target class; record them as such.
    target = assoc.polymorphic? ? "(polymorphic)" : assoc.class_name
    puts "#{model.name} -> #{target} [#{assoc.macro}]"
  end
end
RUBY
bin/rails runner tmp/coupling/assoc_map.rb > tmp/coupling/associations.txt

grep -rnE '^\s*(before|after|around)_(save|create|update|destroy|commit|validation)' \
  app/models > tmp/coupling/callbacks.txt || true

grep -rhoE '^\s*include [A-Z][A-Za-z:]+' app/models \
  | awk '{print $2}' | sort | uniq -c | sort -rn > tmp/coupling/concerns.txt || true

grep -rnE '\.joins\(|\.includes\(|\bJOIN\b' app lib > tmp/coupling/joins.txt || true

awk '{print $3}' tmp/coupling/associations.txt | sort | uniq -c | sort -rn | head -20

A script that collects association edges via ActiveRecord reflection and greps callbacks, concern usage and joins, producing raw edge lists you can cluster by hand before naming components or moving any files.

Should you use in-repo engines or plain namespaced directories?

Neither layout enforces boundaries, so choose based on how much ceremony you need. A path: gem in components/ gives you a gemspec that declares dependencies, a test/dummy app for isolated tests, and an engine class with its own routes and initializers. It also brings costs. Migrations must be copied into the host with railties:install:migrations, or the engine must append its db/migrate path to the host's paths. Every component's gemspec must also be kept in sync with the root Gemfile.lock.

Namespaced directories avoid all of that. You add a directory such as components/ to the autoloader so that components/billing/ maps to the Billing namespace, and the host app owns routes, migrations and config.

That ceremony is worth it in three cases: when a component needs separately mounted routes, ships its own UI, or is reusable across applications.

Loading behaves differently across environments. In development, Zeitwerk loads constants lazily, so a misnamed file or an undeclared cross-component reference can work by accident. Test usually behaves the same unless you enable eager loading in CI. Production eager-loads everything at boot, which is where these errors finally surface. Run bin/rails zeitwerk:check in CI to catch them earlier. Engine initializers run in railtie load order, which follows Bundler's require order, so an initializer that depends on another engine's setup can break when someone reorders the Gemfile.

Option Boundary enforcement Boilerplate Best fit
Do nothing None None Unclear domains
Namespaced dirs Via Packwerk Low Most monoliths
In-repo engines Via Packwerk, plus gemspec deps Medium–high Mountable UI, reuse
Microservices Network Very high Independent scaling and deploys
gem "billing", path: "components/billing"

module Billing
  class Engine < ::Rails::Engine
    isolate_namespace Billing  # own routes, helpers and table prefix

    # Append this engine's migrations to the host's path instead of copying
    # them with railties:install:migrations. Skip this when the engine's
    # own test/dummy app is the one booting.
    initializer "billing.append_migrations" do |app|
      unless app.root.to_s.start_with?(root.to_s)
        config.paths["db/migrate"].expanded.each do |path|
          app.config.paths["db/migrate"] << path
        end
      end
    end
  end
end

mount Billing::Engine, at: "/billing"

config.eager_load_paths << Rails.root.join("components")

The same Billing component wired up both ways: as a path-gem engine with mounted routes and appended migrations, and as a namespaced directory added to the autoloader, with a zeitwerk:check CI step that applies to both.

How does Packwerk enforce dependency rules between components?

Each component gets a package.yml at its root. Setting enforce_dependencies: true and listing the packages it may reference under dependencies turns the folder into a declared unit. Packwerk parses Ruby files, resolves constant references the way Zeitwerk would load them, and reports any reference to a package that is not declared. Run the check in CI on every pull request so the rules apply to all code, not only to engineers who remember them.

On day one, a large app will have hundreds of violations. Packwerk can record them in a per-package package_todo.yml. CI then fails only on new violations, so teams can keep shipping while the existing violations are paid down. The risk is that this file becomes a permanent exemption list. These policies prevent that:

  • Each package has a named owning team, and that team owns its package_todo.yml.
  • Regenerating package_todo.yml can only remove entries. Additions need sign-off from the owning team.
  • Track entry counts per package and review the trend each sprint.

Treat every new line under dependencies as a design decision that needs review, not a fix to make CI pass. Packwerk's validation step rejects cyclic declared dependencies, which keeps the graph acyclic. Render the graph regularly so everyone can see its shape.

A green check does not prove a component is isolated. Static analysis cannot see constantize, send with dynamic names, const_get, metaprogrammed methods, or polymorphic *_type columns that store class names as strings. Grep for these patterns and review them by hand.

#!/usr/bin/env bash
set -euo pipefail

bin/packwerk validate

bin/packwerk check

git fetch --quiet origin main
added=$(git diff --numstat origin/main...HEAD -- '*package_todo.yml' \
  | awk '{ sum += $1 } END { print sum + 0 }')
if [ "$added" -gt 0 ]; then
  echo "package_todo.yml gained $added line(s); owning team must approve." >&2
  exit 1
fi

echo "Dynamic references for manual review:"
grep -rnE 'constantize|const_get|public_send\(|\.send\(|polymorphic: true' \
  app packs --include='*.rb' || true

A CI script that validates the package graph, fails on new Packwerk violations, blocks growth of package_todo.yml files, and lists dynamic constant lookups that static analysis cannot detect.

How should components talk to each other without sharing ActiveRecord models?

Once Packwerk and the manual review have surfaced the cross-component references, the next step is replacing them with a deliberate public API. Each component exposes a small facade or a set of service objects that accept IDs and return plain data, such as structs, hashes or value objects, never ActiveRecord instances. A returned model leaks its associations, its callbacks and the ability to call save, so the boundary disappears the moment a caller touches it.

The hardest coupling points need specific treatment:

Coupling point Replacement Cost
Cross-domain belongs_to/has_many Store the ID; resolve it through the owning component's facade Facades that look up records one at a time cause N+1 queries unless you add batch methods
Foreign keys across components Keep the database constraint, drop the Ruby association The schema still couples the components, so deletes need coordination
Polymorphic associations Store a stable string key instead of a class name Requires a data migration and a mapping layer
Callbacks with side effects elsewhere Publish a domain event after commit Subscribers see stale state until they run, which creates eventual-consistency bugs
Reporting reads across domains Read-only query objects owned by one component Duplicates some query logic

All of this adds code and indirection. Shared tables also mean that logical boundaries are not data boundaries. Packwerk cannot stop two components from writing the same rows, and wrapping calls to several components in one transaction block stays easy and tempting. Treat each cross-component transaction as a design decision you record and review, not a convenience.

What is a safe, incremental sequence for extracting components?

Extraction is safer when every step is a small, separately deployable change.

Steps

  1. Pick a leaf domain. Choose one that many parts of the app could call but that calls little else, such as notifications, exports or billing address validation. Few inbound dependencies means few call sites to update, and few outbound ones means the new package will rarely need to depend on code that has not been extracted yet.
  2. Move code behind a namespace first. Relocate classes into a Notifications:: module and update callers, without changing behavior. Ship this on its own. A rename-only diff is easy to review and easy to revert, and Zeitwerk will raise on any constant that does not match its file path.
  3. Add the package boundary. Create the package.yml with dependency enforcement on, then record the existing violations in the package's package_todo.yml instead of fixing them all at once. CI then blocks new violations while the old ones remain visible.
  4. Pay down the recorded violations. Replace each entry in package_todo.yml with a call to the component's public API. Every deleted entry is its own small merge.
  5. Repeat with the next domain. Prefer one that depends only on packages you have already extracted.

Testing each component

Run a component's specs from its own directory with its own helper, not the app-wide spec_helper. The app-wide helper loads every factory and support file, which hides dependencies the component never declared.

For engines, the generated dummy app gives you a minimal host to boot against. Boot that dummy app with eager loading turned on. If the engine references a parent-app constant at load time, for example as a superclass, an included module or in a class-level macro, loading fails right away instead of surfacing later in production. References inside method bodies only fail when that code runs, so the component's own specs still need to exercise them.

What are the alternatives to engines with Packwerk?

Engines plus Packwerk is one point on a range. The main alternatives, from least to most separation:

  • Leave the flat app/ layout and rely on conventions. Code review, naming conventions and a written architecture guide cost almost nothing to start. They also depend entirely on reviewers noticing cross-domain references, which gets harder as the codebase and the number of reviewers grow. This is the right choice while domains are still unclear.
  • Namespaced directories without Packwerk. Moving code into Billing:: and Fulfillment:: namespaces improves navigation and ownership mapping. Without a static check, though, nothing stops new cross-namespace references, so the layout erodes unless reviewers catch them.
  • Engines without Packwerk. You get gemspecs, isolated routes, migrations and a dummy app for testing. Gemspec dependencies describe gem-level requirements, but the autoloader still makes every constant reachable, so this gives packaging without enforcement.
  • Custom static checks. Some teams write their own CI scripts or linter rules that flag references from one namespace to another. This can work for a few simple rules, but you then own the constant-resolution logic, the exemption mechanism and the maintenance that Packwerk already provides.
  • Separate gems in separate repositories. Moving a component into its own repository with versioned releases creates a hard boundary at the dependency level. It also adds release coordination: a change that spans the component and the host needs a gem release and a version bump before the host can use it.
  • Extracted services. A component becomes its own deployable with its own database, reached over the network. This is the only option here that gives independent deploys and scaling, and it brings network failures, distributed data consistency and API versioning with it. The comparison table in the final section covers the trade-offs.

The engines-or-directories table earlier in this guide summarizes the in-repo options. A modular monolith with Packwerk sits between conventions and services: stronger than conventions because CI enforces it, and cheaper to change than services because moving a boundary means moving code and editing package.yml, not migrating data.

How can a modular monolith save engineering time?

The time savings come from reducing how much of the codebase any one person or change has to deal with. The main sources:

  • Shorter investigation before a change. When a component exposes a small public API and declares its dependencies, an engineer can see from package.yml which packages a change could affect, instead of searching the whole app for callers.
  • Narrower test runs. A component with its own spec helper and declared dependencies can run its own suite during development without loading the entire app's support files. In CI, you can decide which suites to run based on which packages a pull request touched and their declared dependents. You still need a full run before merge or deploy to catch dynamic references Packwerk cannot see.
  • Earlier detection of unwanted coupling. Packwerk flags a new cross-component reference in the pull request that introduces it. Without the check, the same coupling is often discovered months later, during a refactor, when removing it means touching many call sites.
  • Clearer review routing. An owner entry in each package's metadata tells authors whose approval a change needs. Pull requests that add a dependency go to the owning team instead of waiting for someone to work out who is responsible.
  • Faster onboarding. A new engineer can learn one component, its public API and its dependencies, and start contributing there without first building a mental model of every model in the app.
  • Cheaper refactors inside a component. Code behind the facade can change freely as long as the public API holds, because Packwerk confirms that no other package references the internals directly.

These savings depend on the boundaries matching how the code actually changes. If most features cross several packages, the facades and dependency reviews add work instead of removing it. The next section puts rough numbers on the trade-off.

When is a modular monolith worth the cost, and when should you avoid it?

The cost lands first. Each component needs its own namespace, a package.yml or gemspec, a public API module and a dummy host to boot against. The first Packwerk run on an existing app usually reports a long list of violations, and each one must be fixed or recorded and paid down later. Every cross-component call also goes through a facade or event rather than a direct model reference, which adds a hop when you trace behaviour.

The payoff comes from limiting what any single change can touch. Ownership becomes explicit. A change inside one package can only break its declared dependents. New engineers can learn one component instead of the whole app. CI can run one component's specs without the rest.

Illustrative estimate (assumed numbers, not a benchmark)

Months to break even = upfront hours ÷ (engineers × hours saved per engineer per month − ongoing overhead hours per month)

Assume 400 upfront hours, 2 hours saved per engineer per month, and 10 hours of monthly overhead:

  • 20 engineers: 400 ÷ (40 − 10) ≈ 13 months.
  • 5 engineers: 400 ÷ (10 − 10) never breaks even.

When to avoid it

  • Small apps. One team can already hold the whole codebase in their heads, so there is little time to save.
  • Unclear domains. Boundaries drawn too early harden the wrong seams.
  • Teams expecting independent deploys. Engines do not provide them.

A modular monolith still has one deploy, one runtime and one scaling profile. A slow migration or a memory leak in one component affects all of them.

Concern Modular monolith Extracted services
Deploy Single pipeline Per service
Cross-boundary call In-process method Network call that can fail
Data consistency Shared database transactions Sagas or eventual consistency
Scaling Whole app together Per service
Cost of a wrong boundary Move code and update package.yml Migrate data and version APIs

Extract services when components truly need separate deploys or scaling. Until then, a modular monolith lets you test your boundaries cheaply first.

How OneEnv can help

Disclosure: OneEnv is the product behind this blog.

OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.

Applied to rails engines modular monolith, this is where it helps:

Saves time

  • Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
  • One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
  • Reviewers see the exact diff and the list of affected services up front, so approval is a decision rather than an investigation.

Saves cost

  • Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
  • Less duplicated configuration to maintain: one shared definition inherited by many services.
  • Per-service approve/reject means a bad shared value can be refused where it would break something, before it is live.
  • OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.

These are qualitative benefits, not measured results — how much you save depends on how many services share the value.

Want to try it? Start at oneenv.io.