Engineering
System Design & Architecture Simplified
Date Published

Goal: Translate raw domain models into a maintainable, decoupled system structure.
Core Principles
-
Separation of Concerns (SoC)
Different parts of the system handle different responsibilities.
Business logic should not know if data came from HTTP, GraphQL, or CLI. -
Dependency Rule
Dependencies must point inward toward the domain.- Inner layers: entities + use cases (pure business rules).
- Outer layers: databases, web frameworks, messaging.
- Inner layers talk outward only through interfaces/contracts.
-
Infrastructure Is a Detail
PostgreSQL, MongoDB, queues, and web frameworks are tools—not the core application.
Layers
- Domain: Entities and business rules.
- Application: Use cases that orchestrate work.
- Infrastructure: Database, web, messaging adapters.
Example: E-Commerce Order System
1. Repository Interfaces (Contracts)
1from abc import ABC, abstractmethod2from typing import Optional3from domain import Order, Product4 5class OrderRepository(ABC):6 @abstractmethod7 def save(self, order: Order) -> None:8 ...9 10 @abstractmethod11 def get_by_id(self, order_id: str) -> Optional[Order]:12 ...13 14class ProductRepository(ABC):15 @abstractmethod16 def get_by_id(self, product_id: str) -> Optional[Product]:17 ...
2. Use Case (Application Logic)
1import uuid2 3class CreateOrderUseCase:4 def __init__(5 self,6 order_repo: OrderRepository,7 product_repo: ProductRepository8 ):9 self.order_repo = order_repo10 self.product_repo = product_repo11 12 def execute(self, customer_id: str, items_to_buy: list[dict]) -> Order:13 order = Order(14 order_id=str(uuid.uuid4()),15 customer_id=customer_id16 )17 18 for item in items_to_buy:19 product = self.product_repo.get_by_id(item["product_id"])20 if not product:21 raise ValueError(f"Product '{item['product_id']}' not found.")22 23 order.add_item(24 product=product,25 quantity=item["quantity"]26 )27 28 self.order_repo.save(order)29 return order
3. In-Memory Adapter (Infrastructure)
1class InMemoryOrderRepository(OrderRepository):2 def __init__(self):3 self._storage: dict[str, Order] = {}4 5 def save(self, order: Order) -> None:6 self._storage[order.order_id] = order7 8 def get_by_id(self, order_id: str) -> Optional[Order]:9 return self._storage.get(order_id)
4. Wiring Everything Together
1order_repository = InMemoryOrderRepository()2product_repository = ... # Postgres, mock, etc.3 4use_case = CreateOrderUseCase(5 order_repo=order_repository,6 product_repo=product_repository7)8 9new_order = use_case.execute(10 customer_id="cust_123",11 items_to_buy=[{"product_id": "prod_999", "quantity": 2}]12)13 14print(f"Order {new_order.order_id} created successfully!")
Why This Design Pays Off
- Fast testing: Use
InMemoryOrderRepositorywithout PostgreSQL or Docker. - Flexibility: Swap PostgreSQL for MongoDB by writing a new adapter.
- Clean boundaries: Business logic stays untouched when infrastructure changes.
