Skip to content

Modular Monoliths and Microservices Code Boundaries and Operational Trade-offs

Modular Monoliths and Microservices Code Boundaries and Operational Trade-offs

Corrected educational edition. Original English publication: 2026-10-14T14:40:03.987+03:00. The Hebrew edition uses its actual publication date, not the English original date. All code examples are runtime-untested; no benchmark or first-hand testing is claimed. English original

Microservices can provide independent deployment and team ownership, but they are not a requirement for a modern scalable application. A monolith is not automatically unmaintainable, and a Kubernetes deployment is not a measure of engineering maturity. The useful question is which boundaries need independent deployment for this product and team. [source 1]

Splitting a system can add API contracts, service networking, distributed tracing and deployment coordination. These costs can be justified, but should be compared with latency, reliability and staffing needs. This article does not claim a first-hand migration or a measured industry reversal. [source 1]

Published case studies need their actual scope. Shopify described componentizing its existing monolith; Basecamp’s account describes continued evolution of a monolithic core, not proof of a return from microservices. The Prime Video discussion concerned a particular audio/video monitoring workload, not the entire streaming platform. These examples support considering modular boundaries, not a universal claim that monoliths are winning. [source 1] [source 2] [source 3]

The Hidden Costs of Microservices

One reason to choose services is organizational independence: teams can own contracts and deploy components separately. There is no universal 500-engineer threshold, and a single repository does not force a single deployment or prevent team ownership. [source 1]

For a smaller team, the overhead of services may exceed their benefits, but that depends on requirements and tooling. Do not infer an organization’s motivation or suitability solely from its headcount. [source 1]

1. Distributed Systems Complexity

An in-process call normally avoids a network hop, but is neither instantaneous nor automatically atomic or safe. It can block, throw, race or perform remote I/O internally. Crossing a service boundary adds transport and partial-failure concerns such as:

  • Network latency: Cascading API calls add up quickly.
  • Partial failures: What happens if Service A succeeds, Service B succeeds, but Service C times out?
  • Data consistency: a saga coordinates a sequence of local transactions and compensations; it is not a single distributed ACID transaction. A shared-database transaction can be simpler where all participating operations truly share the same transaction context. [source 1]

2 Local development and coordination costs [source 1]

A multi-service development environment may require containers, mocks, shared test environments and coordinated changes. Its memory use and setup time vary widely. The original 30 GB figure and three-repository scenario are illustrative, not benchmarks or universal requirements. Modular monoliths also need fixtures, databases and reliable tests. [source 1]

Enter the Modular Monolith

A modular monolith keeps a coordinated deployment unit while organizing code into explicit domain modules and public contracts. It may run multiple instances or worker processes. The important distinction is deployment and domain coupling, not a rule that there can be only one binary or process. [source 1]

In-process contracts can avoid serialization and network overhead at module boundaries. Type safety depends on the language and tooling; transactional integrity depends on database usage. Preserve module ownership and interfaces, but do not promise zero latency or effortless later extraction. [source 1]

Let's look at how you can enforce these boundaries in a modern backend system.

Designing Boundaries in Code

Consider Users, Orders and Inventory. The first runtime-untested fragment deliberately demonstrates direct cross-domain model imports. Its stock read/check is not a safe reservation under concurrency and it omits validation and transactional handling; it is an anti-pattern, not runnable application code.

// Runtime-untested ANTI-PATTERN. Domain models are application-specific.
import { UserModel } from '../users/user.model';
import { InventoryModel } from '../inventory/inventory.model';

export class OrderService {
  async createOrder(userId: string, productId: string) {
    const user = await UserModel.findById(userId);
    const item = await InventoryModel.findById(productId);
    if (!user || !item) throw new Error('Not found');
    if (item.stock < 1) throw new Error('Out of stock');
    // This check is NOT an atomic reservation; another request can race it.
    // No persistence or transaction implementation is supplied.
  }
}

One modular design permits communication only through public module interfaces. Enforce that rule in code and reviews; interfaces do not themselves prevent runtime access to another table. The next untested sketch makes a shared transaction contract explicit, but leaves all persistence, authorization, concurrency and idempotency implementations to the application.

// Runtime-untested contract sketch, NOT a transaction implementation.
// These public interfaces are supplied by their respective modules.
export interface CheckoutTransaction {
  users: { assertCanOrder(userId: string): Promise<void> };
  inventory: {
    reserveStock(productId: string, quantity: number): Promise<boolean>;
  };
  orders: {
    create(userId: string, productId: string, requestKey: string): Promise<string>;
  };
}
export interface UnitOfWork {
  // Contract: all adapters use ONE database transaction; errors roll back.
  // The application must implement this contract and verify its semantics.
  run<T>(work: (tx: CheckoutTransaction) => Promise<T>): Promise<T>;
}
export class OrderService {
  constructor(private readonly unitOfWork: UnitOfWork) {}
  async createOrder(userId: string, productId: string, requestKey: string) {
    return this.unitOfWork.run(async (tx) => {
      await tx.users.assertCanOrder(userId);
      // Implementation must reserve stock atomically, not read-then-write.
      const reserved = await tx.inventory.reserveStock(productId, 1);
      if (!reserved) throw new Error('Out of stock');
      // Application must implement replay/uniqueness semantics for requestKey.
      return tx.orders.create(userId, productId, requestKey);
    });
  }
}

The interface call itself is local, but its implementation may access a remote database and can fail. A single atomic order-and-reservation operation requires the same database transaction, an atomic stock update or appropriate locking, rollback on failure and an idempotency strategy for retries. No microsecond result or working transaction implementation is supplied here.

Enforcing Architecture with Tooling

Architectural boundaries can erode under delivery pressure in either monoliths or distributed systems. Automated checks make selected rules visible and repeatable; they are not evidence of why the entire industry chose services. [source 1] [source 2]

Lint and architecture tests can enforce selected dependency rules when correctly configured and required in CI. They do not cover all dynamic behavior, reflection, SQL access or runtime authorization. [source 1] [source 2]

1. Language-Level Workspaces and Package Managers

Workspace and visibility mechanisms differ across languages and build tools. In TypeScript, pnpm workspaces organize packages but do not by themselves enforce architectural isolation. The Nx example requires separately recognized projects, assigned tags, the Nx ESLint plugin and a CI lint target. The following flat-config fragment is runtime-untested and must be adapted to the installed Nx/ESLint versions. [source 1]

// Runtime-untested eslint.config.mjs fragment for an Nx workspace.
// Requires compatible @nx/eslint-plugin + ESLint and Nx project configuration.
// Assign tags to DISTINCT projects in their project configuration:
// orders:        ["domain:orders"]
// inventory-api: ["domain:inventory-api"]
// inventory-impl:["domain:inventory"]
// shared:        ["domain:shared"]
import nx from '@nx/eslint-plugin';

export default [
  ...nx.configs['flat/base'],
  ...nx.configs['flat/typescript'],
  ...nx.configs['flat/javascript'],
  {
    files: ['**/*.ts', '**/*.tsx', '**/*.js', '**/*.jsx'],
    rules: {
      '@nx/enforce-module-boundaries': ['error', {
        allow: [],
        depConstraints: [
          {
            sourceTag: 'domain:orders',
            onlyDependOnLibsWithTags: ['domain:shared', 'domain:inventory-api'],
          },
          {
            sourceTag: 'domain:inventory',
            onlyDependOnLibsWithTags: ['domain:shared', 'domain:inventory-api'],
          },
          {
            sourceTag: 'domain:inventory-api',
            onlyDependOnLibsWithTags: ['domain:shared'],
          },
          {
            sourceTag: 'domain:shared',
            onlyDependOnLibsWithTags: ['domain:shared'],
          },
        ],
      }],
    },
  },
];
// Require lint in CI. This does not govern SQL or intra-project private paths.

With orders, inventory-api and inventory-impl as distinct tagged Nx projects, a forbidden cross-project import can fail the required lint check. That is not an automatic TypeScript compiler error. Internal paths within a single project or overly broad public exports need additional import/export rules and tests. [source 1]

2. Architecture Verification Tests

ArchUnit can inspect compiled Java class dependencies; NetArchTest addresses .NET assemblies. The following runtime-untested Java/JUnit example supplies its imports and importedClasses and checks dependencies, which is broader than only method/field accesses. It still does not inspect SQL text or enforce runtime data permissions. [source 1]

// Runtime-untested Java/JUnit 5 example; requires ArchUnit + JUnit dependencies.
import com.tngtech.archunit.core.domain.JavaClasses;
import com.tngtech.archunit.core.importer.ClassFileImporter;
import com.tngtech.archunit.lang.ArchRule;
import org.junit.jupiter.api.Test;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses;

class DomainArchitectureTest {
    @Test
    void ordersMustNotDependOnUsersInternals() {
        JavaClasses importedClasses = new ClassFileImporter()
            .importPackages("com.sysseder");
        ArchRule rule = noClasses()
            .that().resideInAPackage("com.sysseder.orders..")
            .should().dependOnClassesThat()
            .resideInAPackage("com.sysseder.users.internal..");
        rule.check(importedClasses);
    }
}
// Ensure compiled application classes are on the test classpath.
// This rule does not inspect SQL strings, reflection or runtime authorization.

When Should You Microservice?

Choosing a modular monolith isn't an anti-cloud or anti-scale stance—it's a pragmatic recognition of operational trade-offs. However, microservices still make sense under specific circumstances:

  • Different resource profiles: a compute-heavy video or inference component may benefit from scaling separately from ordinary request handling. The appropriate instance counts require measurement; thousands of GPUs versus two VMs was only an illustrative contrast.
  • Independent Organizational Velocity: When you have independent engineering groups operating in different timezones with distinct release lifecycles.
  • Polyglot Requirements: When a specific domain fundamentally requires a language ecosystem other than your main stack (e.g., Python for data analytics embedded in a Go web app).

Good module boundaries can make later extraction more manageable, but it is not trivial. Network failures, serialization, authentication, API versioning, data migration, transaction redesign, observability and rollout strategy become new work. Evaluate extraction when its benefits justify those costs. [source 1] [source 2]

Conclusion

There is no evidence here that monoliths are fastest or most resilient for 95% of applications. A modular monolith can be a practical starting point when independent deployment is not needed, while services may fit other constraints. Compare both against your team size, failure isolation, release cadence, workload and data boundaries. [source 1] [source 2]

Before you spin up another Kubernetes cluster or design an event-driven system across a dozen repos, step back and ask: Could this just be a module inside a solid, modern monolithic core?


What's your take? Has your team transitioned back to a monolithic design, or are microservices still serving you well? Let me know in the comments below or reach out on Twitter/X at @sysseder!

Primary sources for corrections

Post a Comment

Previous Post Next Post