Domain-Driven Design (DDD) for Web Application

Our company is engaged in the development, support and maintenance of sites of any complexity. From simple one-page sites to large-scale cluster systems built on micro services. Experience of developers is confirmed by certificates from vendors.
Development and maintenance of all types of websites:
Informational websites or web applications
Business card websites, landing pages, corporate websites, online catalogs, quizzes, promo websites, blogs, news resources, informational portals, forums, aggregators
E-commerce websites or web applications
Online stores, B2B portals, marketplaces, online exchanges, cashback websites, exchanges, dropshipping platforms, product parsers
Business process management web applications
CRM systems, ERP systems, corporate portals, production management systems, information parsers
Electronic service websites or web applications
Classified ads platforms, online schools, online cinemas, website builders, portals for electronic services, video hosting platforms, thematic portals

These are just some of the technical types of websites we work with, and each of them can have its own specific features and functionality, as well as be customized to meet the specific needs and goals of the client.

Showing 1 of 1 servicesAll 2065 services
Domain-Driven Design (DDD) for Web Application
Complex
from 2 weeks to 3 months
FAQ
Our competencies:
Development stages
Latest works
  • image_website-b2b-advance_0.png
    B2B ADVANCE company website development
    1215
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1161
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    852
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1043
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    823
  • image_bitrix-bitrix-24-1c_fixper_448_0.png
    Website development for FIXPER company
    815

Domain-Driven Design (DDD) Implementation for Web Application

DDD is a methodology where software architecture reflects the business domain. Code speaks the same language as domain experts. Not "update a record in users table" but "suspend account for policy violation". DDD justified for complex domains — e-commerce with non-trivial pricing rules, financial systems, SaaS with flexible pricing.

Ubiquitous Language

First step — create shared vocabulary with business experts. Terms encoded directly in code.

Bad: updateUserStatus(userId, 1) or setActive(true) Good: customer.activate(), subscription.suspend(reason), order.submit()

Vocabulary documented and maintained as requirements change.

Bounded Context

Large system divided into Bounded Contexts — limited contexts where terms have strictly defined meaning. "Product" in Catalog context is description, photo, SEO. "Product" in Orders context is SKU, price, quantity. "Product" in Inventory context is physical unit with storage location.

┌─────────────────────┐  ┌─────────────────────┐  ┌─────────────────────┐
│   Catalog Context   │  │   Orders Context    │  │ Inventory Context   │
│                     │  │                     │  │                     │
│ Product             │  │ OrderItem           │  │ StockItem           │
│ Category            │  │ Order               │  │ Warehouse           │
│ PriceList           │  │ Customer            │  │ StockMovement       │
└─────────────────────┘  └─────────────────────┘  └─────────────────────┘
         ↑ Anti-Corruption Layer between contexts

Explicit boundaries and mapping between contexts. Context Map documents interaction.

Building Blocks

Entity — object with identity, preserved through attribute changes:

class Order {
  private readonly _id: OrderId;
  private _status: OrderStatus;
  private _items: OrderItem[] = [];
  private _domainEvents: DomainEvent[] = [];

  constructor(id: OrderId, customerId: CustomerId) {
    this._id = id;
    this._status = OrderStatus.Draft;
    this.raise(new OrderCreatedEvent(id, customerId));
  }

  addItem(product: Product, quantity: Quantity): void {
    if (this._status !== OrderStatus.Draft) {
      throw new OrderNotEditableError(this._id);
    }
    if (quantity.isZero()) {
      throw new InvalidQuantityError();
    }

    const existing = this._items.find(i => i.productId.equals(product.id));
    if (existing) {
      existing.increaseQuantity(quantity);
    } else {
      this._items.push(new OrderItem(product.id, product.price, quantity));
    }
  }

  submit(): void {
    this.ensureCanTransitionTo(OrderStatus.Submitted);
    if (this._items.length === 0) throw new EmptyOrderError();
    this._status = OrderStatus.Submitted;
    this.raise(new OrderSubmittedEvent(this._id, this.calculateTotal()));
  }

  get id(): OrderId { return this._id; }
  get total(): Money { return this.calculateTotal(); }
  pullDomainEvents(): DomainEvent[] { /* ... */ }
}

Value Object — object without identity, defined by values. Immutable:

class Money {
  private constructor(
    private readonly _amount: number,
    private readonly _currency: Currency
  ) {
    if (_amount < 0) throw new NegativeAmountError();
  }

  static of(amount: number, currency: Currency): Money {
    return new Money(amount, currency);
  }

  add(other: Money): Money {
    if (!this._currency.equals(other._currency)) {
      throw new CurrencyMismatchError();
    }
    return new Money(this._amount + other._amount, this._currency);
  }

  multiply(factor: number): Money {
    return new Money(Math.round(this._amount * factor * 100) / 100, this._currency);
  }

  equals(other: Money): boolean {
    return this._amount === other._amount && this._currency.equals(other._currency);
  }
}

class Email {
  private constructor(private readonly value: string) {}

  static create(email: string): Email {
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
      throw new InvalidEmailError(email);
    }
    return new Email(email.toLowerCase());
  }
}

Aggregate — cluster of related entities with single entry point (Aggregate Root). External code works only with root:

// Order — Aggregate Root
// OrderItem — part of Order aggregate, not directly accessible
class Order {
  // ...all interaction with items only through Order
  removeItem(productId: ProductId): void { /* ... */ }
  updateQuantity(productId: ProductId, qty: Quantity): void { /* ... */ }
}

Rule: one transaction = one aggregate. Between aggregates — eventual consistency via domain events.

Domain Service — operation not belonging to any entity:

class OrderPricingService {
  constructor(
    private discountRepo: DiscountRepository,
    private taxService: TaxCalculationService
  ) {}

  async calculateTotal(order: Order, customer: Customer): Promise<PricingResult> {
    const discounts = await this.discountRepo.findApplicable(
      customer.segment, order.items
    );

    let subtotal = order.items.reduce(
      (sum, item) => sum.add(item.price.multiply(item.quantity.value)),
      Money.zero(Currency.USD)
    );

    const discountAmount = this.applyDiscounts(subtotal, discounts, customer);
    const taxAmount = await this.taxService.calculate(subtotal, customer.address);

    return new PricingResult(subtotal, discountAmount, taxAmount);
  }
}

Repository — abstraction for aggregate storage access:

interface OrderRepository {
  findById(id: OrderId): Promise<Order | null>;
  findByCustomer(customerId: CustomerId, options?: FindOptions): Promise<Order[]>;
  save(order: Order): Promise<void>;
  delete(id: OrderId): Promise<void>;
}

// Implementation separated from interface (dependency inversion)
class PostgresOrderRepository implements OrderRepository {
  async findById(id: OrderId): Promise<Order | null> {
    const row = await this.db.queryOne(
      'SELECT * FROM orders WHERE id = $1', [id.value]
    );
    return row ? this.toDomain(row) : null;
  }

  private toDomain(row: OrderRow): Order {
    return Order.reconstitute({
      id: OrderId.from(row.id),
      status: OrderStatus[row.status],
      customerId: CustomerId.from(row.customer_id),
      items: row.items.map(this.itemToDomain)
    });
  }
}

Application Layer

Thin layer orchestrating domain objects. Contains no business logic:

class PlaceOrderUseCase {
  async execute(dto: PlaceOrderDto): Promise<PlaceOrderResult> {
    const customer = await this.customerRepo.findById(
      CustomerId.from(dto.customerId)
    );
    if (!customer) throw new CustomerNotFoundError(dto.customerId);

    const order = new Order(OrderId.generate(), customer.id);

    for (const item of dto.items) {
      const product = await this.productRepo.findById(ProductId.from(item.productId));
      order.addItem(product, Quantity.of(item.quantity));
    }

    const pricing = await this.pricingService.calculateTotal(order, customer);
    order.applyPricing(pricing);
    order.submit();

    await this.orderRepo.save(order);
    await this.eventBus.publishAll(order.pullDomainEvents());

    return { orderId: order.id.value, total: order.total };
  }
}

Layered Architecture

Domain Layer          — Entities, Value Objects, Aggregates, Domain Services, Events
Application Layer     — Use Cases, Application Services, DTOs, Ports
Infrastructure Layer  — Repositories (PostgreSQL/Redis), External APIs, Message Brokers
Presentation Layer    — HTTP Controllers, GraphQL Resolvers, CLI Commands

Dependencies flow inward only: Presentation → Application → Domain. Domain depends on nothing.

Implementation Timeline

  • Domain design, Context Map, Ubiquitous Language — 1–2 weeks
  • One Bounded Context with 3–5 aggregates — 3–5 weeks
  • Full system with multiple contexts and integration — 2–4 months