🏗️ Architecture

Modular Monolith

Modular Monolith

A Modular Monolith is an architecture that combines the modularity of microservices with the simplicity of a monolith. By maintaining clear module boundaries within a single deployment unit, it allows a gradual transition to microservices.

📖 Detailed Explanation

Modular Monolith is an architecture that keeps the advantages of the traditional monolithic approach (simple deployment, local function calls) while adopting the advantages of microservices (module independence, clear boundaries). It is also called a "well-designed monolith."

Architecture Comparison

Characteristics Traditional Monolith Modular Monolith Microservices
Deployment Unit 1 1 N (per service)
Module Boundaries None or weak Clear Physical separation
Communication Method Function calls Calls through interfaces Network (HTTP/gRPC)
Database Shared Logical separation (schema) Physical separation
Operational Complexity Low Low High

Core Principles

💻 Code Example

Project structure

src/
├── modules/
│   ├── catalog/                 # 상품 카탈로그 모듈
│   │   ├── api/                 # Public API (다른 모듈이 사용)
│   │   │   ├── CatalogApi.ts
│   │   │   └── types.ts
│   │   ├── domain/
│   │   │   ├── Product.ts
│   │   │   └── Category.ts
│   │   ├── infrastructure/
│   │   │   └── CatalogRepository.ts
│   │   └── index.ts             # 모듈 진입점
│   │
│   ├── orders/                  # 주문 모듈
│   │   ├── api/
│   │   │   ├── OrderApi.ts
│   │   │   └── types.ts
│   │   ├── domain/
│   │   │   ├── Order.ts
│   │   │   └── OrderItem.ts
│   │   ├── application/
│   │   │   └── PlaceOrderUseCase.ts
│   │   ├── infrastructure/
│   │   │   └── OrderRepository.ts
│   │   └── index.ts
│   │
│   └── payments/                # 결제 모듈
│       ├── api/
│       ├── domain/
│       ├── infrastructure/
│       └── index.ts
│
├── shared/                      # 공유 인프라 (최소화)
│   ├── database/
│   └── messaging/
│
└── main.ts                      # 애플리케이션 진입점

Defining the Module Public API

// modules/catalog/api/CatalogApi.ts
// 다른 모듈이 사용할 수 있는 공개 인터페이스

export interface ProductDTO {
  id: string;
  name: string;
  price: number;
  stockQuantity: number;
}

export interface CatalogApi {
  getProduct(productId: string): Promise<ProductDTO | null>;
  getProducts(productIds: string[]): Promise<ProductDTO[]>;
  checkAvailability(productId: string, quantity: number): Promise<boolean>;
  reserveStock(productId: string, quantity: number): Promise<boolean>;
}

// modules/catalog/index.ts (모듈 진입점)
// 외부에 공개할 것만 export
export type { CatalogApi, ProductDTO } from './api/CatalogApi';
export { createCatalogModule } from './CatalogModule';

Module Implementation

// modules/catalog/CatalogModule.ts
import { CatalogApi, ProductDTO } from './api/CatalogApi';
import { ProductRepository } from './infrastructure/ProductRepository';

export function createCatalogModule(db: Database): CatalogApi {
  const repository = new ProductRepository(db);

  return {
    async getProduct(productId: string): Promise<ProductDTO | null> {
      const product = await repository.findById(productId);
      if (!product) return null;

      // Domain → DTO 변환 (내부 구현 숨김)
      return {
        id: product.id,
        name: product.name,
        price: product.price.amount,
        stockQuantity: product.stock.quantity,
      };
    },

    async getProducts(productIds: string[]): Promise<ProductDTO[]> {
      const products = await repository.findByIds(productIds);
      return products.map(p => ({
        id: p.id,
        name: p.name,
        price: p.price.amount,
        stockQuantity: p.stock.quantity,
      }));
    },

    async checkAvailability(productId: string, quantity: number): Promise<boolean> {
      const product = await repository.findById(productId);
      return product ? product.stock.isAvailable(quantity) : false;
    },

    async reserveStock(productId: string, quantity: number): Promise<boolean> {
      const product = await repository.findById(productId);
      if (!product || !product.stock.isAvailable(quantity)) {
        return false;
      }
      product.stock.reserve(quantity);
      await repository.save(product);
      return true;
    }
  };
}

Inter-Module Communication (Through Interfaces)

// modules/orders/application/PlaceOrderUseCase.ts
import { CatalogApi } from '../../catalog'; // 모듈 public API만 import
import { OrderRepository } from '../infrastructure/OrderRepository';
import { Order } from '../domain/Order';

export class PlaceOrderUseCase {
  constructor(
    private catalogApi: CatalogApi,  // 인터페이스에 의존
    private orderRepository: OrderRepository
  ) {}

  async execute(input: PlaceOrderInput): Promise<PlaceOrderResult> {
    // 1. 상품 정보 조회 (Catalog 모듈 API 통해)
    const products = await this.catalogApi.getProducts(
      input.items.map(i => i.productId)
    );

    // 2. 재고 확인
    for (const item of input.items) {
      const available = await this.catalogApi.checkAvailability(
        item.productId,
        item.quantity
      );
      if (!available) {
        throw new Error(`Product ${item.productId} out of stock`);
      }
    }

    // 3. 주문 생성 (Order 모듈 내부 도메인 로직)
    const order = Order.create({
      customerId: input.customerId,
      items: input.items.map(item => {
        const product = products.find(p => p.id === item.productId)!;
        return {
          productId: item.productId,
          productName: product.name,
          quantity: item.quantity,
          unitPrice: product.price,
        };
      }),
    });

    // 4. 재고 예약 (Catalog 모듈 API 통해)
    for (const item of input.items) {
      await this.catalogApi.reserveStock(item.productId, item.quantity);
    }

    // 5. 주문 저장
    await this.orderRepository.save(order);

    return { orderId: order.id, total: order.calculateTotal() };
  }
}

Module Assembly (Composition Root)

// main.ts
import { createCatalogModule } from './modules/catalog';
import { createOrderModule } from './modules/orders';
import { createPaymentModule } from './modules/payments';
import { Database } from './shared/database';

async function bootstrap() {
  const db = new Database(process.env.DATABASE_URL);

  // 모듈 생성 (의존성 주입)
  const catalogApi = createCatalogModule(db);
  const paymentApi = createPaymentModule(db);
  const orderApi = createOrderModule(db, catalogApi, paymentApi);

  // Express 라우터 설정
  const app = express();
  app.use('/api/catalog', createCatalogRoutes(catalogApi));
  app.use('/api/orders', createOrderRoutes(orderApi));
  app.use('/api/payments', createPaymentRoutes(paymentApi));

  app.listen(3000);
}

bootstrap();

Module Boundary Verification (Architecture Tests)

// tests/architecture.test.ts
import { filesOfProject } from 'ts-arch';

describe('Module Boundaries', () => {
  it('Orders module should not access Catalog internals', async () => {
    const rule = filesOfProject()
      .inFolder('modules/orders')
      .shouldNot()
      .dependOnFiles()
      .inFolder('modules/catalog/domain')
      .inFolder('modules/catalog/infrastructure');

    await expect(rule).toPassAsync();
  });

  it('Modules should only import from public API', async () => {
    const rule = filesOfProject()
      .inFolder('modules/orders')
      .should()
      .onlyDependOn()
      .filesMatching('modules/catalog/index.ts')
      .or()
      .filesMatching('modules/catalog/api/*');

    await expect(rule).toPassAsync();
  });
});

💬 Real-world conversation examples

👨‍💼 CTO

"I want to move to microservices, but our team is small and I'm worried. Can we handle the operational complexity?"

👩‍💻 Architect

"Let's start with a Modular Monolith. If you define the module boundaries well, you can later split off only the modules you need as microservices once the team grows. For now, you reduce the operational burden with a single deployment while preparing for the transition to microservices."

👨‍💻 Junior developer

"Wouldn't it be faster to JOIN the product table in the order module and query it?"

👩‍💻 Senior developer

"That's a module boundary violation. Only Catalog should access the Catalog module's DB. If there's a JOIN when we later split Catalog into a separate service, the split becomes impossible. Fetch the data through CatalogApi."

👨‍💼 PM

"Does this order feature development require work from the payments team?"

👩‍💻 Backend developer

"No, the PaymentApi interface is already defined, so our Orders module can develop independently. Because the module boundaries are clear, dependencies between teams are minimized."

⚠️ Cautions

Beware of boundary violations: If the module boundaries break down, it simply becomes a monolith. Do not import another module's internal code or access its DB directly. Continuously verify the boundaries with Architecture Tests.

No circular dependencies: A circular dependency like Module A → Module B → Module A makes module separation impossible. Keep the dependency direction one-way.

Minimize the shared kernel: If the code in the shared folder grows, module independence weakens. Share only the infrastructure code that is truly necessary.

Tip: Using DDD's Bounded Context as the module boundary naturally leads to good module design. Analyze the domain with Event Storming, then define the modules.

🔗 Related Terms

📚 Learn More