What are package cycles and why do they block modularizing a monolith?
A package cycle exists when a chain of dependencies between Java packages leads back to where it started. The simplest case is com.shop.order importing a class from com.shop.billing while billing imports something from order. Longer cycles, such as order → billing → customer → order, behave the same way: every package in the loop depends, directly or indirectly, on every other.
That matters because a cycle turns several packages into one unit. You cannot extract billing into its own module or service without bringing order along, and order brings customer. You cannot compile, test, or reason about one of them in isolation, because each one's behavior depends on code in the others. Cycles also compound. Once two packages already depend on each other, adding one more import between them looks harmless, so the coupling gets denser and harder to undo.
Most cycles form in a few predictable ways:
- A shared
utilorcommonpackage. It starts with string helpers. Then someone adds a helper that needs a domain type, and nowcommondepends on the packages that depend on it. - Bidirectional service calls.
OrderServicecallsBillingServiceto charge a card, andBillingServicecalls back intoOrderServiceto update order status. - Entities referencing services. A domain entity calls a service or repository to load related data, so the model layer depends on the layer built on top of it.
This matters most to backend and platform engineers who are planning to extract modules from a large Java monolith, or who are trying to enforce boundaries that the compiler does not check.
Package cycle: each package depends on every other
+----------------+ imports +------------------+
| com.shop.order |------------->| com.shop.billing |
+----------------+ +------------------+
^ |
| imports | imports
| +-------------------+ |
+---------| com.shop.customer |<-+
+-------------------+
(1) shared util/common (2) service calls (3) entity -> service
+-----------+ +----------------+ +----------------+
| order |-----+ | OrderService | | Order entity |
+-----------+ | +----------------+ +----------------+
^ v | ^ | ^
| +-----------+ v | v |
+-----| common | +----------------+ +----------------+
+-----------+ | BillingService | | OrderService |
+----------------+ +----------------+
The top shows a three-package cycle (order → billing → customer → order), and the bottom shows the three common ways cycles form: a shared common package, bidirectional service calls, and entities that call services.
How does ArchUnit cycle detection work?
ArchUnit does not parse source files. It reads compiled bytecode, either through ClassFileImporter directly or through @AnalyzeClasses on a JUnit 5 test class, where each @ArchTest field or method is a rule. Because it works on class files, the same checks apply to Kotlin, Scala, or any other JVM language that compiles to bytecode. Dependencies that exist only in source, such as references a compiler inlines as constants, may not appear in the bytecode.
The import scope determines what the rules see. ImportOption.DoNotIncludeTests drops test classes, which often depend on many packages at once and can create cycles that production code does not have. Generated code, such as mappers, protobuf stubs, or annotation-processor output, can be excluded with a custom ImportOption that rejects matching class-file locations.
A cycle rule starts with SlicesRuleDefinition.slices().matching("com.example.(*)..").should().beFreeOfCycles(). The capture group (*) defines the slice: every class under com.example.billing.. belongs to the billing slice. A cycle is reported only when dependencies between slices form a loop. Dependencies inside a slice are ignored.
| Pattern | Slice unit | Cycles reported |
|---|---|---|
com.example.(*).. |
Top-level feature | Between features only |
com.example.(*).(*).. |
Feature plus subpackage | Also between subpackages within a feature |
Start with top-level features. They match the module boundaries you plan to extract, and the result list stays short. Use the deeper pattern later, once features are clean and you want to enforce layering inside them.
import com.tngtech.archunit.core.importer.ImportOption;
import com.tngtech.archunit.core.importer.Location;
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 production bytecode under com.example, minus tests and generated code.
@AnalyzeClasses(
packages = "com.example",
importOptions = {
ImportOption.DoNotIncludeTests.class,
PackageCycleTest.DoNotIncludeGenerated.class
})
class PackageCycleTest {
// Start here: one slice per top-level feature (billing, orders, ...).
// Only loops between features are reported.
@ArchTest
static final ArchRule features_are_free_of_cycles =
slices().matching("com.example.(*)..").should().beFreeOfCycles();
// Later: one slice per feature subpackage (e.g. billing.api, billing.domain),
// which also reports loops between subpackages of the same feature.
@ArchTest
static final ArchRule subpackages_are_free_of_cycles =
slices().matching("com.example.(*).(*)..").should().beFreeOfCycles();
// Rejects class files whose location points into a generated-sources output.
// Adjust the path fragment to match your build's generated output directory.
public static class DoNotIncludeGenerated implements ImportOption {
@Override
public boolean includes(Location location) {
return !location.contains("/generated/");
}
}
}
A JUnit 5 ArchUnit test that excludes test and generated classes, then checks for cycles first between top-level feature slices and then between feature subpackages.
How do you read an ArchUnit cycle failure and trace it to the code?
An ArchUnit cycle failure has two layers. The first is a summary line naming the slices in the loop, such as orders -> billing -> customers -> orders. That line tells you the cycle exists and which features take part in it. The second layer is a list for each edge in that chain, and this list is the part you act on.
Under each edge, ArchUnit lists the class-level dependencies that create it. Every entry names a source class, a target class, the kind of dependency, and usually a file and line number. The common kinds are:
- Field type: a field in
billingholds acustomerstype. - Method call: a method in
orderscalls a method inbilling. - Parameter or return type: a method signature mentions a class from the other slice.
- Inheritance: a class extends a class or implements an interface from the other slice.
The line number takes you straight to the code. ArchUnit analyzes compiled bytecode, not source text. An unused import never appears in the report. A dependency that exists only through a fully qualified name does. If you clean up imports and the violation remains, look for the actual usage.
Edges are not equally expensive to cut. One edge may rest on a single convenience call, while another rests on dozens of shared types. The report treats them the same. In a cycle with four or five slices, it is often unclear which edge is the cheapest to break. For that decision, a dependency-graph visualization that shows edge weights is more useful than reading the text output.
# Abbreviated ArchUnit failure for slices().matching("com.example.(*)..").should().beFreeOfCycles()
# Package and class names are placeholders.
Architecture Violation [Priority: MEDIUM] - Rule 'slices matching 'com.example.(*)..' should be free of cycles' was violated (1 times):
Cycle detected: Slice billing ->
Slice customers ->
Slice orders ->
Slice billing
1. Dependencies of Slice billing
- Field <com.example.billing.Invoice.customer> has type <com.example.customers.Customer> in (Invoice.java:0)
- Method <com.example.billing.InvoiceService.create(com.example.customers.Customer)> has parameter of type <com.example.customers.Customer> in (InvoiceService.java:0)
2. Dependencies of Slice customers
- Method <com.example.customers.CustomerService.lastOrder(long)> calls method <com.example.orders.OrderRepository.findLatest(long)> in (CustomerService.java:42)
3. Dependencies of Slice orders
- Class <com.example.orders.OrderInvoicedListener> implements interface <com.example.billing.InvoiceListener> in (OrderInvoicedListener.java:0)
- Method <com.example.orders.Order.total()> has return type <com.example.billing.Money> in (Order.java:0)
# How to read it:
# - The "Cycle detected" chain is the summary: which slices form the loop.
# - Each numbered block is one edge. Its entries are the bytecode-level reasons for that edge.
# - Method calls carry a real line number (CustomerService.java:42): open the file there.
# - Fields, signatures and inheritance are declarations, so ArchUnit may report line 0.
# Use the fully qualified member name to find them.
# - Edge 2 rests on a single call. It is likely cheaper to cut than edge 1,
# which shares the Customer type across fields and signatures. The report does not rank edges for you.
An annotated, abbreviated ArchUnit cycle failure showing the slice chain, the per-edge dependency entries (field, parameter, method call, inheritance, return type), and how to use each entry to find the code that creates the edge.
How do you adopt cycle checks in a codebase that already has cycles?
Adopt the freeze before the modularization effort starts. If you wait until after a cleanup, every cycle someone adds during the cleanup has to be found by hand. Wrapping the cycle rule in FreezingArchRule.freeze() gives you a ratchet from the first day. ArchUnit records the current violations in a violation store, a set of plain-text files that you commit to the repository. On later runs, any violation that is not in the store fails the build. Violations that no longer occur are removed from the store automatically. By default, ArchUnit will not create a new store, so set freeze.store.default.allowStoreCreation=true in archunit.properties for the first run, then turn it back off.
Review the store like code. A pull request that deletes lines means a cycle was broken. A pull request that adds lines means someone froze a new cycle into the store, either by enabling freeze.refreeze or by editing the files directly. Treat any added line as a blocking review comment unless the PR explains why it is there. Assigning an owner to the store directory makes sure a specific person sees these diffs.
Merge conflicts in the store are usually two branches each removing different lines. To resolve one, keep the union of both sides and rerun the tests. Entries that are already fixed drop out on that run.
A frozen violation can easily become permanent amnesty. Three things prevent that:
- An owner: one named person is accountable for reducing the store.
- A visible count: report the number of stored violations in CI output or on a dashboard.
- A scheduled review: check the count at a regular interval and confirm it is going down.
package com.example.shop.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;
import static com.tngtech.archunit.library.freeze.FreezingArchRule.freeze;
// src/test/resources/archunit.properties:
// freeze.store.default.path=archunit_store # commit this directory
// freeze.store.default.allowStoreCreation=true # first run only, then remove
// freeze.refreeze=false # never true in CI
@AnalyzeClasses(
packages = "com.example.shop",
importOptions = ImportOption.DoNotIncludeTests.class)
class PackageCycleTest {
// The plain rule: every top-level package under com.example.shop is a
// slice, and no slice may take part in a dependency cycle.
private static final ArchRule noCycles =
slices().matching("com.example.shop.(*)..")
.should().beFreeOfCycles();
// freeze() records today's cycles in the violation store. Violations
// already in the store pass; any new one fails the build. Violations
// that disappear are removed from the store, so the store only shrinks
// unless someone deliberately refreezes or edits it.
@ArchTest
static final ArchRule no_new_package_cycles = freeze(noCycles);
}
A JUnit 5 ArchUnit test that wraps a slice cycle rule in FreezingArchRule.freeze(), with the archunit.properties settings that put the violation store in a committed directory and allow it to be created only on the first run.
Which refactorings break a package cycle?
Each cycle contains one edge that points the wrong way. Choose the fix based on why that edge exists, not on which change is quickest to make.
| Refactoring | Cycle it suits | Why it removes the cycle |
|---|---|---|
| Dependency inversion | A lower-level package calls back into a higher-level one to get a capability | The consuming package defines the interface it needs and the other package implements it, so the source-level dependency reverses |
| Extract a shared package | Both packages reference each other's data types, value objects or constants | The shared types move to a third package that both depend on, and neither depends on the other |
| Replace calls with events | One package notifies another that something happened and needs no result | The publisher stops referencing the subscriber, and only the event type is shared |
| Move a misplaced class | A single class causes the back edge and belongs to the other package's concern | The class moves to the package that owns its behaviour, and the edge disappears with it |
The rule passing doesn't mean the coupling is gone
ArchUnit checks import edges. It does not check design. You can make the rule pass and keep the same coupling:
- Moving an interface without rethinking ownership. The interface moves to the consumer but still mirrors the provider's API method for method, so it has to change whenever the provider changes.
- A shared package that becomes a dumping ground. A
commonpackage that accumulates unrelated types hides the cycle instead of resolving it. - Events that behave like calls. An event whose sender waits for a reply is still a synchronous call.
To check that a fix worked, ask whether the consuming package could change or replace the implementation without touching the other side. If it can't, the coupling is still there.
Scoping, tuning, and running architecture tests in CI
Run a separate beFreeOfCycles() rule for each area of the monolith instead of one rule over the whole codebase. A rule matching com.acme.billing.(*).. and another matching com.acme.catalog.(*).. produce failures that name the area and the team that owns it. One global rule produces a single report that mixes unrelated cycles. When a dependency is intentional, such as a shared event type that several slices are meant to reference, exclude it with ignoreDependency(...) or narrow the slice pattern so that package is not treated as a slice. Both options keep the exception in the rule definition, where reviewers can see it.
Put these rules in their own test class or module, for example ArchitectureTest. A failure there tells the reader the problem is structural and not a broken behavior. Architecture tests are ordinary unit tests, so they run in the normal build with no extra CI stage.
Importing classes is the expensive part. ArchUnit reads bytecode for every class in scope, which can take seconds on a large monolith. Declare the scope once with @AnalyzeClasses and write the rules as @ArchTest fields. ArchUnit then caches the import and reuses it for every rule with the same locations, instead of re-importing for each test. Use ImportOption.DoNotIncludeTests to keep test code out of the analysis.
Illustrative estimate. These inputs are assumptions:
- An import takes 15 seconds.
- There are 12 rules.
- The team runs 50 builds a day.
Re-importing for every rule adds about 180 seconds per build, roughly 2.5 hours of build time a day. With a cached import the cost is 15 seconds per build. That difference decides whether developers run the tests locally or skip them.
When should you avoid relying on ArchUnit cycle checks, and what are the alternatives?
ArchUnit reads compiled bytecode, so it only sees dependencies the compiler recorded. A cycle created through reflection, a Spring bean injected by name, a Class.forName string lookup, or a handler chosen from runtime configuration leaves no edge in the class files. The rule passes, and the coupling still exists. If your monolith relies heavily on these mechanisms, a green cycle check does not prove much.
Slice granularity has a cost in both directions. Coarse slices, such as one slice per top-level domain, merge internal cycles into a single node and hide them. Fine slices, such as one per subpackage, produce long reports full of trivial cycles, and teams tend to respond by disabling the rule. Pick the granularity that matches the units you actually plan to extract.
Acyclic packages are also not isolated modules. billing can depend on orders internals without any cycle. Pair the cycle rule with layer or dependency-direction rules that state which way dependencies may point.
| Approach | What it enforces | Fits best when |
|---|---|---|
| ArchUnit cycle and layer rules | Bytecode dependencies, checked in tests | You need fast feedback inside one build unit before splitting it |
| Maven or Gradle multi-module | Compile classpath per module. Cyclic module dependencies are rejected | Boundaries are stable enough to pay the cost of restructuring the build |
| JPMS modules | Exported packages and readability, at compile time and run time | You control the libraries and want strong encapsulation, including against reflection |
| Code review conventions | Design intent, including runtime wiring | Coupling happens through config or reflection, which no static check sees |
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 archunit cycle detection, 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.