Beyond a backend framework's basic structure,design a layered architecture (Django example)
Split API·business logic·database·external payment API into layers by responsibility, and complete a practical back-end architecture and development rules where several developers and AI development agents can write code in consistent places without conflicts.
1. Lecture Overview: Why Do We Need a Layered Architecture?
Keep Django's fast productivity while solving the Fat View, duplicate rules, untestable code and scattered AI code that come with growing service size.
01 Lecture topic: 6 key design requirements
Extend Django's basic structure to design a layered architecture that meets these requirements.
- Separate API and business logic — so the View doesn't do everything
- Separate database access logic — wrap ORM queries behind a Repository
- Turn frequently changing business rules into a library — modularize Rule·Policy·Calculator
- A structure where many developers can work at once — minimize Git conflicts by splitting responsibility per file
- Structure external payment API and third-party integrations — loose coupling with Port & Adapter
- Set development rules so AI development agents write code consistently
02 7 learning goals
After the lecture, students should be able to explain and build the following themselves.
- 1. Understand the limits of Django's basic structure (bloated
models.py,views.py). - 2. Tell the Model, API, Business and Infrastructure layers apart.
- 3. Tell the roles of
Rule,Policy,CalculatorandWorkflowapart. - 4. Separate DB and external system dependencies using
RepositoryandPort. - 5. Build a café order API with a layered architecture.
- 6. Add an external payment provider as an
Adapter. - 7. Write project development rules for AI to follow.
⚠️ Anti-pattern: one View doing too much (Ch 02)
A structure mixing HTTP request handling, DB lookup, availability checks, amount calculation, saving the order and calling external payment in one View.
class OrderCreateView(APIView):
def post(self, request):
menu = Menu.objects.get(id=request.data["menu_id"])
if not menu.is_available:
raise ValidationError("This menu item is not on sale.")
total_price = menu.price * request.data["quantity"]
order = Order.objects.create(
user=request.user,
total_price=total_price,
)
PaymentAPI.confirm(...)
return Response({"order_id": order.id})
- The same business rule is duplicated across several APIs.
- Business logic is hard to unit test without a DB.
- Several developers edit the same file at once and conflict.
- A change in an external API affects the whole service.
- It's hard for AI to judge consistently where to write code.
📁 Django's basic structure and file bloat (Ch 03)
Fine for small projects, but as features grow, models.py, views.py, serializers.py and tests.py bloat to thousands of lines.
backend/
├── manage.py
├── config/
│ ├── settings.py
│ ├── urls.py
│ ├── asgi.py
│ └── wsgi.py
└── cafe/
├── migrations/
├── admin.py
├── apps.py
├── models.py # ⚠️ bloated to thousands of lines
├── serializers.py # ⚠️ validation + business mixed
├── tests.py # ⚠️ slow DB-dependent tests
└── views.py # ⚠️ HTTP + queries + payment mixed
💡 Solution: split the files inside the Django app by responsibility, and add a pure business layer and an infrastructure layer.
2. Target Architecture and the One-Way Dependency Rule
Split responsibilities into 5 top-level directories, and set Port interfaces as the boundary so the Business layer doesn't depend directly on the Django ORM or external APIs.
🏗️ 4.1 Full target architecture directory structure
backend/
├── manage.py
├── pyproject.toml
├── config/ # Django global settings
├── apps/ # Django and HTTP layer
│ ├── cafe/
│ └── billing/
├── business/ # pure business logic (no Django imports)
│ ├── core/
│ ├── cafe/
│ └── billing/
├── infrastructure/ # DB and external system implementations (Port implementations)
│ ├── repositories/
│ ├── transactions/
│ ├── payment_gateways/
│ ├── notifications/
│ └── outbox/
└── tests/ # 3-level test suite
├── unit/
├── integration/
└── contract/
📋 4.2 Key responsibilities per layer
| Layer | Responsibility |
|---|---|
config | Overall Django project settings (settings, urls, wsgi/asgi) |
apps | HTTP request/response (DRF API), Django Model definitions, Admin and container.py |
business | Pure business rules (Rule), policies (Policy), calculations (Calculator), procedures (Workflow), interfaces (Port) |
infrastructure | Django ORM Repository, transactions (UoW), external payment API Adapter, messages/email, Outbox |
tests | Unit (no DB) · Integration (DB/ORM) · Contract (external Adapter) tests |
API → Workflow → Rule·Policy·Calculator → Port ← Infrastructure Adapter → DB / External API.
The Business layer never imports Django or DRF.
🚫 Forbidden dependency (calling the ORM directly from Business)
# ❌ never allowed in the business layer!
from django.db import transaction
from apps.cafe.models import Order
Order.objects.create(...)
✅ Allowed dependency (injecting a Port interface)
# ✅ The Workflow doesn't know which DB it uses
class CreateOrderWorkflow:
def __init__(self, order_repository: OrderRepository):
self.order_repository = order_repository
3. The 6 Building Blocks of the Business Layer
Inside business/cafe/ is split into dto, rules, policies, calculators, workflows and ports, each with a single responsibility.
6.1 DTO (Data Transfer Object)
Immutable objects that pass data between layers. DTOs don't use Django Models.
from dataclasses import dataclass
@dataclass(frozen=True)
class OrderItemCommand:
menu_id: int
quantity: int
@dataclass(frozen=True)
class CreateOrderCommand:
customer_id: int
items: tuple[OrderItemCommand, ...]
6.2 Rule (checks a single condition)
Checks just one business condition (e.g. order quantity, whether on sale, order hours, discount eligibility).
class OrderQuantityRule:
def evaluate(self, quantity: int) -> RuleResult:
if quantity < 1:
return RuleResult.reject(
code="INVALID_QUANTITY",
message="Order quantity must be at least 1.",
)
return RuleResult.accept()
6.3 Policy (decides with combined rules)
Combines several Rules to make a final decision (e.g. order acceptance, cancellation, discount and refund policies).
class OrderAcceptancePolicy:
def __init__(self, rules):
self.rules = rules
def evaluate(self, context):
for rule in self.rules:
result = rule.evaluate(context)
if not result.passed:
return result
return RuleResult.accept()
6.4 Calculator (pure calculator)
Always returns the same result for the same input, doesn't call the DB or external APIs, and doesn't use float for money.
class OrderPriceCalculator:
def calculate(self, items):
return sum(
item.unit_price * item.quantity
for item in items
)
6.5 Workflow (coordinates the use case steps)
Manages the full processing order a use case needs, combining Rules, Policies and Calculators rather than calculating or deciding itself.
class CreateOrderWorkflow:
def __init__(
self,
menu_repository,
order_repository,
acceptance_policy,
price_calculator,
unit_of_work,
):
self.menu_repository = menu_repository
self.order_repository = order_repository
self.acceptance_policy = acceptance_policy
self.price_calculator = price_calculator
self.unit_of_work = unit_of_work
def execute(self, command):
menus = self.menu_repository.get_available_menus(
menu_ids=[item.menu_id for item in command.items]
)
self.acceptance_policy.validate(menus=menus, items=command.items)
total_price = self.price_calculator.calculate(items=command.items, menus=menus)
with self.unit_of_work:
return self.order_repository.create_order(
customer_id=command.customer_id,
items=command.items,
total_price=total_price,
)
6.6 Port (external feature interface)
A Protocol interface for features the Business layer needs from outer layers. The real implementation lives in infrastructure.
from typing import Protocol
class OrderRepository(Protocol):
def create_order(self, order_data):
...
def get_order(self, order_id: int):
...
4. Real Case 1: Café Order API & Wiring Dependencies
Map 7 order requirement steps to the folder structure and pipeline, then inject the implementations (DI) in container.py.
☕ 7.1 Requirements & 7.3 Processing flow
- Validate request data (
CreateOrderSerializer) - Create the
CreateOrderCommandDTO - Look up menu items (
MenuRepository) - Check availability + quantity (
OrderAcceptancePolicy) - Calculate the total (
OrderPriceCalculator) - Save order and items in a transaction (
OrderRepository) - Return the order result (
201 Created)
// POST /api/v1/cafe/orders request
{
"items": [
{ "menu_id": 1, "quantity": 2 },
{ "menu_id": 3, "quantity": 1 }
]
}
// response
{
"order_id": 1042,
"status": "RECEIVED",
"total_price": 13500
}
📂 7.2 Café domain folder structure
apps/cafe/
├── models/ (menu.py, order.py, order_item.py)
├── api/ (serializers.py, views.py, urls.py)
└── container.py
business/cafe/
├── dto/ (order_command.py, order_result.py)
├── rules/ (menu_available_rule.py, order_quantity_rule.py)
├── policies/ (order_acceptance_policy.py)
├── calculators/ (order_price_calculator.py)
├── workflows/ (create_order_workflow.py)
└── ports/ (menu_repository.py, order_repository.py, unit_of_work.py)
infrastructure/
├── repositories/ (django_menu_repository.py, django_order_repository.py)
└── transactions/ (django_unit_of_work.py)
🧩 8. Wiring dependencies (container.py)
Instead of creating DjangoOrderRepository() directly inside the Workflow, wire it up in container.py.
# apps/cafe/container.py
def create_order_workflow() -> CreateOrderWorkflow:
return CreateOrderWorkflow(
menu_repository=DjangoMenuRepository(),
order_repository=DjangoOrderRepository(),
acceptance_policy=OrderAcceptancePolicy(...),
price_calculator=OrderPriceCalculator(),
unit_of_work=DjangoUnitOfWork(),
)
- Inject a
FakeRepositoryright away in unit tests - Easy to swap DB and external API implementations
- The Workflow doesn't depend on technical details
5. Real Case 2: Extending the Architecture with a Billing·Payment Module
Isolate external payment provider integration, network Timeouts, duplicate-approval prevention (Idempotency), webhook verification and Outbox event publishing with the Port & Adapter pattern.
🔌 10. PaymentGateway Port & Toss Adapter
The Business layer knows nothing of the name Toss or its response format; it only sees the PaymentGateway Protocol.
class PaymentGateway(Protocol):
provider_code: str
def confirm(self, command) -> PaymentResult: ...
def get_payment(self, provider_payment_id) -> PaymentResult: ...
def cancel(self, command) -> RefundResult: ...
def verify_webhook(self, raw_body, headers) -> bool: ...
class TossPaymentGateway:
provider_code = "TOSS"
def __init__(self, client, mapper):
self.client = client
self.mapper = mapper
def confirm(self, command):
response = self.client.confirm_payment(
payment_key=command.payment_key,
order_id=command.order_id,
amount=command.amount,
)
return self.mapper.to_payment_result(response)
📌 6 files inside the Adapter: adapter.py · client.py · mapper.py · schemas.py · signature.py · exceptions.py
🗂️ 11. Payment provider Registry & 12. State machine
Pick the payment provider with a PaymentGatewayRegistry instead of an if provider == "TOSS": branch, so adding a new provider changes 0 lines of existing Workflow.
class PaymentGatewayRegistry:
def __init__(self, gateways):
self._gateways = {g.provider_code: g for g in gateways}
def get(self, provider_code):
return self._gateways[provider_code]
READY → PENDING → PAID / FAILED, PAID → PARTIAL_REFUND → REFUNDED, PAID → CANCELLED🚫 Forbidden state transitions:
FAILED → REFUNDED, READY → CANCELLED, REFUNDED → PAID
⚡ 13. Splitting the approval transaction
Don't hold a DB transaction open while calling an external API.
- Short TX 1: change to
PENDING - Outside TX: call the provider's approval API
- Short TX 2: save payment result + Outbox
- On Timeout, don't confirm failure right away (check by lookup/webhook)
🛡️ 14. Idempotency
Blocks duplicate payments caused by network retries at the source.
Idempotency-Keyheader required- Same Key + same request → return the existing result
- Same Key + different amount →
409 Conflict provider_payment_idUnique constraint
🔔 15. Webhook principles
Must be safe against duplicate delivery and out-of-order events.
- Verify the Signature with the Raw Body
- External
event_idUnique constraint - Stop old events from overwriting the latest state
- A structure that can reprocess failed events
📦 16. Outbox pattern
Separates follow-up tasks so their failures don't roll back payment approval.
- Save
Paymentand thePAYMENT_COMPLETEDOutbox event in the same TX - After Commit, the Outbox Publisher asynchronously publishes order status changes, receipts and notifications
6. 3-Level Test Strategy · AI Dev Rules · Deciding File Placement
Define clear rules and a matrix for where AI agents write which code and how they verify it.
🧪 17.1 Unit tests
tests/unit/business/ — verify the pure Business layer in milliseconds, without a DB.
- Order quantity·availability·total calculation
- Payment state transitions·partial refund limits
- Duplicate payment·Timeout·out-of-order webhook handling
🔗 17.2 Integration tests
tests/integration/ — verify real Django models, transactions and DB constraints.
- Atomic save and Rollback of order + order items
- Saving payment + payment attempt history + Outbox together
- Guarantee duplicate webhook events are handled once
📜 17.3 Adapter contract tests
tests/contract/payment_gateways/ — verify every payment Adapter follows the same contract.
- Consistent DTO conversion for approval success/rejection
- Classifying Timeout·unknown response exceptions
- Webhook signature verification and state mapping
🤖 18. 12-step build order for AI dev agents
- Read the existing project rules.
- Search existing code in the related domain.
- Define the
DTOand error codes. - Implement the
Rule,PolicyandCalculator. - Write unit tests.
- Define the
Portinterface. - Implement the
Workflow. - Write the Django
ModelandMigration. - Implement the
RepositoryorAdapter. - Implement the
API (Serializer · View · URL). - Wire dependencies in
container.py. - Run all tests and static checks.
⛔ 18. 9 things AI must never do
- Write complex business logic in a View
- Use the Django ORM directly in the Business layer
- Copy code without checking existing shared Rules
- Return the payment provider's raw response straight from the API
- Fixing a bug with a quick if-statement and no failing test
- Change existing Migration files freely
- Hardcode payment Secret Keys in code
- Do large refactors nobody asked for
- Falsely report that unrun tests passed
🧭 19. File placement decision matrix
Question: "Is this code a business rule that can run without Django and a DB?" → If Yes, it always goes in business/!
| Code type | Where to write it |
|---|---|
| DB table definitions | apps/<domain>/models |
| Request·response validation (HTTP) | apps/<domain>/api |
| A single business condition | business/<domain>/rules |
| A combination of conditions | business/<domain>/policies |
| Amount·score·period calculation | business/<domain>/calculators |
| Business process steps | business/<domain>/workflows |
| External feature interface | business/<domain>/ports |
| Django ORM implementation | infrastructure/repositories |
| A specific payment provider implementation | infrastructure/payment_gateways |
| Wiring dependencies | apps/<domain>/container.py |
🎯 20. Lecture summary: a structure that contains the impact of change
The goal of a layered architecture isn't making lots of folders, but limiting the impact of a change to one area.
API spec change → change only apps/api
Business rule change → change only business/rules or policies
Price formula change → change only business/calculators
DB access change → change only infrastructure/repositories
Add/change payment vendor → change only the infrastructure/payment_gateways adapter
🔥 5 key principles to remember
- 1. The View receives the request and calls the Workflow.
- 2. The Workflow manages the order of business steps.
- 3. Rule, Policy and Calculator handle pure business logic.
- 4. The DB and external systems connect through Ports and Adapters.
- 5. The Business layer doesn't depend on Django or specific external services.
Review the full design process with the 20-lecture slide share
Flip through all the code and architecture diagrams from chapters 1 to 20 in the slide share popup and practice along.