What does code ownership in a monolith actually mean?

Code ownership in a monolith means a named team is accountable for a module across its whole lifecycle, not just at merge time. In practice that accountability breaks down into four responsibilities:

Responsibility What the owning team does What breaks without it
Approving changes Reviews and signs off on pull requests touching the module Changes land from people who don't know the invariants
Triage and paging Receives bug reports and alerts, decides severity Incidents bounce between teams while users wait
Public interface Decides what other modules may call and how it evolves Callers reach into internals, so every refactor breaks someone
Tech debt Schedules cleanup, upgrades, and deletions Debt accumulates in code nobody feels entitled to touch

Most teams stop at the first row because review routing is the easiest piece to automate. That leaves ownership incomplete. A team that approves every pull request but never gets paged has no feedback on whether its approvals were good. A team that gets paged but can't refuse a new dependency on its internals is responsible for outcomes it can't control.

The core idea is to make the codebase structure and the org chart agree without splitting the deployable. You keep one build, one release, and one process, but each package has an owner whose responsibilities match the table above.

This guide is for monoliths shared by several teams where friction already shows up: reviews wait on the wrong people, incidents start with "whose code is this?", or an interface change in one area quietly breaks another. If one team owns the whole codebase, you don't need any of this yet.

How do you draw module boundaries that match how teams change code?

The unit of ownership should be a module: a package with a small public surface, such as an api subpackage or a facade class, and internals that nothing outside the module imports. Assigning owners to individual files or scattered directories fails because changes don't respect those lines. A feature touches a handler, a service, a repository, and a migration together. If those pieces have different owners, every change needs several approvals, and no team can refactor its own internals without asking permission. A module gives the owning team freedom inside its boundary and a stable contract at the edge. Only the contract needs negotiation with other teams.

Draw boundaries around how work actually flows. Stream-aligned teams own domain modules that map to a business capability. A platform team owns shared infrastructure that domain teams consume but rarely change, such as logging, authentication, and persistence helpers. If two areas change together in most pull requests, they are one module in practice. Give them to one team instead of splitting ownership across a seam that keeps getting crossed.

Module Owner May depend on
orders Checkout team catalog.api, platform.*
catalog Catalog team platform.*
billing Payments team orders.api, platform.*
platform (logging, auth, persistence) Platform team nothing above it

Dependencies point inward and downward. Domain modules call each other only through api packages, and platform never imports a domain module. When a cycle appears, the boundary is drawn in the wrong place.

+------------------+     +------------------+     +------------------+
| billing          |     | orders           |     | catalog          |
| Payments team    |     | Checkout team    |     | Catalog team     |
|------------------|     |------------------|     |------------------|
| api (public)     |  +->| api (public)     |  +->| api (public)     |
|------------------|  |  |------------------|  |  |------------------|
| internal         |--+  | internal         |--+  | internal         |
| (private)        |     | (private)        |     | (private)        |
+--------+---------+     +--------+---------+     +--------+---------+
         |                        |                        |
         v                        v                        v
+--------------------------------------------------------------------+
| platform -- Platform team                                          |
|   logging      auth      persistence helpers                       |
|   depends on nothing above; never imports a domain module          |
+--------------------------------------------------------------------+

A modular monolith where each team owns a whole module. Domain modules reach each other only through public api packages, and every module depends downward on the platform team's shared infrastructure, which imports no domain module.

How do you write a CODEOWNERS file that assigns teams correctly?

Each line in CODEOWNERS maps a path pattern to one or more owners. Point every pattern at a team handle (for example @acme/billing-team), never at individuals. People change roles and go on leave. A team handle survives reorganizations, and you can update its membership without touching the file.

Structure the file in the same order as your module layout:

  • Catch-all first. Start with a * line assigned to the platform or architecture group. Any path that no other rule covers still gets a reviewer.
  • Domain modules next. Add one block per module, such as /src/billing/ and /src/orders/, each owned by the team that ships changes there.
  • The file itself last. Assign CODEOWNERS to the platform group. A team should not be able to reassign ownership of another team's module in the same pull request that changes it.

Order matters because the last matching pattern wins. Earlier matches are not merged with later ones. They are replaced. This is how precedence mistakes hide. Suppose someone moves the * line to the bottom "for tidiness". Now every file in the repository is owned by the platform group. Domain teams stop getting review requests, and nothing reports an error.

A narrower version of the same problem happens when /src/billing/ appears below /src/billing/tax/. The tax team silently loses ownership of its subdirectory. Add a check that compares expected owners against a few sample paths whenever the file changes.

Finally, CODEOWNERS on its own only requests reviews. It blocks nothing until branch protection on your main branch requires code owner approval.

# .github/CODEOWNERS
# Rule: the LAST matching pattern wins. Earlier matches are replaced, not merged.
# Order from broadest to most specific.

# 1. Catch-all: any path not matched below still gets a reviewer.
*                       @acme/platform-team

# 2. Domain modules, one block per module, owned by the shipping team.
/src/billing/           @acme/billing-team
/src/orders/            @acme/orders-team
/src/inventory/         @acme/inventory-team

# Subdirectory overrides go AFTER their parent so they win.
/src/billing/tax/       @acme/tax-team

# Shared infrastructure stays with the platform group.
/src/shared/            @acme/platform-team

# 3. The ownership file itself: ownership changes need platform approval.
/.github/CODEOWNERS     @acme/platform-team

# ------------------------------------------------------------------
# WRONG ORDER (do not do this). No error is reported for either mistake:
#
#   /src/billing/tax/   @acme/tax-team
#   /src/billing/       @acme/billing-team   <- matches tax/ too and wins;
#                                               tax team gets no requests
#
#   /src/orders/        @acme/orders-team
#   *                   @acme/platform-team  <- matches everything and wins;
#                                               every domain rule is overridden
# ------------------------------------------------------------------
#
# This file only REQUESTS reviews. To block merges, enable
# "Require review from Code Owners" in branch protection for main.

A CODEOWNERS file ordered from catch-all to most specific, with team handles only, the file itself owned by the platform group, and commented examples of ordering mistakes that silently reassign ownership.

Why isn't CODEOWNERS enough, and how do you enforce dependency rules?

Even with review enforced, CODEOWNERS answers only "who must approve this diff?" It says nothing about what the diff does. A developer on the Billing team can add an import of orders.internal.PricingCalculator inside billing/, and Orders never sees the pull request because no Orders file changed. Coupling builds up in exactly the places the owning team cannot see. You need a second mechanism that checks the dependency graph.

Mechanism Where it fails Strength Limitation
Language visibility (Java package-private or JPMS exports, Kotlin/C# internal, Go internal/ directories) Compile time Violations can't build at all Bound to language units, which rarely match team boundaries exactly
Architecture tests or lint rules in CI Test or lint stage Express any rule about modules, layers, or teams Only as good as the rule set, and can be suppressed

Use visibility wherever it fits. The compiler is the cheapest enforcer you have. For boundaries the language can't express, write an architecture test. Conceptually, it loads every class or file, maps each to its owning module, and then asserts one rule: code in module A may depend on module B only through B's declared public interface package. Any import that reaches into B's internals fails the build, and the error names both modules.

The ongoing cost is rule fatigue. If you encode dozens of fine-grained layer rules, every refactor trips one. Teams then start adding blanket suppressions or moving code into "shared" just to get green. Keep rules coarse, around one per module boundary. Require an owner's approval for every exception, and track the exception count over time.

import com.tngtech.archunit.junit.AnalyzeClasses;
import com.tngtech.archunit.junit.ArchTest;
import com.tngtech.archunit.lang.ArchRule;

import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses;

// Runs in CI as a normal JUnit 5 test. A violation fails the build.
@AnalyzeClasses(packages = "com.example")
class ModuleBoundaryTest {

    // Convention: each module is com.example.<module>.
    // Its public interface lives in com.example.<module>.api.
    // Everything under com.example.<module>.internal is private to the owning team.
    private static ArchRule internalsStayInside(String module) {
        String base = "com.example." + module;
        return noClasses()
                .that().resideOutsideOfPackage(base + "..")
                .should().dependOnClassesThat().resideInAPackage(base + ".internal..")
                .because(module + " internals are private; depend on " + base + ".api instead");
    }

    // Keep rules coarse: one per module boundary, not one per layer or class.
    @ArchTest
    static final ArchRule orders = internalsStayInside("orders");

    @ArchTest
    static final ArchRule billing = internalsStayInside("billing");

    @ArchTest
    static final ArchRule inventory = internalsStayInside("inventory");

    // Example of what this catches: a class in com.example.billing importing
    // com.example.orders.internal.PricingCalculator fails the orders rule,
    // and the failure message names both the offending class and the target.
}

A conceptual ArchUnit test that fails the CI build when any module imports another module's internal package instead of going through its public api package, with one coarse rule per module boundary.

Who owns shared kernels, database schemas, and contested code?

The hard cases are the code nobody naturally owns. Leaving them unassigned means anyone can change them, and in practice nobody maintains them.

Shared kernels

Common domain types such as Money, CustomerId, or event envelopes need a single named owning team, even if every team imports them. That team does not write every change. It keeps the kernel small and rejects additions that only one module needs. Make contributions cheap: any team can open a change, and the owner commits to reviewing within a stated window. Without that commitment, teams copy types into their own modules to avoid waiting, and the kernel stops being shared.

Database schemas

A single database does not mean shared tables. Give each table, or each schema if your database supports namespacing, exactly one owning module. Only that module writes to it, and its team approves migrations touching it. Put migrations in per-owner directories so CODEOWNERS can route reviews. Other modules read through the owner's API or an agreed view, not with ad hoc joins.

Cross-cutting changes

A framework upgrade or a type rename can touch every module and need a dozen approvals. You have two options:

  • Platform bypass group with approval rights everywhere. It is fast, but it weakens the guarantee that owners see every change to their code.
  • Bulk-change process: announce the change, split it per module, let owners approve their slice, and set a deadline after which the change merges. It is slower, but owners keep visibility.

Prefer the bulk process. Reserve the bypass for mechanical, tool-generated changes, and audit its use.

How do you migrate a tangled codebase to module ownership?

Start with an inventory: list every top-level directory and package, and note which have no obvious owner. That list is your migration backlog.

Next, let history tell you who actually changes what. Run git shortlog -sne --since="12 months ago" -- path/ for each path, or git log --since="12 months ago" --format='%ae' -- path/ | sort | uniq -c for raw counts. Map authors to teams. Paths where one team makes most changes get that team as provisional owner. Paths split across several teams are your contested code. Handle them with the rules from the previous section rather than forcing a choice now.

Turn on dependency rules in warn-only mode, and record every existing violation in an allowlist. CI then fails only on new violations, so you stop the bleeding without a big-bang refactor. Shrink the allowlist on a schedule, for example by a few entries per sprint, and never let it grow.

To keep ownership from rotting:

  • Keep the ownership map versioned in the repo.
  • Run a periodic check that flags owners who have left or have not reviewed anything recently.
  • Add a CI check that fails when a new top-level path has no owner.

Automatic routing saves time because reviews and bugs stop waiting for someone to find the right team. Illustrative estimate: assume 200 PRs and bug reports a month, each losing 15 minutes to manual routing. That comes to 50 engineer-hours a month spent finding owners.

#!/usr/bin/env bash
# Ownership discovery and an unowned-path check for a monolith.
# Run from the repository root. Assumes a CODEOWNERS-style file
# with one '/dir/ @team' line per top-level directory.
set -euo pipefail

SINCE="12 months ago"
OWNERS_FILE=".github/CODEOWNERS"
missing=0

# Only tracked top-level directories, so build output and local
# clutter do not show up in the inventory.
for dir in $(git ls-tree -d --name-only HEAD); do
  # Count non-merge commits touching this path in the window.
  total=$(git log --no-merges --since="$SINCE" --format='%H' -- "$dir" | wc -l)
  echo "== $dir ($total commits since $SINCE)"

  # Top three author emails. Map these to teams by hand: one dominant
  # team means a provisional owner, several means contested code.
  git log --no-merges --since="$SINCE" --format='%ae' -- "$dir" \
    | sort | uniq -c | sort -rn | head -n 3

  # Flag any top-level path that has no exact '/dir/' owner entry.
  if ! awk -v d="/$dir/" '$1 == d { found = 1 } END { exit !found }' "$OWNERS_FILE"; then
    echo "   !! no owner entry for /$dir/ in $OWNERS_FILE"
    missing=1
  fi
done

# A non-zero exit lets CI fail when a new top-level path has no owner.
exit "$missing"

A bash script that uses git history to show who changed each top-level directory over the past 12 months and exits non-zero when any directory has no ownership entry, so it works both for the inventory step and as a CI check.

When should you avoid strict monolith ownership, and what are the alternatives?

Strict ownership has costs, and they land hardest on small organizations. If a module's required reviewer is a two-person team that is also on call, every cross-cutting change waits for them. Boundaries drawn from the current org chart become wrong after the next reorg. If nobody redraws them, the codebase keeps the old structure, which is Conway's law working against you. Silos form: teams stop reading each other's code and write their own date helpers and retry wrappers rather than ask. A team can also be named owner of a module it lacks the time or knowledge to maintain, which is worse than no owner because it hides the gap. And clean package boundaries do not remove the shared runtime, build, deploy pipeline, and database. One team's memory leak or slow migration still affects everyone.

Approach Fits when Main cost
Collective ownership One or two teams, high trust, broad context No clear escalation path as headcount grows
Review-only CODEOWNERS (optional reviewers) You want routing and visibility without blocking merges Reviews get skipped under deadline pressure
Full modular-monolith enforcement Several stable teams, clear domains, CI-checked dependency rules Rule maintenance and exception handling
Extracting services A module needs its own scaling, release cadence, or failure isolation Network calls, distributed data, operational overhead

Watch three friction signals to decide whether to move along this table. The first is how long PRs wait for cross-team review. The second is the share of changes that touch many modules, which suggests the boundaries are wrong. The third is how often teams request exceptions to dependency rules. If any of these keeps rising, revisit the boundaries before you add more enforcement.

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 code ownership 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.