What is a module dependency cycle, and why does it matter in a modular monolith?

A module dependency cycle exists when following "depends on" edges from one module eventually leads back to it. The direct case, where orders imports billing and billing imports orders, tends to get caught in review because both halves often appear in the same diff. The transitive case usually slips through. Each pull request adds one reasonable-looking import, and no reviewer sees the whole loop:

orders ──▶ billing ──▶ notifications ──▶ orders ✂ cut here

Here notifications reaching back into orders, perhaps to look up a customer's display name, closes the loop. Removing that single edge turns the cycle into a straight chain.

Cycles matter because they merge modules into one unit in everything except name:

  • Extraction: You can't move billing into its own service or library while it still needs orders, which needs billing. To pull out any one of them, you have to pull out all three.
  • Testing: A test for notifications has to load orders and therefore billing. A unit test of one module becomes a test of the whole cluster.
  • Reasoning: A change inside the cycle can affect any module in it. Ownership and impact analysis stop working.

The approach in this article is that cycle detection only pays off once module boundaries are written down explicitly, as package conventions or a declared list of slices. If nobody has said where orders ends, a tool has nothing to measure against, and "cycle" has no precise meaning.

  BEFORE: transitive cycle, one edge added per pull request

  ┌──────────┐      ┌──────────┐      ┌───────────────┐
  │  orders  │─────▶│ billing  │─────▶│ notifications │
  └──────────┘      └──────────┘      └───────┬───────┘
       ▲                                      │
       │                                      │
       └──────────────────╳───────────────────┘
                          ╳ = cut this edge
              (notifications ──▶ orders, e.g. display name)

  AFTER: edge removed, the cycle becomes a straight chain

  ┌──────────┐      ┌──────────┐      ┌───────────────┐
  │  orders  │─────▶│ billing  │─────▶│ notifications │
  └──────────┘      └──────────┘      └───────────────┘

A three-module transitive cycle (orders → billing → notifications → orders) and the single back-edge from notifications to orders whose removal turns it into an acyclic chain.

Who should use ArchUnit cycle checks, and when are they not worth it?

When should you use it?

The check pays off most for backend and platform teams shipping a single deployable whose code is organized into feature packages such as orders, billing and inventory. In that setup, the compiler accepts any import between packages, so nothing stops a cycle from forming one convenient call at a time. Two moments make adoption worthwhile. The first is before extracting a service, because a cycle through billing means it cannot leave without taking part of orders with it. The second is when a growing codebase starts showing tangled modules, such as changes that ripple across features or tests that need half the application to start.

Situation What ArchUnit adds
Single deployable, feature packages Module-level cycle detection the build doesn't provide
Separate Gradle or Maven modules Package-level cycles inside each module, plus allowed-dependency rules
Very small codebase Little; the rules cost more to maintain than they catch

In short, use it when three things are true: the code runs on the JVM, module boundaries are expressed as packages rather than as separate build modules, and more than one team or a growing number of contributors touch those modules.

When should you avoid it?

If modules are already separate Gradle or Maven modules, the build tool refuses module-level cycles, so ArchUnit's value shifts to cycles between packages inside a module and to rules about which modules may depend on which. On a small codebase where everyone can still hold the whole design in their head, keeping slice definitions current is overhead with little return. It is also a poor fit when nobody has agreed where module boundaries are. Writing a slice pattern before that agreement exists encodes an arbitrary package layout as if it were architecture.

The check also has a hard limit. ArchUnit reads bytecode, so it cannot see dependencies created through reflection, string-based bean lookup, configuration files or runtime wiring by a DI container. A clean report rules out compile-time cycles only. It does not rule out runtime coupling. If most of your coupling flows through those mechanisms, a bytecode check will give you false confidence.

How does ArchUnit detect cycles between slices?

ArchUnit works on bytecode, not source. It imports compiled classes, records every dependency it can resolve (field types, method signatures, calls, inheritance, annotations), groups classes into slices, and searches the resulting slice-to-slice graph for cycles.

How it works, step by step

  1. Import. ArchUnit reads the compiled .class files from the locations that match the configured packages. With the JUnit 5 integration, @AnalyzeClasses drives this import. Without it, you can call the class importer directly in an ordinary test.
  2. Resolve dependencies. For each imported class, it records the classes it depends on: superclasses and interfaces, field types, parameter and return types, method calls, field accesses, annotations and type parameters.
  3. Group into slices. The slice pattern assigns each class to a slice based on its package. Classes the pattern does not match are not part of any slice.
  4. Build the slice graph. Class-level dependencies that cross from one slice to another are collapsed into a single edge between those slices. Each edge keeps the list of class dependencies behind it.
  5. Search for cycles. ArchUnit searches the slice graph for closed paths and turns each one into a rule violation.
  6. Report. The test fails like any other failed assertion. The message lists each cycle and the class-level dependencies behind every edge, which is what you use to decide where to cut.

Because all of this runs as a normal unit test, it needs no separate tool, server or build plugin. It runs wherever your tests run.

A minimal test uses the JUnit 5 integration. @AnalyzeClasses names the root package and passes ImportOption.DoNotIncludeTests and ImportOption.DoNotIncludeJars. Excluding tests matters because test fixtures often reach across modules and would create cycles that never exist in production code. Excluding jars keeps third-party code out of the graph and shortens import time. A field annotated with @ArchTest then holds the rule: slices().matching("com.example.(*)..").should().beFreeOfCycles(). The capture group (*) names the slice, so com.example.billing.api and com.example.billing.internal both belong to the billing slice.

Choosing slice granularity

The pattern should match the packages your team treats as modules. If it is too coarse, such as one slice per application layer, a billing to orders to billing loop sits inside a single slice and never appears in the report. If it is too fine, such as com.example.(**), every subpackage becomes a slice. You then get dozens of cycles between helper packages that nobody considers a boundary, and engineers learn to ignore the report.

Guarding against silent passes

If someone renames com.example and the pattern matches no classes, the rule has nothing to check and can pass. Call allowEmptyShould(false) on the rule explicitly instead of relying on the configured default. This guard only catches a pattern that matches nothing at all. A rename that removes just one module still leaves other slices matched, so the rule keeps passing. To catch that case, add a test that asserts the expected set of slice names exists.

import com.tngtech.archunit.core.importer.ImportOption;
import com.tngtech.archunit.junit.AnalyzeClasses;
import com.tngtech.archunit.junit.ArchTest;
import com.tngtech.archunit.lang.ArchRule;

import static com.tngtech.archunit.library.dependencies.SlicesRuleDefinition.slices;

// Import only production bytecode under the root package.
// Test fixtures often reach across modules and would add cycles
// that do not exist in production; jars keep third-party code out
// of the graph and shorten import time.
@AnalyzeClasses(
        packages = "com.example",
        importOptions = {
                ImportOption.DoNotIncludeTests.class,
                ImportOption.DoNotIncludeJars.class
        })
class ModuleCycleTest {

    // One slice per top-level module package: (*) captures the slice name,
    // so com.example.billing.api and com.example.billing.internal
    // both belong to the "billing" slice.
    @ArchTest
    static final ArchRule modulesAreFreeOfCycles =
            slices().matching("com.example.(*)..")
                    .should().beFreeOfCycles()
                    // Fail instead of passing silently if a package rename
                    // leaves the pattern matching no classes at all.
                    // This does not catch a single module disappearing.
                    .allowEmptyShould(false);
}

A JUnit 5 ArchUnit test that excludes test classes and jars from the import, builds one slice per top-level module package, checks the slices for cycles, and fails if the slice pattern matches nothing.

What are the alternatives to ArchUnit for preventing cycles?

ArchUnit is one way to enforce module boundaries on the JVM. These are the main alternatives and how they compare:

  • Separate build modules. Split each feature into its own Gradle or Maven module. The build tool rejects cycles between modules, so the guarantee is structural rather than test-based. The cost is more build configuration, slower restructuring, and boundaries that are expensive to move while the design is still settling. It also says nothing about cycles between packages inside one module.
  • Java Platform Module System (JPMS). Declaring modules with module-info.java gives compile-time enforcement: the module graph cannot contain cycles, and only exported packages are accessible to other modules. It is strict and built into the language, but adopting it in an existing application can be disruptive, especially when libraries or frameworks rely on reflective access.
  • jdeps. The JDK ships jdeps, which analyzes class files and reports package- and module-level dependencies. It is useful for one-off exploration of an unfamiliar codebase. On its own it does not give you a failing assertion in your test suite, so you would need scripting around it to enforce rules in CI.
  • Code review and conventions. Agreeing that modules only call each other's api package, and checking it in review, costs nothing to set up. As this article's first section describes, it misses transitive cycles because no single diff shows the whole loop.

ArchUnit sits between these. It is stricter than review, easier to adopt incrementally than build modules or JPMS, and produces actionable failures rather than reports. A common path is to start with ArchUnit while boundaries are still moving, then promote stable modules to separate build modules once their boundaries have held for a while.

How do you read ArchUnit's cycle report and pick the edge to cut?

When a cycle check fails, ArchUnit lists each cycle as a path through slices, followed by the class-level dependencies behind every edge. The sample below is a representative illustration, not verbatim tool output:

Illustrative sample: Cycle detected: billing → orders → billing Dependencies of billing → orders: – InvoiceService.create() calls OrderRepository.findById() – Invoice has field of type OrderId Dependencies of orders → billing: – Order has field of type Money – OrderService calls Money.add() – OrderLine extends PricedItem – OrderDto is annotated with @BillingAudited – Discount method signature uses generic type List<TaxRule>

Count the lines under each edge. Here, billing → orders has two dependencies and orders → billing has five. The shorter list is usually the cheaper cut, though cost also depends on what kind of dependency it is. A field type that appears in a persisted entity costs more to move than one service call.

Read the dependencies before you edit anything. In this sample, Money and PricedItem sit in billing, but orders depends on them heavily. That suggests they belong in a shared kernel or in orders, so cutting the shortest edge would leave the misplaced concept where it is. Treat each cycle as a question about which module owns a concept. Adding an exclusion only hides that question.

Check any edge you don't expect before you choose a fix:

  • Annotations: a single annotation can create a dependency.
  • Generic parameters: a type inside a signature, such as List<TaxRule>, counts as a dependency.
  • Compiler-inlined constants: these are the reverse case. The Java compiler copies them into the calling class's bytecode, so ArchUnit never sees the dependency. The source still imports the constant, even though the report shows no edge.
package com.example.architecture;

import com.tngtech.archunit.core.importer.ImportOption;
import com.tngtech.archunit.junit.AnalyzeClasses;
import com.tngtech.archunit.junit.ArchTest;
import com.tngtech.archunit.lang.ArchRule;

import static com.tngtech.archunit.library.dependencies.SlicesRuleDefinition.slices;

// Analyze production classes only, so test helpers do not add edges
// that do not exist at runtime.
@AnalyzeClasses(
        packages = "com.example",
        importOptions = ImportOption.DoNotIncludeTests.class)
class ModuleCycleTest {

    // Each top-level package under com.example (billing, orders, ...)
    // becomes one slice. A failure prints every cycle between slices and
    // lists the class-level dependencies behind each edge. Count those
    // lines per edge to compare how expensive each edge is to cut.
    //
    // ArchUnit caps how many dependencies it reports per edge. If an edge
    // looks truncated, raise the cap in src/test/resources/archunit.properties:
    //   cycles.maxNumberOfDependenciesPerEdge=100
    //
    // No ignoreDependency(...) calls: an exclusion hides the question of
    // which module should own the concept, so fix the code instead.
    @ArchTest
    static final ArchRule modules_should_be_free_of_cycles =
            slices()
                    .matching("com.example.(*)..")
                    .namingSlices("$1")
                    .should()
                    .beFreeOfCycles();
}

A JUnit 5 ArchUnit test that treats each top-level package as a module and fails with a per-edge list of class dependencies whenever modules form a cycle.

How do you add the rule to an existing codebase without blocking every build?

Running the cycle rule against a large codebase for the first time usually produces a long list of violations. If the rule fails the build, someone has to fix every existing cycle before anyone can merge, so the check either gets postponed or deleted. ArchUnit avoids this with FreezingArchRule.freeze(...). Wrap your slice rule in it, and the first run records every current violation in a violation store. Later runs fail only on violations that are not in the store. Existing cycles are tolerated, and new cycles fail the build.

Configure the store in archunit.properties:

  • freeze.store.default.path sets the directory for the store. Point it at a location inside the repository and commit its contents. The store is the agreed baseline, so changes to it should go through code review like any other change.
  • freeze.store.default.allowStoreCreation is off by default. Enable it once to generate the initial store, then turn it off. Otherwise a misconfigured path in CI silently creates an empty baseline and the check passes.
  • freeze.refreeze records all current violations as accepted. Leave it off. Turning it on is the only way new violations get added to the store, and that should be an explicit, reviewed decision.

When a cycle is fixed, ArchUnit removes its entry from the store. The removal appears in the diff, which gives reviewers visible evidence that the cycle is gone.

A frozen file with no owner tends to become permanent debt. Assign the store to a team, the same way you would assign a module. Review it on a fixed schedule, such as each planning cycle, and pick specific entries to remove. This lets you adopt the check immediately and pay down existing cycles incrementally, without a multi-week cleanup project before the first enforced build.

package com.example.architecture;

import com.tngtech.archunit.core.importer.ImportOption;
import com.tngtech.archunit.junit.AnalyzeClasses;
import com.tngtech.archunit.junit.ArchTest;
import com.tngtech.archunit.lang.ArchRule;
import com.tngtech.archunit.library.freeze.FreezingArchRule;

import static com.tngtech.archunit.library.dependencies.SlicesRuleDefinition.slices;

// Store settings live in src/test/resources/archunit.properties:
//
//   # Committed to the repo and reviewed like code
//   freeze.store.default.path=src/test/resources/archunit_store
//   # Set to true once to create the baseline, then set back to false
//   # so a wrong path in CI fails instead of creating an empty store
//   freeze.store.default.allowStoreCreation=false
//   # Keep off: turning it on accepts every current violation
//   freeze.refreeze=false
//
// Owner: platform-team. Review the store each planning cycle
// and pick entries to remove.
@AnalyzeClasses(
        packages = "com.example",
        importOptions = ImportOption.DoNotIncludeTests.class)
class ModuleCycleTest {

    // Each top-level package under com.example is treated as one module.
    // Cycles recorded in the store are tolerated. A new cycle fails the build.
    // When a recorded cycle is fixed, its entry is removed from the store
    // and the removal shows up in the diff.
    @ArchTest
    static final ArchRule modulesShouldBeFreeOfCycles =
            FreezingArchRule.freeze(
                    slices().matching("com.example.(*)..")
                            .should().beFreeOfCycles());
}

A JUnit 5 ArchUnit test that wraps the slice cycle rule in FreezingArchRule.freeze, along with the archunit.properties settings that keep the committed violation store in the repository and stop new violations from being added to it without a reviewed change.

What are the ways to break a dependency cycle, and which should you choose?

Once you have picked the edge to cut, there are four common ways to remove it. Take a typical cycle: orders calls billing to create an invoice at checkout, and billing reads orders to get line items.

Technique When it fits What it costs Risk left behind
Dependency inversion One side needs a capability, not the other module's internals One interface plus wiring A logical cycle can remain: billing still calls back into order logic at runtime
Shared kernel / API module The coupling is only shared IDs and value objects A new module and a rule that it depends on no feature module It grows into a dumping ground for anything two modules both touch
In-process event or callback Upstream only needs to announce that something happened Event types, a dispatcher, and handler registration Control flow is harder to trace and debug, and handler order is implicit
Merge the modules Changes to one almost always require changes to the other A larger module, and a possible ownership discussion Cohesion problems move inside the module, where slice rules no longer see them

Dependency inversion: billing defines OrderLineSource, and orders implements it. The compile-time arrow now points one way.

Shared kernel: move OrderId and Money into a shared module. Review additions to it as strictly as public API changes, or it will grow without anyone deciding it should.

Events: orders publishes OrderPlaced, and billing subscribes. orders no longer references billing at all.

Merge: if every invoice change also touches order code, the boundary is not real.

Use inversion when the dependency is a real need for a capability. Use events when the caller does not need a result. Use a shared kernel only for data types that have no behavior.

How do you keep the module graph intentional and the checks cheap in CI?

Acyclic is the minimum. A graph can be free of cycles and still let every module reach into every other module's internals. Add allowed-dependency rules so each edge in the graph is one you chose. A common rule is that code outside a module may only depend on that module's api package. Express it as "no classes outside ..billing.. should depend on classes in ..billing.internal..", or generate one such rule per module from a list. This keeps the public surface small, so a later extraction only has to replace the calls into api.

CI wiring

  • Import once. Class import is the expensive step. With JUnit 5 and @AnalyzeClasses, ArchUnit caches the imported classes per location set, so several rule classes can share one import. Exclude test classes from the import unless you have rules about them.
  • Run in the normal test phase. Architecture tests are unit tests. Don't put them in a separate nightly job, where failures show up after the code has merged.
  • Treat the frozen-violation store as reviewed code. Commit it and require review on any diff to it. A pull request that adds entries is adding debt and should be justified. Entries should only ever be removed.

The cost

Illustrative estimate. Assume the import plus rule evaluation takes about 10–20 seconds on a large codebase, and that a few cycles or boundary rules are checked. Shared across rule classes, that is a small part of a typical test run.

The larger cost is maintenance. These rules match on package names, so renaming or moving a module means updating the rules in the same change.

The payoff is that a boundary violation fails a build during review, when the fix is a one-line change. Without the rule, it may stay hidden until extraction, when dozens of such calls have to be untangled at once.

How can ArchUnit cycle checks save engineering time?

The time savings come from moving the discovery of a cycle from late, expensive moments to early, cheap ones:

  • Fixing at the point of introduction. When a new cycle fails the pull request that created it, the author still has the context and the change is small. The usual fix is to move one import or introduce one interface.
  • Less manual review effort. Reviewers no longer need to trace imports across modules to spot transitive loops, which they rarely catch anyway. Review time goes to design questions instead.
  • Cheaper extraction. When a team decides to pull a module out into a service or library, an acyclic graph with a narrow api package means the work is mostly replacing calls into that package, not first discovering and untangling hidden dependencies.
  • Faster, more isolated tests. Once a module no longer drags its cycle partners along, its tests start fewer components, which shortens feedback loops for everyone working in that module.
  • Shorter debates. The report lists the exact class-level dependencies behind each edge, so a discussion about module ownership starts from facts rather than recollection.

Illustrative estimate, with assumed inputs. Assume a cycle caught in review takes about 15 minutes to fix. Assume that the same kind of coupling, left unchecked until a service extraction, has grown to 30 call sites, each taking about an hour to untangle, retest and review. That is roughly 30 hours of work versus a series of small fixes spread across the pull requests that would otherwise have introduced those call sites. These figures are assumptions for the sake of the arithmetic, not measurements. Your own numbers will depend on codebase size, test coverage and how often modules are extracted. The shape of the trade-off holds regardless: the check costs a few seconds per build and a small amount of rule maintenance, and it removes a category of work that otherwise arrives all at once at the worst time.

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 break module dependency cycles, 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.