All notes

A Modular Monolith Needs Enforced Dependency Rules

Express capabilities and data ownership instead of mistaking folders for independent modules.

English edition, edited for length. Read the complete Chinese original.

The project has been divided into three categories: orders, billing, and accounts. Orders are directly updated in the billing table, and billing information is then imported into the internal accounting tools. While the categories appear organized, each change still requires understanding the entire system. Modularity is not simply a way of arranging files; it’s a set of rules about who can rely on whom and who owns which data.

A monolithic deployment allows you to retain the advantages of simple transactions and direct debugging, while also establishing clear module boundaries. It doesn’t require you to pretend that each module is an independent service, and it shouldn’t preemptively introduce all the complexities of a fully distributed architecture for future decomposition.

Public Entrance Communication Skills

The order module provides external capabilities for creating, querying, and canceling orders, rather than exporting all entities, storage functions, and utility functions. Other modules should be accessed through a public interface, and developers should not delve into the internal directory to access convenience functions.

modules/orders/public.ts
modules/orders/domain/
modules/orders/application/
modules/orders/storage/

This directory is merely illustrative. The rules require linting, build checks, or testing validation, and cannot simply be written in documentation. When introducing cross-module imports, continuous integration should flag violations of boundaries, rather than relying on familiar project members to discover them incidentally.

The public interface doesn’t necessarily need to be a perfectly abstract design from the start. Instead, focus on establishing stable functionality based on real-world use cases, and avoid exposing all internal parameters. An overly broad interface can once again make internal refactoring vulnerable to external dependencies.

Assuming the order page needs to display the payment status, importing the ORM entities directly from the billing module is the simplest approach, but it would tie the page to the column names, null value conventions, and loading methods of the billing table. A smaller entry point could be getPaymentSummary(orderId), which returns the payment status, amount, and the last updated time. This query does not expose the internal state machine of the payment records to the page, nor does it allow the page to modify the payment records through the returned object.

Maintaining stability at the entry point doesn’t mean promising never to change, but rather having a designated person or team responsible for managing changes. Adding fields can preserve existing calls, while changing the meaning of fields requires migrating the callers. Documenting interface versions, callers, and compatibility strategies within the module documentation is more practical than creating ten layers of abstraction upfront. Internal methods should default to not being exported, and the decision of whether they should be considered public capabilities should be discussed only when actual usage is identified.

The rules should also cover path aliases. While prohibiting ../../billing/storage, it allows @billing/internal, simply using a different method to achieve the same result. Verification should be based on the actual module belonging after parsing, rather than just matching a path prefix. Test code, background tasks, and command-line scripts are also callers, and should not be denied access to all internal entry points solely because they are not HTTP requests.

Data Ownership is More Difficult to Establish Than Code Ownership

The order module has order status, and the billing module has payment records. Other modules can read controlled views, but cannot arbitrarily update the other tables. The database is located in one place, but this does not mean that all tables are public shared variables.

Cross-module transactions may still be reasonable. For example, creating an order and recording a local payment intent require atomicity, which can be coordinated by the application layer to perform a clear, public operation. The key is that the transaction boundaries are visible, rather than one repository secretly modifying data in another module.

Shared reports can be accessed using a read-only query model to retrieve data from multiple modules, but they must be kept separate from write-enabled areas. To improve efficiency, reports can connect to several tables without also granting access to the business modification permissions for those tables.

The read models should have their own data contracts. For example, if a report needs the amount of successful orders, it must clearly specify whether the order date or the payment date determines the month, how to handle cancellations, and whether refunds are treated as negative values or separate records. While cross-table queries can be centralized within the reporting module, the meaning of these queries still needs to be interpreted by the original module. Reading the same value does not necessarily mean understanding the same business concept.

Constraints at the database level can further reduce the risk of out-of-bounds access: Each module uses a clear storage entry point, with key table writes centralized, and independent database roles or schema permissions are used when possible. However, when a process shares a high-permission connection, the database cannot automatically identify which module the code belongs to. At this point, architecture testing, SQL review, and changes in ownership must still be performed, and the directory boundary should not be mistaken for a security isolation.

Cross-module transactions also require a common agreement. The coordination layer can create an order and a local payment intent within the same database transaction, but the payment network request does not belong to this transaction. A successful external call and a failed local submission are still possible states, requiring idempotency keys, recoverable records, or a compensation process. Modular monoliths simplify local atomicity and do not eliminate external side effects.

Clarification on Circular Dependency: Responsibilities Need to Be Reviewed

Order-based billing: Billing triggers an order call, which in turn triggers another order call. This sometimes reflects the actual workflow, but the implementation should avoid allowing both sides to arbitrarily reference internal objects. This can be coordinated by a higher-level workflow module, or expressed through domain events to indicate subsequent actions.

Don’t automatically add messages to the queue just because you see a loop. Internal process events might be sufficient, and direct application-layer coordination might be clearer. Introducing asynchronous changes to maintain consistency and error recovery semantics requires a strong business justification.

Extracting common modules can also mask problems. A directory called shared is constantly growing, eventually becoming a new, unbounded center. Shared code should have a clear and stable concept, such as a currency value object, rather than simply dumping any function that doesn’t fit neatly into a category.

To determine if a loop represents a responsibility issue, you can rewrite the two calls as business sentences. The “Request Payment” call says “Request payment,” while the “Notify Order of Payment Completion” call says “Notify the order that payment has been completed.” The first is a command, and the second is a result. The coordinator is responsible for mapping the result to an order action, while the billing system does not need to know about the order page, inventory management, or notification channels. Conversely, if two modules must read each other’s entire internal fields every time they operate, they may not have yet formed a concept that is worth separating.

Internal event handling is not free decoupling. It should be clear whether the synchronous processor rolls back the original operation when it fails, how the asynchronous processor compensates when it loses events, and whether there are any requirements for event order. For events that can be reliably processed after submission, a transactional outbox can be used. However, events that are only used to refresh the internal process cache may not need to be persisted. Before choosing a mechanism, it is important to list the business results that cannot be lost.

Interfaces Must Carry Necessary Semantics

Assume that canceling an order requires simultaneously checking if it has already been shipped, if there is a payment dispute, and if refunds are allowed. The public API should return a clear result: “Canceled,” “Current status cannot be canceled,” or “Requires manual processing.” It should not allow the caller to first read several internal statuses and then assemble the update themselves. The latter creates a competitive window between checking and writing, and also allows different pages to implement their own rules.

The interface design also needs to distinguish between commands and queries. Queries return user-facing projections, while commands express intent and are maintained by the owner. A query object containing status fields should not be returned to the caller as an update command, even if the fields are the same. This is especially important when dealing with fields such as amounts, tenant information, and audit status, as field similarity does not imply equivalent permissions.

Incorrect agreements also fall under the category of public semantics. Callers should be able to identify business rejections and temporary storage failures. Internal SQL exceptions should not directly become public error codes. At the same time, all exceptions should not be swallowed into false, as this would prevent the coordination layer from knowing whether to prompt the user to modify their input or retry. The entry point for cross-module communication should retain sufficient recovery information while avoiding the leakage of internal implementation details.

updateOrder(data) is very flexible, allowing the caller to define arbitrary field combinations. cancelOrder(id, reason) is closer to business actions, enabling centralized validation of status and record auditing. The more the module’s public interface aligns with business capabilities, the less the external system needs to understand the internal model.

The return type should ideally be a stable query result, rather than a mutable internal entity reference that can be freely modified. Even within the same process, avoid breaking module invariants after external changes to objects. The principles of immutability, controlled construction, and type checking can work together to reduce risks.

When passing user or tenant context between modules, a clear and well-defined structure should be used. This should not rely on global variables or hidden thread contexts to obscure permission checks. Convenience should not come at the expense of losing the ability to understand and control the execution flow.

Testing by Boundary Organization

Within the module, use rapid testing to verify domain rules. Use integration testing at the public entry to verify storage and permissions. Use a small number of cross-module tests to verify critical processes. Avoid initializing the entire system for each test, as this would make it impossible to understand and verify independently after the boundaries are established.

You can write architectural tests to scan for and prevent the import of relationships, thereby preventing external access to internal directories. Database access should also be checked, at a minimum, through code reviews to identify cross-table writes and ensure proper repository ownership. However, simply checking TypeScript imports will not detect SQL queries that bypass boundaries.

The ownership of the migration script also needs to be clarified. Before deleting a module’s fields, it’s essential to confirm that the report and query model depend on it. You should not assume that no one is using it simply because the code hasn’t been imported.

A useful architectural test isn’t just to prove that the current dependency graph doesn’t have any “red lines,” but to deliberately introduce a boundary violation and confirm that the checks actually fail. Furthermore, adding a direct SQL query to modify the payment table in a background task can be used to check whether the review mechanism can detect it. The second scenario might not be automatically detected by a linter, making it more honest to include the table ownership list in the change template than to claim that “the architecture is guaranteed by the tools.”

The test database doesn’t necessarily need to be completely independent for each module. If real-world transactions span modules, the shared test database can retain its semantic meaning. However, test constructs should prepare data using common capabilities, rather than arbitrarily inserting tables from the other module. This means that changes to the internal storage only require adjusting the test factory owned by the module, and callers won’t be stuck with outdated models in dozens of fixtures.

Instead of just looking at the dependency graph, use the order cancellation process to check the boundaries.

Users can cancel orders that have been paid for but not yet shipped, which involves at least the following: order eligibility, refund intent, inventory reservation, and notifications. The order module should first determine whether the cancellation is allowed, and then the application process should coordinate the capabilities provided by the relevant modules. The billing module should create a recoverable refund operation, the inventory module should release the inventory it has reserved, and the notification module should receive the necessary information to send. The process can be synchronized within a single module, but no module should directly modify the tables of other modules to avoid unnecessary calls.

If the local state must be submitted together, either the controlled transaction capability or a specific coordination layer can be used to call public operations within the transaction. This design should avoid exposing the original database connection to all callers; otherwise, even methods outside the “public” interface could arbitrarily modify the table. The transaction mechanism provided by the framework does not need to be repackaged as a generic infrastructure; instead, the focus should be on clearly defining the atomic scope for participants and ensuring that failures are properly rolled back during testing.

External refunds are not considered local transactions. The outcome might be that the order has been stopped, and the refund is being processed. The system needs to demonstrate these two facts, rather than simply requiring a boolean value to indicate that all steps have completed. The process contract should define who continues to coordinate in case of failure, how to handle repeated requests with the same refund intent, and which actions can be compensated. Module boundaries should clearly define responsibilities and should not automatically provide atomicity across external systems.

The query can retrieve information about the status of a page combination and the refund progress, but it should not be responsible for enforcing the rules. The page should decide whether to initiate a refund based on the snapshot it has, leading to a potential conflict between checking and execution. The command entry maintains the invariant based on the current state, while the query projection describes the state. These two have different purposes, and this distinction is more important than simply adopting a layered naming scheme.

Identify Which Shared Concepts Are Worth Stabilizing

The monetary amount appears to be a generic field, with order, billing, and reporting potentially representing prices including tax, actual deductions, and net revenue, respectively. Unifying these into a single “amount” field and sharing a common ORM type would obscure the semantic differences. A standardized currency code and precision rules can be shared, while business fields can still be named according to the specific needs of each module. This involves sharing stable concepts, not just fields that happen to use the same original types.

Identity and permission contexts also require boundaries. Public interfaces accept tenant and operator identities, while owners perform necessary authorization. Callers cannot bypass checks simply because they are in the same process. Internal, trusted calls can have a clear system identity, but should not treat arbitrary user input as a system context. The primary purpose of modularization is maintenance, and code directories should not be treated as a real access isolation.

Regularly check the dependencies and direction of shared directories. If a shared directory imports orders or billing, its internal implementation is no longer a basic, common concept. If it contains a universal service that is executed based on different business switches, it may need to be returned to the process owner. Deletion should not be done at the expense of losing meaning. Two similar but future code segments that will change due to different rules can be temporarily maintained independently.

Data Changes Require Identifying Unseen Consumers

When deleting a field from a payment table, TypeScript import checks may all pass, but the report SQL, maintenance scripts, and data export remain in use. The list of table owners must include read-only consumers. The migration should be performed in the following order: first, provide the new query or field; then, migrate the read; then, stop the old write; and finally, delete. The absence of code dependencies does not mean the absence of data dependencies.

If reports directly connect to tables, it acknowledges controlled coupling and specifies the stable semantics and change notification methods. For high-frequency reports, a dedicated read model can be maintained, but this introduces latency, rebuilding, and reconciliation responsibilities. All reads should not be converted to network-based event synchronization solely for the sake of module purity, and data replication expiration should not be ignored. A shared database can be a reasonable choice, provided that the write ownership and read-only relationships are clearly defined.

The test fixture is also a consumer. The caller directly inserts into the billing internal table, which will fail during storage migration, potentially even creating a state where production does not occur. Providing a public test factory or preparing data for legal testing allows direct operation on the table, while minimizing the need for exclusive test storage. This approach makes testing easier and balances the need for boundary responsibility, preventing the fixture from becoming a permanent backdoor for all modules to bypass rules.

Gradually Migrate Existing Code, Rather Than Rewriting It All at Once

First, identify and freeze the current illegal imports and cross-table writes, preventing any new ones. Then, choose the boundary migration that experiences the most frequent changes. If immediate clearing of all historical issues is required, the team could make the checks meaningless by expanding the allowed list. Each temporary exception marker should have an owner, a reason, and an exit condition, and the exception cannot be indefinitely inherited.

When wrapping existing out-of-bounds functions into genuine public capabilities, check if you’re simply renaming a generic interface. If the entry point still allows callers to submit arbitrary field values, the rules remain external. You can start narrowing down from a specific action, such as canceling, confirming payment, or releasing a reservation, and then migrate the responsibility to the caller. Use real-world test results at each step to avoid the situation where only the import path changes, but the underlying behavior remains completely unchanged.

Regarding the benefits of module boundaries, record the actual modification scope rather than claiming a percentage of decoupling. A change in an internal column name only affects the owner and the controlled adapter, indicating that the boundary is effective. A change in a business contract that affects multiple consumers is reasonable. The goal is not to make every change affect only one place, but to be able to explain which changes should be propagated and which should not.

The module lead also needs to review whether the new capabilities added to the public entry are worth long-term support. Special fields in temporary reports can be placed in the controlled query adapter without expanding the core order API. Record consumers and usage, and when the report is deleted, the unnecessary entry can also be deleted, avoiding the accumulation of compatibility burdens in the public layer that are not owned.

Perform a Single Internal Replacement for Acceptance

The refactoring exercise can be limited to a single change: switching from multiple flat-field columns in the order address to a value object, or from ORM-returned objects in order queries to explicit projection. First, list the expected change locations, and then check the actual diff. It’s normal for internal owners to make changes; if the billing system suddenly requires address conversion, it indicates that it’s relying on a structure that doesn’t belong to it. Checking the scope of the actual changes is more informative than simply counting the number of modules.

It is also important to record the costs associated with the boundaries. If the public methods across modules are too fine-grained, it can lead to complex round trips and state coordination. If they are too coarse, it can hide different responsibilities within a single entry point. During review, use a real-world process diagram to illustrate the call sequence and observe whether the caller needs to understand the internal steps to work. Boundaries should not be overly thick; instead, they should separate stable business relationships from replaceable internal representations.

Attempt to modify the internal representation of the order data, while keeping the public interface unchanged. If significant changes are required to billing, accounts, and pages, this indicates that the vulnerability still exists. Then, check if the order module can be tested independently, and discover deliberately inserted illegal imports.

Whether to decompose into services in the future depends on factors such as independent scalability, deployment frequency, or team boundaries. Well-designed, modular monoliths provide flexibility, but pre-deciding on a specific decomposition strategy is not always advisable. It primarily serves to maintain the current system’s understandability and change safety.

Conducting a mock split also has value, but it’s not necessary to actually deploy microservices. Instead, identify the calls that need to cross networks, the transactions that must be maintained, the shared queries, and the data that needs to be synchronized. Mutable objects that were previously passed in memory need to be serialized, and exceptions that were previously immediately returned need a protocol. Transactions that were previously submitted as a single unit may require a business state machine. If the benefits of splitting are only “making the directory appear more independent,” these costs are often not justified.

The final boundary of the delivered system should include the public entry point, data ownership, allowed directions, and feedback mechanisms for violating rules. These together answer the question: When modifying the internal implementation of an order, can the engineer determine which parts will inevitably be affected and which parts should not be affected? A single system that can answer this question is often easier to maintain than separate services that only focus on the deployment topology.

References