Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close
    Lesson1 / 15

    Module 1 · Boundaries and Communication · Lesson 1 of 15

    Modular Monolith vs Microservices: Boundaries, Data Ownership and When to Split

    Usually choose a modular monolith first. Choose microservices when independent releases, scaling or isolation justify the extra cost, and draw boundaries around business capabilities and their data.

    By the end of this lesson, you can explain where Ordering should end, where Billing should begin, and what changes when they stop sharing one application.

    Modular monolith vs microservices: what changes?

    A modular monolith is one deployable application whose modules own their tables and talk only through public contracts. For example, Ordering and Billing can run in the same ASP.NET Core application without reading each other's tables or using each other's implementation classes.

    A microservices architecture divides the application into services that can be developed, tested, deployed and versioned independently. Each service owns a business capability and the data needed to carry it out. A business capability is something the business does, such as accepting orders or issuing invoices.

    The important difference is not the number of projects in your solution. It is whether you can release one part without deploying the others.

    ChoiceModular monolithMicroservices
    DeploymentModules ship as one applicationServices can ship independently
    CommunicationUsually ordinary method calls inside the applicationCalls or messages cross process boundaries
    ScalingYou usually run more copies of the whole applicationYou can run more copies of one service
    Operational workFewer separately running partsMore deployments, connections and failures to manage

    For example, an Ordering change in a modular monolith means releasing the application that also contains Billing. With microservices, Ordering can be released while Billing keeps running its current version.

    The mistake to avoid. Do not equate a monolith with tangled code. One deployment can contain well-separated modules; several deployments can still be tightly coupled.

    In an interview, say: “I usually start with a modular monolith. Microservices make sense when independent releases, scaling or isolation solve a concrete problem; otherwise they add network failures, consistency problems and operational cost too early.”

    Where should a service boundary go?

    Start with business decisions, not a list of tables. Ask who owns each decision and which rules must remain consistent together.

    A bounded context is the part of the business where one model, with its own terms and rules, applies. The same real-world thing can look different in different contexts.

    For example, Ordering needs an order's items, prices and status; Billing needs only what an invoice requires, not Ordering's whole order class.

    Suppose the rule is: “An accepted order's total must equal the sum of its accepted line prices.” Keep that decision and the data required to enforce it together in Ordering. Splitting totals and lines into separate services would turn one local rule into a coordination problem.

    A different rule, “Every accepted order must eventually receive an invoice”, can allow a delay: Ordering publishes an OrderPlaced event with the facts Billing needs, instead of giving Billing access to its tables.

    flowchart TD
        O["Ordering"] -->|"owns"| R["Acceptance and order totals"]
        O -->|"announces"| E["OrderPlaced"]
        E -->|"informs"| B["Billing"]
        B -->|"owns"| I["Invoice decisions"]

    A technical-layer split, such as an API service, a business-logic service and a data-access service, usually makes one business change cross several services. An entity-per-service split can cause the same problem: Order, OrderLine and OrderTotal services may constantly need each other.

    These are judgments, not a formula: Microsoft's domain analysis guidance explains why boundaries need business knowledge and may change as requirements change.

    The mistake to avoid. “One thing per service” does not mean one table or one class per service. A useful boundary contains a coherent business responsibility, including the rules it must enforce.

    In an interview, say: “A service ends at a business capability or bounded context, where terms and rules mean one thing. It owns its data and ships alone. I avoid boundaries where routine changes need constant coordination with other services.”

    Why should each module or service own its data?

    Each module or service owns its tables. Other parts request an operation through its public interface or receive information it publishes.

    If Billing directly updates Ordering's tables, Ordering cannot safely change their structure without coordinating with Billing. Sharing writable tables undermines independent releases.

    Separate ownership does not require separate hardware. Microsoft's data considerations for microservices says services can safely share a physical database server; the problems start when they share a schema or the same tables. A schema is a named grouping of database objects that can help separate ownership and permissions.

    The next example uses SQLite, a small database engine, in memory. Ordering owns an Orders table in one database; Billing owns an Invoices table in another.

    The public event is the contract: the agreed data shape passed across the boundary. Placing an order returns an OrderPlaced value, and the application passes it straight to Billing; there is no messaging system.

    Before reading the explanation below, predict how many invoices exist right after Ordering stores its order.

    C#
    using Microsoft.Data.Sqlite;
    using Contracts;
    
    using var orderingDatabase = new SqliteConnection("Data Source=:memory:");
    using var billingDatabase = new SqliteConnection("Data Source=:memory:");
    orderingDatabase.Open();
    billingDatabase.Open();
    
    var ordering = new Ordering.OrderModule(orderingDatabase);
    var billing = new Billing.BillingModule(billingDatabase);
    
    OrderPlaced placed = ordering.PlaceOrder(42, 2500);
    Console.WriteLine($"Orders stored: {ordering.OrderCount()}");
    Console.WriteLine($"Invoices before handling: {billing.InvoiceCount()}");
    billing.Handle(placed);
    Console.WriteLine($"Invoices after handling: {billing.InvoiceCount()}");
    
    namespace Contracts
    {
        public sealed record OrderPlaced(int OrderId, long TotalCents);
    }
    
    namespace Ordering
    {
        internal sealed class OrderModule
        {
            private readonly SqliteConnection database;
    
            public OrderModule(SqliteConnection database)
            {
                this.database = database;
                using var command = database.CreateCommand();
                command.CommandText = """
                    CREATE TABLE Orders (
                        Id INTEGER PRIMARY KEY,
                        TotalCents INTEGER NOT NULL
                    );
                    """;
                command.ExecuteNonQuery();
            }
    
            public OrderPlaced PlaceOrder(int id, long totalCents)
            {
                if (totalCents <= 0)
                    throw new ArgumentOutOfRangeException(nameof(totalCents));
    
                using var command = database.CreateCommand();
                command.CommandText =
                    "INSERT INTO Orders (Id, TotalCents) VALUES ($id, $total);";
                command.Parameters.AddWithValue("$id", id);
                command.Parameters.AddWithValue("$total", totalCents);
                command.ExecuteNonQuery();
                return new OrderPlaced(id, totalCents);
            }
    
            public long OrderCount()
            {
                using var command = database.CreateCommand();
                command.CommandText = "SELECT COUNT(*) FROM Orders;";
                return (long)command.ExecuteScalar()!;
            }
        }
    }
    
    namespace Billing
    {
        internal sealed class BillingModule
        {
            private readonly SqliteConnection database;
    
            public BillingModule(SqliteConnection database)
            {
                this.database = database;
                using var command = database.CreateCommand();
                command.CommandText = """
                    CREATE TABLE Invoices (
                        OrderId INTEGER PRIMARY KEY,
                        TotalCents INTEGER NOT NULL
                    );
                    """;
                command.ExecuteNonQuery();
            }
    
            public void Handle(OrderPlaced placed)
            {
                using var command = database.CreateCommand();
                command.CommandText = """
                    INSERT INTO Invoices (OrderId, TotalCents)
                    VALUES ($orderId, $total);
                    """;
                command.Parameters.AddWithValue("$orderId", placed.OrderId);
                command.Parameters.AddWithValue("$total", placed.TotalCents);
                command.ExecuteNonQuery();
            }
    
            public long InvoiceCount()
            {
                using var command = database.CreateCommand();
                command.CommandText = "SELECT COUNT(*) FROM Invoices;";
                return (long)command.ExecuteScalar()!;
            }
        }
    }
    Output
    Orders stored: 1
    Invoices before handling: 0
    Invoices after handling: 1

    Needs the package Microsoft.Data.Sqlite 10.0.12. Built and run with it: the output above is what the program really printed.

    Creating an event value does not run another module's work: Billing has no invoice until the application calls billing.Handle(placed). Billing then writes its own row from the contract's values. Neither module queries the other's table.

    Both modules share a process, but these database writes do not share a transaction. If execution stops before Handle, the order remains without an invoice. Continue with delivery guarantees and the dual-write problem before treating this handoff as reliable delivery.

    The mistake to avoid. Placing databases on separate servers is not what establishes data ownership; controlling access and changes does.

    In an interview, say: “Each service owns its data so it can control schema changes and business rules. Shared writable tables couple releases. Separate owned databases or schemas can share a physical server; separate hardware is not required.”

    What does splitting cost, and what is a distributed monolith?

    Moving Billing into a separate service turns a method call into communication across a network. That changes the failure cases, not just the calling syntax.

    Every call now pays network latency: the time a message takes to cross the network. Calls can also fail partway: Ordering might accept an order while Billing is unavailable.

    No transaction spans separate service databases automatically. Two-phase commit, a distributed transaction with a prepare step and a commit step, is usually avoided across services.

    Instead, each service commits locally. A saga coordinates the local steps and uses compensating business actions when a later step fails. For example, a failed fulfillment step might require cancelling an accepted order.

    Publishing the resulting events must also be reliable. An outbox stores an outgoing event in the same database transaction as the business change, so it can be published afterward. Microsoft's transactional outbox guide explains this approach. Later lessons cover sagas and the outbox.

    For example, Ordering may show “accepted” while Billing still shows “invoice pending.” Here, eventual consistency means allowing Billing to catch up after Ordering commits, rather than requiring both to change at once. That is a business-visible state to design, not merely a technical inconvenience.

    Contracts must stay compatible, or each Ordering release forces a Billing release. Operational work grows too: more applications to deploy and monitor, failures to investigate across them, and connections and permissions to manage. REST vs gRPC vs events continues with the communication choices.

    A distributed monolith is split into separate services that still cannot change or run on their own. They must be released together, or one request needs all of them to work. You pay the costs of a distributed system without getting independence. Warning signs include:

    • Ordering and Billing both write the same tables.
    • Every release requires both services to deploy together.
    • One request must synchronously pass through a long chain of services before it can succeed.

    A synchronous call, where the caller waits for the result, is not proof of a distributed monolith on its own. The question is whether services must keep waiting for each other, so that none can be changed, released or kept running alone.

    The mistake to avoid. Moving tightly coupled modules onto different servers does not remove their coupling. It can add network failures to dependencies that were already difficult to change.

    In an interview, say: “Across services there is no shared transaction. I avoid two-phase commit and use local transactions, a saga with compensation, an outbox for reliable publication, and eventual consistency. A distributed monolith pays those costs but still needs coordinated releases or long synchronous chains.”

    Should services share a library?

    Prefer a small, versioned contract library over a shared implementation library. Versioned means that a service chooses which released package version it uses rather than automatically receiving every change.

    In the example, OrderPlaced is a reasonable candidate for a contract package. Ordering's price rules and Billing's invoice rules are not.

    Version numbers alone do not make a shared contract compatible; message contracts, versioning and tolerant readers covers the rules.

    The mistake to avoid. Do not share business logic or the classes that map to a service's database tables merely to remove duplicate-looking code. The duplication may represent different business meanings that should evolve separately.

    In an interview, say: “I share only small, versioned contracts, never business logic or classes mapped to tables, because shared implementation couples releases. Contract packages still need compatible changes, since services run different versions.”

    How do you enforce modular monolith boundaries in .NET?

    Use separate assemblies for real access boundaries. An assembly is the executable or DLL produced by compiling source files. A namespace groups names; it does not prevent another namespace in the same assembly from accessing implementation code.

    A practical solution can contain Ordering, Billing, Contracts and a host application. Keep implementation types internal, expose small public entry points, and let the host connect the modules. C#'s internal access rule normally restricts access to the same assembly. InternalsVisibleTo can open internal members to named assemblies, so use it sparingly.

    The SQLite example uses namespaces only to fit in one file; it shows data ownership, not compiler-enforced separation.

    An architecture test checks whether code follows a structural rule, such as “Ordering must not reference Billing.” Libraries such as NetArchTest or ArchUnitNET can help you write these checks. Make violations fail a test, and run these tests in continuous integration (CI), the automated build and test of every change.

    The mistake to avoid. Namespaces do not enforce a boundary, and a check that can never fail proves nothing. A useful check must reject a forbidden dependency, and code checks cannot replace database access controls.

    In an interview, say: “I use separate assemblies, internal implementations, small public contracts and owned tables. Architecture tests fail CI on forbidden dependencies. Namespaces are not access boundaries, and assembly-reference tests do not enforce database permissions.”

    When should you extract a module into a microservice?

    Ask which measurable problem the split will solve. “We may grow” is not enough to choose the added failure cases and operational work.

    Use concrete evidence:

    NeedEvidence worth investigating
    Independent releasesBilling changes repeatedly wait for unrelated Ordering releases
    Independent scalingBilling has a measured workload that needs a different amount of capacity
    Fault isolationBilling failures must not stop order acceptance, and the workflow can tolerate delayed invoicing
    ComplianceA specific requirement demands tighter separation of data access or operations
    Team autonomySeparate teams own Ordering and Billing and are repeatedly blocked by each other's changes

    A separate process can help, but not if Ordering must wait for Billing on every request.

    Before extraction, establish the module's contract and data ownership inside the monolith. Then compare the expected benefit against the cost of running it separately. Extract one capability and verify the result rather than committing to a system-wide split immediately. This step-by-step approach is called the strangler fig pattern; migrating a monolith shows how to do it.

    For example, if Billing release delays are the problem, measure whether Billing can actually release without Ordering afterward. More deployed services are not evidence that the problem was solved.

    The mistake to avoid. Do not treat a request to “split the monolith” as a complete requirement. Without a measurable goal, the team cannot tell whether the extra complexity bought anything useful.

    In an interview, say: “I first ask which measurable problem the split must solve. I modularize and settle data ownership first, then extract one capability at a time with the strangler fig pattern, and measure after each step whether releases, scaling, isolation or team autonomy improved enough to pay for the extra operations.”

    Check yourself

    Ordering and Billing must deploy together because both write the Orders table. What is the best first step?

    A Put each service on a different physical database server without changing table access.
    B Rename both services so that each one matches the SQL table it writes.
    C Replace every method call with an HTTP call but keep the shared table writes.
    D Give the table one owner and replace the other module's writes with a contract.
    Show answer

    Correct answer: D

    One owner can control the table's rules and schema changes. Changing servers, names or call syntax does not remove the shared-write dependency.

    Ordering stores an order, then calls Billing in the same application process. Billing fails before saving its invoice. What can you conclude?

    A The order is rolled back automatically, because both modules run in the same process.
    B The invoice still exists, because a local method call cannot fail halfway.
    C The order stays stored unless both writes were placed in one shared transaction.
    D The modules must now become separate microservices so each can fail alone.
    Show answer

    Correct answer: C

    Sharing a process does not create a shared transaction. The transaction arrangement determines which writes commit or roll back together.

    Going deeper

    A modular monolith can deliberately share one database transaction across modules when both operations must succeed together. That is a design choice, not a consequence of sharing a process, and it makes a later extraction harder.

    With Entity Framework Core, changes in one SaveChanges call use a transaction by default when the provider supports transactions. Separate calls on separate contexts do not become one transaction unless the contexts share both the database connection and the database transaction.

    Sources

    Sign in to mark lessons done and keep your place in the course.Sign in

    Checked before publishing: links opened, reviewed while it was written and read in full. How lessons are checked

    Updated 1 Dec 2026 ·