NestJS modules around business capabilities
A NestJS module should own a coherent business capability and export the operations other capabilities are allowed to use. Keep repositories and internal policies private, define transaction ownership, and test import boundaries so the module remains more than a folder convention.
Inside this article 4 sections +
A useful NestJS module protects a business decision. It does not merely collect every file with the same database table name. For a product that sells limited-capacity training sessions, a Reservations module can own the decision that a seat is available and may be held. Orders can request that decision without learning how seat counts are stored.
This boundary is valuable before introducing separate services. It reduces the number of places that can change the same invariant and gives future extraction a credible starting point. The immediate goal is understandable ownership within one application, with one deployment if that remains appropriate.
Start with the invariant that must stay true
In the illustrative training product, a confirmed reservation must not exceed the session's permitted capacity. Order creation, an administrator's adjustment, and a scheduled expiry worker can all affect available seats. If each entry point edits a shared seat repository directly, the invariant belongs to everyone and therefore has no reliable enforcement boundary.
List those entry points and the decisions they need. Orders needs to request a hold, confirm a hold, and release a hold. Administration needs an explicit capacity-change operation with its own policy. An expiry worker needs a conditional transition for holds that are still eligible to expire. These are business operations; they should not become a generic interface for arbitrary row updates.
- Orders may call
- Request a hold, confirm an eligible hold, release a hold by operation identity.
- Administration may call
- Change session capacity under an explicit authorization and conflict policy.
- Private internals
- Seat repository, lock strategy, expiry query, and capacity arithmetic.
- Boundary evidence
- Concurrent hold tests, dependency checks, and explicit conflict results.
Export a narrow provider interface
Nest modules encapsulate providers unless those providers are exported and made available through an imported module. Use that mechanism deliberately. Export a reservation application service or an injection token representing the allowed operations. Leave the repository, adapter configuration, and internal domain policies unexported unless another concrete responsibility requires them.
Define results that let callers make decisions without inspecting database exceptions. A hold request might return held, capacity unavailable, or request conflict. Preserve a stable hold identifier and expiry value. If a caller needs the raw query result to discover whether an operation succeeded, the boundary has not yet expressed the business contract.
Keep transport details outside that contract. An HTTP controller can translate an unavailable seat into the chosen API response, while a queue consumer can record a business rejection. Neither should force the reservation service to know about response objects or queue job instances. This makes the same rule usable from multiple adapters without duplicating its implementation.
Decide who commits the operation
Moving methods into a module does not settle transactions. If creating an order and reserving capacity must commit atomically in the same database, define a transaction coordination strategy that includes both operations. Keep the capability's invariants inside its implementation while making the transaction boundary visible. Avoid opening an independent transaction secretly inside every service method.
If the workflow can tolerate a pending order, use explicit states instead: record the request, acquire the reservation, then confirm or reject the order. This permits asynchronous coordination but introduces recovery obligations. A lost response must not create a second hold, and an expired hold must not later confirm a paid order without a defined resolution path.
Do not hide circular ownership with increasingly broad exports or a global module. A cycle between Orders and Reservations often means an orchestration responsibility is misplaced. A coordinating application service can depend on both capabilities, while each capability remains responsible for its own state transitions. Occasionally a cycle reveals that two proposed modules are one cohesive capability and should stay together.
Extract one path and test the boundary itself
First route new hold requests through the proposed service while leaving storage unchanged. Next move the confirm and release operations, then the expiry worker. During the transition, identify and remove direct repository imports from other capabilities. A compatibility adapter can preserve existing call sites temporarily, but give it an owner and a removal condition.
Test behavior with two simultaneous requests for the final available seat. Exactly which request wins is less important than preserving the capacity rule and returning explainable results. Test repeated confirmation, expiry racing with confirmation, and a capacity reduction below existing reservations. These scenarios reveal whether the invariant lives inside the module or relies on callers behaving politely.
Add an import restriction that rejects references to the module's internal persistence directory from outside it. A dependency check is useful because Nest's injection encapsulation does not prevent ordinary TypeScript imports of internal code. Also compile a small consumer fixture using only the documented exports. That check catches accidental reliance on application-wide provider registration.
The result should be a smaller public surface and fewer reasons for unrelated code to change together. The separate business API decision explains when this boundary may eventually deserve its own deployment. An architecture review helps prioritize the extraction, and application implementation turns the contract into a tested migration.