Backend Separation of Concerns and Module Boundaries
Learn how to set backend module boundaries, keep dependencies pointed in one direction, and avoid coupling that makes routine changes risky.
Backend module boundaries separate HTTP handling, business rules, and storage so a change in one area does not pull in details from the others. An order example shows how a use case can depend on a storage contract while an adapter handles database work. It also covers when boundaries help, how to enforce them, and what to watch in production.
Backend Separation of Concerns and Module Boundaries
Introduction
When a small backend grows, one file often ends up handling HTTP parsing, business rules, database queries, and logging. The first few features still ship. Then an order-rule change breaks a report, tests need a database just to check validation, and developers hesitate to touch the shared utils folder.
Consider creating an order: the HTTP route should parse the request, the use case should check order rules, and a storage adapter should write to the database. If the use case imports the web framework and SQL client directly, a validation test has to understand both. A module boundary gives each responsibility a clear owner and lets the use case depend on a small storage contract instead. The aim is to keep common changes local and failures easier to trace, not to create the most folders.
Trace a request through the boundaries
For an order request, the HTTP adapter validates transport-specific details, the application flow coordinates the use case, and the domain code applies the order rules. A storage adapter performs database work. The response goes back through the HTTP adapter.
flowchart LR
Client[HTTP client] --> Route[HTTP route]
Route --> UseCase[Create order use case]
UseCase --> Rules[Order rules]
UseCase --> StorePort[Order storage interface]
StorePort --> SqlAdapter[SQL storage adapter]
SqlAdapter --> Database[(Database)]
UseCase --> Route
Route --> Client
The application flow can depend on an interface for storage, while the SQL adapter implements it. That lets the order behavior run against an in-memory fake in a unit test. It also keeps HTTP concepts such as status codes out of the order module. For a related view of how this plays out at service scale, see microservices vs monolith. Internal module boundaries can provide useful separation without introducing network calls.
A small implementation
Here is a deliberately plain TypeScript example. The route owns HTTP parsing and response mapping. The use case owns the operation’s sequence. The storage interface expresses what the use case needs, not how a database happens to provide it.
type NewOrder = { customerId: string; itemIds: string[] };
type Order = NewOrder & { id: string; status: "pending" };
interface OrderStore {
insert(order: NewOrder): Promise<Order>;
}
async function createOrder(input: NewOrder, store: OrderStore): Promise<Order> {
if (input.itemIds.length === 0) {
throw new Error("An order needs at least one item");
}
return store.insert(input);
}
async function postOrder(
request: Request,
store: OrderStore,
): Promise<Response> {
const input = (await request.json()) as NewOrder;
try {
const order = await createOrder(input, store);
return Response.json(order, { status: 201 });
} catch (error: unknown) {
if (
error instanceof Error &&
error.message === "An order needs at least one item"
) {
return Response.json({ error: "invalid_order" }, { status: 400 });
}
throw error;
}
}
In production code, use a dedicated validation result or error type rather than matching an error message. The useful part here is the seam: createOrder does not import the web framework or database client. This also complements functions, modules, and error handling, which covers smaller function and error boundaries.
Enforcing boundaries in a codebase
Folder names suggest ownership, but they do not stop a caller from importing a private file. Give each module a small public entry point and make the allowed dependency direction reviewable. For example, an order module might expose orders/index.ts while keeping its SQL adapter under orders/infrastructure/:
import { createOrder } from "../orders"; // public operation
import { SqlOrderStore } from "../orders/infrastructure/sql-order-store"; // internal detail
Other modules should call the public operation, not reach into the adapter or import its database types.
Write down a few rules that match the architecture, then enforce the ones that prevent recurring mistakes. A lint restriction can block imports from orders/infrastructure outside the order module. A dependency graph check can flag cycles or a domain module that imports an HTTP framework. A focused architecture test can protect a small set of critical rules. These checks work best when they explain the violation and point to the public API; a blanket ban on imports can turn ordinary refactors into configuration work.
Keep the rule set small. If each pull request needs another exception, the module may have an unclear owner or the boundary may not fit the way the code changes. Review exceptions when they are added, and remove them once the underlying boundary is fixed.
| Enforcement option | Useful when | Cost to watch |
|---|---|---|
| Public module entry points | Callers need a stable API and internals should stay local | A large entry point can become a second catch-all module |
| Import restrictions | A few forbidden dependency directions cause repeat bugs | Path rules need maintenance as folders move |
| Dependency graph checks | Cycles or broad dependency drift are hard to spot in review | A noisy rule set will train developers to ignore failures |
Start with one rule tied to a real failure, such as preventing business modules from importing transport code. Add another only when the team can name the change or defect it would have caught.
When to Use
Separate responsibilities when a part of the system has its own rules, changes on a different cadence, needs a distinct test strategy, or is owned by a different team. Start with the boundaries visible in current pain: repeated rule logic, imports that form cycles, or a test that needs infrastructure unrelated to what it checks.
When NOT to Use
Do not add an interface and an adapter for every function by default. If a feature is small, used in one place, and has no meaningful variation or testing need, a direct call may be clearer. A boundary that only renames a method adds navigation without reducing coupling. It is also fine to begin with a modular monolith; a process boundary brings operational costs that a folder boundary does not. The architecture trade-offs between monoliths and microservices are a useful reminder to make that jump for a concrete reason.
Trade-Off Table
| Choice | Helps with | Costs or risks |
|---|---|---|
| Feature-oriented modules | Keeps a feature’s rules and storage near each other | Shared behavior can be duplicated unless ownership is clear |
| Layer-oriented modules | Makes framework and infrastructure code easy to locate | A single feature may require edits across many folders |
| Public interfaces at boundaries | Allows callers to ignore implementation details and simplifies focused tests | Too many interfaces create ceremony and hide simple control flow |
| Shared common module | Centralizes stable, genuinely cross-cutting behavior | A catch-all module becomes a dependency that every feature can change |
Pick the smallest structure that keeps likely changes local. Revisit it when the actual change patterns contradict the original choice.
Production Failure Scenarios
Boundaries do not prevent every bug, but they make failures easier to localize. Circular imports can create fragile startup behavior; move the shared contract to a stable owner or let one module own the workflow. A route that catches every exception and returns 400 hides database outages as client mistakes; map expected input errors explicitly and return a safe 5xx for infrastructure failures. A slow dependency can tie up requests, so apply timeouts and cancellation at its adapter and track its latency separately from total request time.
Two concrete incidents
Here are two ways a boundary mistake can reach production:
- A storage migration changes business behavior. A team replaces a nullable database column with a default value. The repository maps
NULLto0, and the order module treats that as a real price instead of a missing price. Orders now complete with incorrect totals. Keep database representations inside the storage adapter, map missing values explicitly, and test the adapter contract against both old and new records before deploying the migration. - A shared module change breaks unrelated features. A developer changes a shared
Customertype to require a new field. Billing and reporting import that internal type directly, so both fail at runtime when older records do not include it. Expose stable module operations rather than internal data shapes, add compatibility tests for known consumers, and roll out schema and code changes in an order that supports both versions.
In both cases, find where the assumption crossed its owner boundary. Fix the mapping or contract there, then add a regression test at that edge.
Boundary and tracing checklist
- Ownership and contracts: Name an owner for each public module contract. Review caller compatibility when its inputs or behavior change, and watch for consumer failures after rollout.
- Dependency direction: Keep business rules dependent on stable interfaces, with adapters implementing them. Review boundary changes for new reverse dependencies or callers reaching into private types.
- Cross-module traces: Propagate a correlation ID through each module call. Record the boundary operation, outcome, and duration with fields such as
order_id,dependency, anderror_code; track storage latency and failures with bounded labels. Do not log request bodies or credentials.
Security at module edges
Treat each boundary as a place to validate assumptions. Parse and validate untrusted HTTP input before it reaches business logic. Check authorization close to the operation that uses the protected resource, rather than relying on a route name or UI state. Storage adapters should use parameterized queries and least-privilege credentials.
Keep secrets in the runtime configuration layer, never in module defaults or logs. Return stable public errors to clients and keep internal stack traces and SQL details on the server. If a module emits events, define which fields are safe to publish; copying an entire database record into an event can expose fields that consumers do not need.
Observability Checklist
- Logs: At each public module operation, log the module name, operation, outcome, duration, and correlation ID. Log denied dependency calls with the caller and target module. Keep payloads, credentials, and personal data out of these records.
- Metrics: Track module call errors and latency by operation, dependency timeouts, and the number of forbidden import or dependency violations found in CI. Keep labels bounded; avoid customer IDs, file paths, and arbitrary exception text as metric dimensions.
- Traces: Create a span for each cross-module or external dependency call. Record the caller module, callee module, operation, and deployment version so a slow request can be followed to the boundary that stalled.
- Change impact: During release review, compare changed public contracts with their declared consumers. Track consumer contract test failures and post-deploy error rates by module version to catch a change that passes the producer’s tests but breaks a caller.
- Alerts: Page on sustained increases in boundary error rate or dependency timeout rate. Send a lower-priority alert when CI detects a forbidden dependency or when a release causes a sharp rise in consumer contract failures; include the module pair and release version in the alert.
Security and Compliance Notes
Treat module contracts as data-sharing decisions. Define which fields may cross each boundary, classify sensitive fields, and pass only what the receiving operation needs. For example, a reporting module that needs an order total should receive the total and a reporting key, not the customer’s address and payment token.
Keep authorization checks with the operation that protects the resource. A route can authenticate the caller, but the application operation should verify that the caller may act on the specific account or order. Give adapters separate, least-privilege credentials and avoid granting a shared module broad access just because several features use it.
For regulated data, document the module owner, approved consumers, retention needs, and audit events at the boundary. Emit an audit record for sensitive reads or changes, but keep secrets and unnecessary personal data out of logs, traces, and events. Review these contracts when a module gains a new consumer or a field changes classification.
Common Pitfalls / Anti-Patterns
- A module per class. If two classes always change together, splitting them adds navigation without clarifying ownership. Keep them together until they have different reasons to change.
- A
sharedpackage with no owner. One feature adds a pricing helper; another adds database rows and HTTP response types. Soon every module depends onshared, and a small helper change can affect the whole application. Give shared code a clear purpose, or keep a helper with its first caller until a second real use appears. - A public interface leaks implementation details.
CustomerRepository.getCustomer()returns an ORM entity, so callers begin using lazy-loaded relations and database-specific fields. Return the small application-level data shape callers need, and keep ORM types private to the adapter. - Business rules copied into a controller. If a controller repeats validation because the module interface is awkward, callers may be using the wrong contract. Add an operation that expresses what the caller needs instead of copying the rule.
- Two modules call each other to finish one workflow. Orders ask inventory to reserve stock, while inventory calls orders to mark the order ready. A failure or retry can leave both sides waiting or applying the operation twice. Choose one owner for the workflow and let it call both modules through explicit operations.
- A module boundary is treated as authorization. Moving a function into an
adminmodule does not prove the current caller is an administrator. Check identity and resource permissions in the operation itself, then test denied access as well as successful access. - A monolith is split into services too early. The team inherits deployment, retry, and partial-failure problems before independent ownership or scaling solves a real need. Keep the boundary in-process until the operational cost has a clear payoff.
If a boundary is hard to explain in one sentence, it may not represent a real responsibility yet. Start with the change that hurts, make the smallest seam that would contain it, and adjust after the next few features.
Quick Recap Checklist
- Can I name the responsibility this module owns?
- Can callers use it without knowing its tables, framework, or private types?
- Do dependencies point toward stable rules, with infrastructure at the edges?
- Can I test the rule without starting unrelated infrastructure?
- Are errors mapped at the boundary that understands them?
- Do logs and metrics identify which boundary failed without exposing sensitive data?
- Does each interface remove real coupling, or only add another hop?
Interview Questions
It means assigning different reasons to change to distinct parts of the system. For example, HTTP response formatting belongs at the transport edge, while a pricing rule belongs with the pricing behavior. The boundary should let one change happen without requiring callers to understand unrelated details.
Look at real changes and tests. A useful boundary keeps related changes together, hides implementation details, or lets a rule be tested without starting infrastructure it does not need. If callers still reach into internals, or the boundary only forwards every call unchanged, it may not be helping.
No. An interface is useful when it separates a policy from a replaceable or external detail, such as a business operation from its database adapter. For a stable helper used in one place, a direct function may be simpler and just as testable.
Consider a service boundary when independent deployment, scaling, security, or team ownership solves a specific problem. The team must also be ready to operate network timeouts, retries, versioned contracts, and partial failure. A code-level boundary is cheaper, so it is often a sensible first step.
Give each module a public entry point, keep implementation files private by convention, and add targeted import restrictions or dependency checks for rules that prevent real problems. Keep the checks narrow and explain how to use the module's public API.
It contains unrelated models, helpers, and framework types, and many features depend on it for different reasons. Move code toward the feature that owns its behavior, and share it only when there is a stable concept with clear ownership.
An ORM entity exposes persistence details such as lazy relations, nullable columns, and database-specific types. Mapping it to an application-level result keeps those details inside the adapter and gives callers a contract they can use without knowing the database.
Choose one owner to coordinate the workflow and have it call the other module through an explicit operation. Mutual calls make retries and partial failures harder to reason about and can create dependency cycles.
Use a direct call when one stable implementation serves one caller and there is no meaningful testing or replacement seam. Add an interface when it lets a policy avoid depending on an external detail or gives callers a stable contract.
Review whether the module owner or dependency direction is wrong, and whether consumers need a missing public operation. Keep only documented exceptions that have a concrete reason, then revisit them when the boundary changes.
The use case may depend directly on the database adapter. Put a small storage contract between the use case and persistence, then test the rule with an in-memory fake. Keep adapter tests for database behavior.
The route should map expected input errors to client responses and let infrastructure failures become safe server errors. Catching every exception as a 400 makes outages look like bad requests and hides the real failure.
Check whether the module has a clear owner and whether callers are missing a public operation. Keep only exceptions with a specific reason; repeated exceptions often point to a boundary that does not match how the code changes.
Keep credentials, request bodies, and unnecessary personal data out of logs and traces. Metrics should use bounded labels such as operation and dependency, not customer IDs, file paths, or arbitrary exception text.
Further Reading
- Functions, modules, and error handling explores how to keep function responsibilities clear and handle errors at the right boundary.
- Backend configuration, environments, and dependencies covers configuration ownership and dependency boundaries across environments.
- Microservices vs. monolith compares code-level modularity with the operational costs of splitting services.
- TypeScript Handbook: Modules explains how module imports and exports define source-level dependencies.
- Martin Fowler: Microservice Trade-Offs discusses module boundaries and the costs that come with service boundaries.
Conclusion
Good module boundaries keep related rules together and keep unrelated changes apart. Start with responsibilities that already have different reasons to change, expose only the operations callers need, and let infrastructure details stay at the edges. If the structure makes routine work slower, change it; the folder tree is there to help the team, not to win an architecture diagram.
Summary
Keep business rules behind clear module contracts, with HTTP and storage details at the edges. Start with boundaries that make real changes easier to test and contain, and add enforcement only for dependency mistakes the team needs to prevent.
Category
Related Posts
Architecture Styles and Patterns: A Practical Guide
Compare layered, hexagonal, event-driven, and service architectures using boundaries, deployment needs, failure modes, and a concrete selection method.
Functions, Modules, and Error Handling
Learn to shape backend functions and modules, handle failures clearly, and build services that are easier to test, operate, and change.
Architecture Decision Records: A Working Guide
Use concise architecture decision records to capture context, options, consequences, and revisit triggers so teams can understand design choices later.