Est.

Layered Architecture Enforcement in Backend Services

Automated enforcement prevents architectural violations that pass tests and compile correctly.

Sponsored by Graphide

The Architecture Graph Editors
· 8 min read
Cover illustration for “Layered Architecture Enforcement in Backend Services”
Codebase Architecture · October 23, 2026 · 8 min read · 1,860 words

To enforce layered architecture in backend services, teams need clear dependency rules, machine-checkable contracts, and a CI gate that blocks violations before merge. Agent-readable guidance and dependency graphs help show how the code should be structured, but neither enforces the rules. Agent-generated code must satisfy the same architectural constraints as any other contribution, even when it compiles and passes functional tests.

What layered architecture means in practice: four layers, one dependency rule

Routes register paths and delegate to controllers. Controllers validate input and translate HTTP, services own business logic and orchestration, and repositories encapsulate persistence. Dependencies must follow the permitted direction between these responsibilities. Services must be unit-testable without HTTP or a database. Controllers must have no queries, and routes must have no business logic.

LifeLineX issue #127 also names Domain/Model and Infrastructure layers, spelling out the work that sits around the controller, service, and repository chain. The practical invariant remains separation of HTTP handling, business decisions, and data access. Authorization provides a concrete test of that separation because different checks need different contexts. Workflow authorization belongs in services or middleware, while structural ownership checks belong in the data layer.

Why AI agents break layer boundaries in ways that compile and pass tests

Dify issue #44145, opened in October 2026, describes agents copying legacy static services instead of the reference slice because their guidance predates the newer pattern. Its repositories-rule.md still described mutating ORM rows inside services, contradicting slices already merged into the codebase. Following the documentation could therefore produce the wrong architecture. Reviews had to restate the same boundary rules on each pull request. The failure was not an inability to generate working code, but a mismatch between available guidance and architectural intent.

This is a structural failure at the seam. An agent can produce a use case that imports a controller, a repository that calls another service’s database, or an entity that calls an external API. Those choices can compile and pass tests while coupling responsibilities that the architecture deliberately separates. Local coherence does not establish global consistency. Unless the boundaries are clear, nearby code can become the example the agent relies on most, even when the team plans to retire that code.

The risk grows when generated diffs cover many files. GitHub’s Copilot telemetry, originally reported in 2023, put AI-generated code at 46% of code written by Copilot users, illustrating the volume reviewers may face. A flawed abstraction can also spread through shared libraries, scaffolding templates, and boilerplate generators. Authorization makes that propagation especially dangerous because bypassing a service can also bypass its workflow checks. Working code alone cannot show reviewers that those checks still run on every path that needs them.

Why documentation alone cannot hold the boundary

An ARCHITECTURE.md file records intent but does not reject code. An agent may read conflicting guidance, read only part of the repository, or underweight instructions buried in a long context. The “lost in the middle” failure means that including a rule in context does not guarantee that it influences generation. Documentation is therefore advisory unless something checks compliance. The same limitation applies to architectural decision records and review comments.

Human review cannot close that gap reliably at scale. A documented dependency rule can be violated in a file the reviewer overlooks or in an import that receives less attention than the surrounding business logic. The pull request can then merge without any system registering the architectural contradiction.

GasiorMateusz’s October 2026 Magazyn PR #215 shows the scope of retrospective cleanup. It applied strict handler → service → repository layering while removing unused types, dead code, and obsolete endpoints. Companion PR #216 handled related frontend cleanup. The example is remediation work. Its clear dependency chain let reviewers check the refactor, but fixing the code that had built up still took changes that an automated boundary gate is meant to prevent.

The enforcement tools that turn layer rules into build failures

Development-time feedback makes boundary violations visible while code is being written. eslint-plugin-boundaries provides immediate IDE feedback, while dependency-cruiser checks JavaScript and TypeScript module rules, detects circular dependencies, and produces graph output. The two serve different purposes rather than competing for the same role. CampusOS set up dependency-cruiser to run through both a pre-commit hook and a GitHub Actions step. Its reported result was all modules and dependencies cruised with zero violations.

ArchUnit is a permissively licensed Java library that runs architecture tests as unit tests, including rules forbidding persistence classes from depending on UI classes. A violation fails the build in CI. NetArchTest serves.NET, while tsarch (ts-arch) serves TypeScript. These tools make dependency direction executable rather than leaving it as a reviewer’s interpretation.

Python projects can set rules for those boundaries with import-linter. Hyperloom added it as a hard CI gate with seven declared contracts covering top-layer ordering, independence between agent packages, and a leaf rule for the common module. An upward import fails a check before review starts. The Dify issue likewise names a per-slice contract template and an ignore_imports baseline as the means to enforce the rules. Beyond source imports, Open Policy Agent (OPA) separates policy decisions from services and supports enforcement across microservices, Kubernetes, APIs, and CI/CD pipelines.

How to define layer rules precisely enough to enforce them mechanically

An enforceable rule names both sides of a boundary. It identifies the packages, modules, or classes involved and states which dependency direction is permitted. A README instruction to keep services independent does not provide that precision by itself. The rule must resolve into a condition that a tool can evaluate. Otherwise, adopting a linter merely moves the ambiguity into configuration.

The Dify issue spells out the rules for each layer. Controllers handle admission, payload mapping, error translation, and serialization, and must not import repositories. Application services own orchestration and must not import HTTP objects. Adapters own their sessions and return records, never ORM rows. The composition root, extensions/ext_application_services.py, alone chooses implementations and reads configuration, so implementation selection does not leak into the layers it assembles.

Exceptions need the same precision as prohibitions. Hyperloom’s seven named contracts name the source packages, the imports they forbid, and the exemptions, so tests and TYPE_CHECKING imports are exempt while function-level imports are still checked. The practical mapping is one automated check for each architectural decision, using a linter rule for package boundaries, CI diffs for file-format changes, or a graph check for circular dependencies. Authorization decisions also need an explicit owner, distinguishing workflow checks from structural ownership checks. Unresolved details should remain documented as unresolved rather than becoming assumed policy, including the baseline details that the Dify issue flags for documentation.

Legacy exceptions require a bounded migration mechanism. A separate Dify issue describes enumerating existing violations in an ignore_imports baseline and shrinking that list over time. This distinguishes tolerated legacy dependencies from newly permitted ones. Without that distinction, an exception can silently redefine the target architecture. Precision therefore includes both the intended boundary and the scope of any temporary departure from it.

Placing the enforcement gate: where in CI layer checks must live to block agent output

The decisive check belongs in the required pre-merge CI path. It must exit non-zero on a violation and block merge without exception. A local hook or IDE suggestion can shorten feedback, but neither guarantees that a submitted pull request satisfies the contracts. CampusOS separates these roles through its pre-commit hook and GitHub Actions step. The hook is a convenience, while the required CI result is the gate.

Hyperloom’s hard gate makes that distinction equally clear. A contributor receives a failure before a reviewer begins examining the pull request, so architecture compliance does not depend on someone noticing the import. The Dify contract template and baseline are likewise described as enforcement mechanisms. Their intended function is to fail CI when a new import violates a contract. This places structural validation before the decision to merge agent output.

The check result also supports traceable governance. Waseem et al. (EASE 2026) describe a governance-aware AI sandbox that treats approval decisions and audit logs as first-class artefacts. Applied to architecture checks, the same principle makes a recorded result preferable to an informal review opinion. Risk-tiered enforcement is an emerging refinement, with stable, well-tested layers potentially warranting lighter scrutiny than shared infrastructure or the composition root. That refinement does not extend static checks into runtime behavior, where valid imports can still support unauthorized access or cross-service database calls.

What static import checks cannot catch, and where runtime and data-layer enforcement fill the gap

A clean import graph proves only the configured structural properties. It cannot prove that an endpoint using the correct service applies the right ownership check. Back4App’s security glossary illustrates the gap with an endpoint that checks ownership and a second endpoint added three sprints later that omits the check. The omitted check creates an IDOR vulnerability despite the existence of a correct check elsewhere.

Workflow authorization needs context such as approval chains, state machines, and role-based limits, so it belongs in services or middleware. Structural authorization concerns ownership, tenancy, and visibility, which belong with the data. Policies, ACLs, and row-level security address that separate exposure. They can protect access through admin SQL, BI tools, background jobs, and second services, including paths that bypass the application’s checks.

OPA decouples policy decision-making from services and extends enforcement across infrastructure and runtime surfaces that import checks cannot reach. The sandbox architecture described by Waseem et al. combines controlled access to AI services with approval workflows and audit logging for traceable experimentation. Its layered separation reaches beyond source organization into execution controls. These mechanisms complement the CI gate because they evaluate behavior and access that a static dependency rule does not express.

Making layer rules visible to agents: the architectural source of truth that enforces itself

Architectural rules need a repository-resident, version-controlled, machine-readable form. Rules held only in meetings or a wiki are not dependable inputs for agents generating code, nor are they executable CI contracts. The Dify issue proposes documenting the application-service architecture in AGENTS.md so agents and contributors build new backend use cases consistently. That guidance explains responsibilities and points generation toward the target pattern. The contracts for that architecture set which dependencies the generated code is allowed to have.

A dependency graph serves a different role from a contract. Dependency-cruiser’s graph output exposes module relationships, while its configuration states which relationships violate policy. The same distinction applies when a developer uses codebase structure to steer an agent. Visibility helps identify where work belongs, but it does not establish permission to cross a boundary. The import-linter contract file and dependency-cruiser configuration are therefore architectural artefacts in their own right, reviewable with the code and enforceable in CI.

The lesson for developers is to shift from inspecting every generated import to defining and verifying structural rules. That work includes precise contracts, agent-readable guidance, and a required CI gate. The Dify migration pattern offers an incremental path by documenting the target architecture, adding contracts, establishing the legacy baseline, and reducing it as code migrates. Each reduction removes an exception from the repository’s executable architectural policy, narrowing the gap between the structure agents encounter and the structure they are allowed to produce.

Sources

  1. Data-Layer vs. Application-Layer Security: Where Rules Belong (2026)
  2. Engineering a Governance-Aware AI Sandbox: Design, Implementation, and Lessons Learned

More in Codebase Architecture