AACE AI SW
👤ParticipantACE AI SW
DAY 05 · FRIDAY · BACKEND ARCHITECTURE

Backend frameworks &
layered architecture

Learn how a request turns into a response behind the screen. In Part 1 you learn the MVC pattern and backend basics that work in any framework. In Part 2 you design a layered architecture that splits API, business rules, DB and external payment by responsibility, using Django as the example.

We connect the docs you made on Day 3 (REQ · DATA · API) to "which folder and which file" they go into in today's backend code.

Today’s Flow

Today's Schedule

First build basics that work in any framework (MVC), then extend to a real-world layered structure with Django.

SESSION A · 80 min · PART 1

Backend & frameworks

  • Request → response, HTTP methods · status codes
  • 6 things a backend does
  • Framework comparison (Django · Express · Spring · Laravel …)
Slides P1 · 1–6
SESSION B · 80 min · PART 1

MVC & starting Django

  • Model · View · Controller
  • Django MTV ↔ MVC mapping
  • startproject · startapp · first API
  • Limits of a Fat View
Slides P1 · 7–13
SESSION C · 100 min · PART 2

Layered architecture

  • 5 main directories and dependency direction
  • DTO · Rule · Policy · Calculator · Workflow · Port
  • Café ordering API and container.py
Slides P2 · 1–8
SESSION D · 80 min · PART 2

Payment extension · tests · AI standard

  • Add a payment provider with Port & Adapter
  • Idempotency · webhooks · Outbox
  • 3-level testing, AI 12 steps · 9 don'ts
Slides P2 · 9–13
Lab · homework

Apply to your project

  • Place Day 3 spec REQs into layers
  • File placement quiz, 8 questions
  • Write BACKEND_RULES.md
  • Review with gstack /plan-eng-review
Lab guide below

HTML Presentation

Day 5 Slides

Use the tabs to switch between Part 1 (backend · MVC) and Part 2 (Django layered architecture). Move with ←/→, and open lecture notes with the N key or the button.

ACE AI SW Startup Training · Day 5 · Part 1

What happens
behind one button?

From the moment a user presses "Order" until "Order complete" shows on screen — the backend is responsible for everything in between.

User"Order"Backend serverDBPayment · notifications① Request④ Response③ Save③ Integrate② Validate · rules · calculate
RequestThe browser or app sends a request to the server
ProcessValidate, apply rules and calculate
PersistSave to the DB and connect to outside systems
ResponseSend the result back as JSON or HTML
Client · Server · Database

The frontend shows; the backend protects

Mobile app · browserFrontend · showsBackend serverProtects the rulesDatabaseKeeps recordsOutside APIsPayment · notifications · mapsHTTP request / response

Frontend (Day 3 UI spec)

  • Screens, buttons, input forms, status display
  • User experience and instant feedback
  • Users can tamper with it → can't be trusted

Backend (Day 3 DATA · API · REQ)

  • Final decision on business rules like "sold-out items can't be ordered"
  • Calculating amounts, saving data, checking permissions
  • Connecting to outside systems like payment and notifications
What if prices are calculated only in the browser? A user could send a ₦0 order with developer tools. Rules must live on the server.
HANDS-ON 0110 minPairs · quiz

Is this feature frontend or backend?

GoalLook at a feature and decide for yourself where it should be handled
FRONTENDShowsScreens · buttons · instant response · can be tampered with
BACKENDProtectsMoney · permissions · stock · storage · final decisions
Question 1Is it OK if the user changes it?No → backend
Question 2Is it about money or permissions?Yes → backend
Color and size of the order button
✓ Frontend — visible look — safe even if the user changes it
Reject the order if the item is sold out
✓ Backend — business rule — blocking only in the browser can be bypassed
Final calculation of the order total
✓ Backend — money — a browser calculation can be tampered to ₦0
Show characters left while typing
✓ Frontend — instant guidance — no harm if tampered with
Only the admin can mark items sold out
✓ Backend — permissions — must be checked on the server to be safe
Show a spinner while loading
✓ Frontend — user experience — showing
Correct 0 / 6
0/4
Tick the boxes
to check yourself
Career linkDevelopers who know "this rule must be checked on the server" are trusted as people who prevent security incidents.
HTTP basics

Request and response: method · URL · body · status code

Request

POST /api/v1/cafe/orders
Content-Type: application/json

{ "items": [
    { "menu_id": 1, "quantity": 2 },
    { "menu_id": 3, "quantity": 1 } ] }

Response

201 Created

{ "order_id": 1042,
  "status": "RECEIVED",
  "total_price": 13500 }
MethodMeaningStatus codeMeaning
GETRead200 / 201OK / Created
POSTCreate400 / 401 / 403Bad request / login needed / no permission
PATCH · PUTUpdate404 / 409Not found / conflict (duplicate, etc.)
DELETEDelete500Server internal error
Analogy · Letters and replies

HTTP is sending a letter and getting a reply

Request = the letter you sendAddress (URL)/api/v1/cafe/ordersLetter type (method)POST = please create thisContents (body JSON)2 chicken sandwiches, 1 colaBackend = post office + officeResponse = reply201CreatedOrder no. 1042Total ₦13,500200Success201Created400The letter's contents are wrong401Who are you?403No permission404No such address409Already handled (duplicate)500Post office accidentJust look at the stamp (status code) to know the result: 2xx success · 4xx sender's problem · 5xx server's problem
HANDS-ON 0210 minPairs · quiz

Which stamp (status code) for this situation?

GoalRead what happened just from the response number
2xxSuccess200 read · 201 created
4xxSender's problem400 · 401 · 403 · 404 · 409
5xxServer's problem500 internal error
TipLook at the first digitWhose fault first
A new order was saved
✓ 201 — newly made = Created
The menu list was loaded
✓ 200 — read succeeded = OK
Sent quantity = -1
✓ 400 — the request is wrong = Bad Request
Sent an order without logging in
✓ 401 — we don't know who you are = Unauthorized
Looked up order number 9999, which doesn't exist
✓ 404 — no such thing = Not Found
Sent a different amount with the same payment key
✓ 409 — clash = Conflict (idempotency)
Correct 0 / 6
0/4
Tick the boxes
to check yourself
Career linkIf you can read status codes, you've found half the cause of a bug. A common backend and QA interview question.
What a backend does

6 things a backend does

① RoutingDecide which code handles it from the URL and method/api/v1/cafe/orders → create order
② Input validationCheck required values, types and rangesIs quantity an integer of 1 or more?
③ Authentication · permissionWho you are, and whether you may do thisOnly the admin can mark items sold out
④ Business rules · calculationCan it be sold, discounts, totalThe core value of the service
⑤ Data storageRecord consistently in the DB (transactions)Save order + order items together
⑥ Outside integrationPayment, SMS/email notifications, maps, etc.Prepare for failures and delays
Why frameworks?

Framework = repeated work + agreements on where code goes

Without a framework

  • Build URL parsing, DB connections, sessions and security yourself every time
  • Code location and style differ from person to person
  • Risk of security mistakes like SQL injection and CSRF

With a framework

  • Routing · ORM · auth · admin · security built in
  • Shared structure: "models here, views here" → easier teamwork
  • Easier for AI to write code in the right place too
My codeI call itLibrary (tool)Framework (house skeleton)urls.pyviews.pymodels.pyIt calls meMy code in set places
A library is a tool you call; a framework is a skeleton that calls you. (Inversion of control)
Popular backend frameworks

Different languages, but MVC-style structure

FrameworkLanguageCharacterStructure patternWhen to use
Django (+ DRF)PythonFull-stack · built-in features (ORM · Admin · Auth)MTV (= MVC)Fast MVPs, admin screens, data-centered services
FastAPI · FlaskPythonMicro · API-centeredFree-formLight APIs, serving AI models
Express · NestJSJavaScript / TSMicro / structuredMVC · modulesSame language as the frontend, real-time
Spring BootJava / KotlinEnterprise · strong structureSpring MVC · layeredLarge-scale, finance and government systems
LaravelPHPFull-stack · productivityMVCWeb services where hosting is PHP
Ruby on RailsRubyFull-stack · convention firstMVCEarly startup products
MVC pattern

MVC splits three responsibilities

CustomerRequest "Order"ControllerWaiter — takes and passes on ordersOrderController.create()① Request data② Decide the screenModelKitchen — ingredients and cooking rulesMenu · Order · OrderItemViewPlate — the visible resultOrder complete screen / JSONPuts data on the screen
🍽️ Restaurant analogy — the waiter (Controller) takes the order to the kitchen (Model), then serves the finished dish (View) to the customer.
MVC request flow

6 steps from one request to a response

UserRouterControllerModel ↔ DBView1 POST /orders2 choose handler3·4 read menu · save orderSave result5 build screen/JSON6 201 Created + order number
Expressroutes/ → controllers/ → models/ → views/
Spring MVC@Controller → @Service → @Repository → View/JSON
Laravel · Railsroutes → Controller → Model(Eloquent/ActiveRecord) → View
HANDS-ON 0310 minPairs · put in order

A request's journey: put it in order

GoalExplain who works in what order from request to response
1
Customer"I'd like to order"
2
Waiter (Controller)Checks and passes on the order
3
Kitchen (Model)Ingredients · cooking · storing
4
Plate (View)Serves the result

① Tap the cards in order

② The order I chose

1…
2…
3…
4…
5…
6…
0 / 6 chosen
0/4
Tick the boxes
to check yourself
Career linkBeing able to draw and explain a request flow is used most in whiteboard questions in tech interviews.
Django MTV = MVC

Django's MTV is MVC with different names

MVC nameDjango nameRouterURLconfurls.pyControllerView ⚠views.pyModelModelmodels.pyView (presentation)Template ⚠ / Serializertemplates · DRF⚠ The names cross overDjango View = Controller
In Django, "View" means the function/class that handles requests (MVC's Controller).
Hands-on · Django in 5 commands

Starting a Django project

Virtual envvenvinstallpip installProject · appstartprojectApply to DBmigrateRunrunserver

Commands

# Virtual env + install
python -m venv .venv
source .venv/bin/activate   # Windows: .venv\Scripts\activate
pip install django djangorestframework

# Create project · app
django-admin startproject config .
python manage.py startapp cafe

# Apply Model → DB, run server
python manage.py makemigrations
python manage.py migrate
python manage.py runserver

Basic structure created

backend/
├── manage.py
├── config/   # settings · urls · wsgi/asgi
└── cafe/
    ├── migrations/
    ├── admin.py
    ├── apps.py
    ├── models.py   # Model
    ├── views.py    # Controller role
    └── tests.py
HANDS-ON 0420 minSolo · terminal

Start a Django server yourself

GoalRun a Django server on your computer and see the first screen
1
Virtual envA box just for this project
2
installdjango · DRF
3
Project · appconfig · cafe
4
Runlocalhost:8000
TipOn Windows: .venv\Scripts\activate · if there's an error, first check the virtual env is on.

Run in order · use the copy buttons

1
Create and turn on virtual envpython -m venv .venv source .venv/bin/activate
2
Installpip install django djangorestframework
3
Create project · appdjango-admin startproject config . python manage.py startapp cafe
4
Apply DB · runpython manage.py migrate python manage.py runserver

Success check

0 / 5
0/4
Tick the boxes
to check yourself
Career link"Start a server locally and fix errors yourself" is the first gate for a junior backend developer.
Basic Django flow

urls → views → models at a glance

① urls.pyURL → which View?② views.pyHandles requests (Controller)③ models.pyData · DB

models.py · Model

class Menu(models.Model):
    name = models.CharField(max_length=50)
    price = models.IntegerField()
    is_available = models.BooleanField(
        default=True)

views.py · Controller

class MenuListView(APIView):
    def get(self, request):
        menus = Menu.objects.filter(
            is_available=True)
        data = MenuSerializer(
            menus, many=True).data
        return Response(data)

urls.py · Router

urlpatterns = [
    path("api/v1/cafe/menus",
         MenuListView.as_view()),
]
Anti-pattern · Fat View / Fat Controller

Problems when one View does everything

A View with 6 responsibilities mixed

class OrderCreateView(APIView):
    def post(self, request):
        menu = Menu.objects.get(           # DB read
            id=request.data["menu_id"])
        if not menu.is_available:          # business rule
            raise ValidationError("Not for sale")
        total = menu.price * \
            request.data["quantity"]       # calculation
        order = Order.objects.create(      # save
            user=request.user, total_price=total)
        PaymentAPI.confirm(...)            # outside payment
        return Response({"order_id": order.id})

As it grows

  • The same rules get duplicated across many APIs
  • You can't test business logic without a DB
  • Several developers edit the same file and clash
  • Changing payment provider affects the whole service
  • AI can't decide code locations consistently
HANDS-ON 0515 minTeam · break-apart game

Break up the Fat View and send each piece home

GoalSplit code mixed in one View into layers by responsibility
APIViewTake requests · return responses
Rule / CalculatorbusinessDecide · calculate (no DB)
RepositoryinfrastructureRead · write the DB
AdapterinfrastructureOutside payment · notifications
HintSee .objects → DB → Repository · see an outside company name → Adapter
menu = Menu.objects.get(id=…)
Answer: Repository
if not menu.is_available: raise …
Answer: Rule
total = menu.price * quantity
Answer: Calculator
Order.objects.create(…, total_price=total)
Answer: Repository
PaymentAPI.confirm(…)
Answer: Adapter
return Response({"order_id": …})
Answer: API
0 / 6 sorted
0/4
Tick the boxes
to check yourself
Career linkSplitting legacy code by responsibility — refactoring — is one of the most used skills on the job.
From MVC to layers

MVC is the start; as it grows, split into more layers

Basic MVC — small serviceController (getting bloated)Model (getting bloated)ViewLayered — when rules growAPI (View · Serializer)Workflow — orderRule · Policy · CalculatorPort ← Adapter (DB · payment)Finer
Spring's Controller → Service → Repository and NestJS's Controller → Provider follow the same idea. Part 2 makes it concrete with Django.
Day 5 · Part 2 · Django layered architecture

A structure that keeps
the impact of change in one place

✗ Change one placeImpact everywhere✓ Contain it in layersAPIWorkflowRules ← only hereInfraThe change stays in one layer
① Separate API ↔ business logicSo the View doesn't do everything
② Separate DB accessORM queries behind a Repository
③ Business rules as a libraryRule · Policy · Calculator
④ Easy parallel developmentResponsibility per file → fewer Git conflicts
⑤ Structured outside paymentLoose coupling with Port & Adapter
⑥ AI dev standardAI writes code in consistent places
Target architecture

Split responsibilities into 5 main directories

backend/
├── manage.py
├── config/          # Django global settings
├── apps/            # Django · HTTP layer
│   ├── cafe/
│   └── billing/
├── business/        # Pure business logic (no Django imports)
│   ├── core/  cafe/  billing/
├── infrastructure/  # DB · outside system implementations (Port implementations)
│   ├── repositories/  transactions/
│   ├── payment_gateways/  notifications/  outbox/
└── tests/
    ├── unit/  integration/  contract/
config/Django global settingssettings · urls · wsgi/asgiapps/Django · HTTP layerDRF API · Model · Admin · container.pybusiness/Pure business logic ★Rule · Policy · Calculator · Workflow · Port · DTOinfrastructure/DB · outside systemsRepository · transactions · payment Adapter · Outboxtests/3-level testsunit · integration · contract
Dependency rule

Dependencies flow one way only

apps / APIView · Serializer — validate HTTP requests, call the Workflow
↓ calls
business / WorkflowCoordinates the whole use-case order
↓ orchestrates
business / Rule · Policy · CalculatorPure business rules · policy decisions · amount calculation (no Django)
↓ depends on interface
business / Port (Protocol)OrderRepository · PaymentGateway interfaces
↑ implements
infrastructure / Repository · AdapterDjango ORM · payment provider API · Outbox implementations
Analogy · Running a restaurant

Understand layered architecture as running a restaurant

apps / APIFloor staffTakes orders, checks them and passes them onView · Serializer
WorkflowManagerSets the order and assigns workCreateOrderWorkflow
Rule · Policy · CalcRecipes · price list"No ingredients, no sale"OrderQuantityRule
PortSupply order form"Please bring it in this format"OrderRepository
Adapter · RepositorySupplierBrings the real ingredients as per the formDjangoOrderRepository
Even if the supplier (DB · payment provider) changes, the manager and recipes stay the same. Just keep to the form (Port).
Forbidden vs allowed

Business doesn't know which DB it uses

Banned — calling the ORM directly in business

from django.db import transaction
from apps.cafe.models import Order

Order.objects.create(...)

Allowed — inject a Port interface

class CreateOrderWorkflow:
    def __init__(self,
                 order_repository: OrderRepository):
        self.order_repository = order_repository
Ask: "Is this a business rule that can run without Django or a DB?" → If yes, business/
HANDS-ON 0610 minPairs · quiz

Which folder does this code go in?

GoalWhen writing new code, pick its set place right away
apps/HTTP · DjangoSerializer · View · container
business/Pure business logicRule · Policy · Calc · Port
infrastructure/DB · outside systemsRepository · Adapter
tests/Verificationunit · integration · contract
Ask"Is this a business rule that can run without Django or a DB?" → If yes, business/
class OrderQuantityRule
✓ business — pure business rule — runs without Django
class OrderCreateSerializer
✓ apps — HTTP request validation — DRF
class DjangoOrderRepository
✓ infrastructure — DB access via Django ORM
class PaystackAdapter
✓ infrastructure — outside payment provider integration
class PaymentGateway(Protocol)
✓ business — the standard (Port) business defines
test_quantity_21_is_rejected
✓ tests — Unit test
Correct 0 / 6
0/4
Tick the boxes
to check yourself
Career linkDevelopers who keep code in its place per team rules get faster code reviews and fewer team conflicts.
Business layer components

The 6 parts of the Business layer

DTOImmutable objects that carry data between layers (no Models)CreateOrderCommand
RuleJudges just one business conditionOrderQuantityRule, MenuAvailableRule
PolicyCombines several Rules into a final decisionOrderAcceptancePolicy
CalculatorSame input → same result. No DB or outside calls; no float for moneyOrderPriceCalculator
WorkflowCoordinates the use-case order. Doesn't judge itself; it combinesCreateOrderWorkflow
PortProtocol interface for features it needs from outside layersOrderRepository, PaymentGateway
Rule · Policy · Calculator

Day 3 REQs become pure Python rules

Day 3 docREQ-006 quantity 1–20Rule classOrderQuantityRuleUnit test0.01 sec without a DB

Rule · REQ-006

class OrderQuantityRule:
    MAX = 20

    def evaluate(self, quantity):
        if quantity < 1 or quantity > self.MAX:
            return RuleResult.reject(
                "QUANTITY_OUT_OF_RANGE")
        return RuleResult.accept()

Policy

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()

Calculator

class OrderPriceCalculator:
    def calculate(self, items):
        return sum(
            item.unit_price * item.quantity
            for item in items
        )
# Use integers (smallest currency unit)
# or Decimal for money; no float
HANDS-ON 0710 minSolo · code

Build and test a quantity Rule yourself

GoalTurn a Day 3 requirement into a pure Python Rule and check it with tests
1
Read the requirementREQ-006 quantity 1–20
2
Write the RuleFill MIN · MAX
3
Run testsInstantly, no DB
4
Check the edges0 · 1 · 20 · 21
EdgesMost bugs happen at the edges (0 and 1, 20 and 21). Always test at the edges!
class OrderQuantityRule:      # REQ-006
    MIN =     MAX = 
    def evaluate(self, quantity):
        if quantity < self.MIN or quantity > self.MAX:
            return reject("QUANTITY_OUT_OF_RANGE")
        return accept()
quantity0Expect: reject–
quantity1Expect: pass–
quantity10Expect: pass–
quantity20Expect: pass–
quantity21Expect: reject–
Try entering MIN · MAX
0/4
Tick the boxes
to check yourself
Career link"A developer who proves it with tests" is welcome on any team. Edge-value testing is a must-know QA interview concept.
Case 1 · Cafe order API

7 steps to create an order, and who handles each

#StepOwnerFile
1Validate request dataAPIapps/cafe/api/serializers.py
2Create CreateOrderCommand DTOAPI → businessbusiness/cafe/dto/order_command.py
3Read menuPort → Repositoryinfrastructure/repositories/django_menu_repository.py
4Check sellable + quantityPolicy · Rulebusiness/cafe/policies/order_acceptance_policy.py
5Calculate totalCalculatorbusiness/cafe/calculators/order_price_calculator.py
6Save order + items in a transactionRepository · UoWinfrastructure/transactions/django_unit_of_work.py
7Return result (201 Created)APIapps/cafe/api/views.py
Workflow & dependency injection

The Workflow does only the order; assembly happens in container.py

business/cafe/workflows/create_order_workflow.py

def execute(self, command):
    menus = self.menu_repository.get_available_menus(
        menu_ids=[i.menu_id for i in command.items])
    self.acceptance_policy.validate(
        menus=menus, items=command.items)
    total = 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)

apps/cafe/container.py

def create_order_workflow():
    return CreateOrderWorkflow(
        menu_repository=DjangoMenuRepository(),
        order_repository=DjangoOrderRepository(),
        acceptance_policy=OrderAcceptancePolicy(...),
        price_calculator=OrderPriceCalculator(),
        unit_of_work=DjangoUnitOfWork(),
    )
  • Inject a FakeRepository instantly in tests
  • Easy to swap DB and outside API implementations
Analogy · Socket and adapter

Port & Adapter = wall socket and travel adapter

Wall socket = PortOne standard set by businessPaymentGatewayTravel adapterPaystack AdapterPaystackTravel adapterFlutterwave AdapterFlutterwaveTravel adapterToss AdapterTossEvery provider's plug shape is differentA new provider means adding just one adapter → 0 lines changed in the Workflow (wiring in the wall)
Case 2 · Billing with Port & Adapter

Change the payment provider with 0 lines changed in the Workflow

Port (business)

class PaymentGateway(Protocol):
    provider_code: str
    def confirm(self, command) -> PaymentResult: ...
    def get_payment(self, payment_id) -> PaymentResult: ...
    def cancel(self, command) -> RefundResult: ...
    def verify_webhook(self, raw_body, headers) -> bool: ...

Registry (assembly)

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]
WorkflowDoesn't know provider namesPortPaymentGatewayRegistryChosen by provider_codetoss/ Adapterpaystack/ Adapterflutterwave/ Adapter

Each Adapter folder: adapter · client · mapper · schemas · signature · exceptions

Analogy · Elevator button

Press twice, happens once: idempotency

Elevator button▲Press once▲Press twice▲Press three timesElevatorComes only oncePress many times, one result = idempotencyThe pay button must work the same wayPay ₦13,500Slow network, pressed twiceIdempotency-Key: abc-123Same key → existing resultMoney goes out onceSame key but a different amount?409 Conflict — rejected(prevents mistakes · tampering)
Payment safety

5 safeguards where money moves

READYPENDINGPAIDFAILEDREFUNDED✗ FAILED → REFUNDED banned
State transitionsREADY → PENDING → PAID / FAILED
PAID → REFUNDED
Banned: FAILED → REFUNDED
Separate TXTX1: save PENDING → outside TX: call provider → TX2: result + OutboxTimeout ≠ instant failure
IdempotencyIdempotency-Key required. Same key + same request → existing resultDifferent amount → 409
WebhooksVerify Raw Body signature, event_id UniqueOld events must not overwrite the latest state
OutboxSave payment and event in the same TX; follow-up work runs async after CommitNotification failure ≠ payment rollback
HANDS-ON 0810 minPairs · simulator

Press the pay button many times

GoalSee for yourself how an idempotency key prevents double payment
1
PredictWhat will the ledger show?
2
Press buttonsSame key · different amount · new key
3
See response201 · 200 · 409
4
Check ledgerMoney actually paid
RuleSame key + same request → existing result · same key + different amount → 409 · new key → new payment

Send payment request

Server response

—Press a button
Money actually paid ₦0
0/4
Tick the boxes
to check yourself
Career linkIdempotency is a common interview question at payment and fintech companies (Paystack · Flutterwave · Moniepoint, etc.).
3-level test strategy

When layers split, tests split too

Check business rules fast with Unit tests without a DB; check DB and provider connections with higher-level tests.

ContractPayment provider Adapter standardtests/contract/IntegrationReal DB · transactionstests/integration/UnitBusiness rules without a DBtests/unit/business/SlowFast · many
🧪 Unit · tests/unit/business/Pure business in milliseconds, without a DBQuantity · sellable · total · payment state transitions · double payment
🔗 Integration · tests/integration/Real Django models · transactions · DB constraintsAtomic save of order + items · webhook processed once
📜 Contract · tests/contract/Does every payment Adapter keep the same standard?DTO mapping · Timeout classification · signature check
Place each TEST-### from your Day 3 trace table in one of these three folders. Business-rule tests are mostly Unit.
HANDS-ON 0910 minPairs · quiz

Which level of the pyramid is this test?

GoalPick the right kind for each test to build fast, reliable checks
UnitNo DBRule · Policy · Calc · state transitions
IntegrationReal DBSaving · transactions · constraints
ContractProvider standardAdapter mapping · signatures · Timeout
RatioMost at the bottomUnit ≫ Integration > Contract
Quantity 21 is rejected
✓ Unit — checks rules only — no DB needed
Order and order items are saved together
✓ Integration — checks real DB transactions
The Paystack Adapter classifies Timeouts correctly
✓ Contract — checks the payment Adapter standard
Total = unit price × quantity is correct
✓ Unit — pure calculation
The same webhook is processed only once (DB unique)
✓ Integration — checks DB constraints
Verifies the Flutterwave webhook signature
✓ Contract — per-provider signature standard
Correct 0 / 6
0/4
Tick the boxes
to check yourself
Career linkIf you can explain a test strategy, you get rated a level higher in both QA and backend roles.
AI development spec

12-step order · 9 don'ts for AI agents

Build order

1Read standard2Search existing code3DTO · error codes4Rule · Calc5Unit tests6Define Port7Workflow8Model · DB9Repo · Adapter10API11Assemble container12Full testsRules (business) first → outside (API) later

Never do this

  • Complex business logic in the View
  • Using the Django ORM in business
  • Copying without checking existing Rules
  • Returning the provider's raw response as-is
  • Fixing a bug with a quick if-statement and no failing test
  • Changing existing Migrations · hard-coding Secret Keys
  • Large unrequested refactoring · reporting tests passed that were never run
Wrap-up

Not adding folders, but containing the impact of change

If this changesOnly this changes
API spec changeapps/<domain>/api
Business rule changebusiness/<domain>/rules · policies
Price formula changebusiness/<domain>/calculators
DB access method changeinfrastructure/repositories
Add · change payment providerinfrastructure/payment_gateways/<provider>
  • The View takes requests and calls the Workflow
  • The Workflow manages the business process order
  • Rule · Policy · Calculator are pure business logic
  • DB and outside systems connect via Ports and Adapters; business doesn't depend on Django
P1 · 1
LECTURE NOTE

MVC Across Frameworks

Same MVC, different names per framework

In any framework, just find where "router → request handling → business logic → data → presentation" live, and the structure becomes clear.

RoleDjango (DRF)Express · NestJSSpring BootLaravelRuby on Rails
Routerurls.pyroutes/ · @Controller() path@RequestMappingroutes/web.php · api.phpconfig/routes.rb
Controllerviews.py (APIView · ViewSet)controllers/@RestControllerapp/Http/Controllersapp/controllers
Business logic (extended)business/ (today's structure)services/ · Provider@Serviceapp/Services · ActionsService Object
Model · datamodels.py + ORMMongoose · Prisma · TypeORM@Entity + @Repository (JPA)Eloquent ModelActiveRecord
View · presentationTemplate / Serializer(JSON)Template engine / res.json()Thymeleaf / JSONBlade / API ResourceERB / Jbuilder

Hands-on Lab Guide

Apply a layered structure to your project

Place the specs you made on Day 3 (REQ · DATA · API) into the layers learned today. If stuck, use the prompts below with gstack.

stagesTo doInputOutputPass condition
1. MVC flow diagramDraw the 6 request → response steps for 1 main APIDay 3 API-###MVC_FLOW.mdRouter · Controller · Model · View locations shown
2. Start Djangovenv · startproject · startapp · runserver—backend/ basic structurerunserver screen checked, git commit
3. Folder designCreate config · apps · business · infrastructure · testsDomain listARCHITECTURE.md1 line of responsibility per folder, no Django imports in business
4. Layer placementAssign Rule/Policy/Calculator/Workflow for each REQTRACEABILITY.mdLAYER_MAP.mdEvery REQ has a file path
5. Order API design7-step flow and DTO · Port definitionsAPI specORDER_API_DESIGN.mdIncludes requests · responses · error codes · state transitions
6. AI standard12-step order · 9 don'ts · placement tableToday's slidesBACKEND_RULES.mdA doc you can give AI as-is
7. ReviewReview the design with gstack /plan-eng-reviewOutputs 3–6Review result + DECISION_LOGAccept/change/reject reason for each finding

① Layer placement request

/plan-eng-review (Codex: gstack-plan-eng-review skill)

/plan-eng-review
Place each REQ in TRACEABILITY.md into a Django layered architecture.
Structure: config / apps / business / infrastructure / tests
- For each REQ, propose in a table which of Rule · Policy · Calculator · Workflow · Port · Repository · Adapter
  it goes into, with the file path
- No Django or DRF imports in the business layer
- Mark unclear REQs as "needs human decision"
Don't write any code yet.

② BACKEND_RULES.md draft

Make the AI dev standard doc

Write a draft BACKEND_RULES.md backend development standard for this project.
Include:
1. The 5 main directories and their responsibilities
2. Dependency direction: API → Workflow → Rule/Policy/Calculator → Port ← Adapter
3. The 12-step order for building a new feature
4. 9 things AI must never do
5. File placement table (kind of code → where to write it)
6. 3 test levels (unit / integration / contract): locations and criteria
My project's domain names: [e.g. cafe, billing]
I'll save the file after I review it.

③ Build contract for one feature

Used in the next build session

First read BACKEND_RULES.md and LAYER_MAP.md.
This scope is only [REQ-___].
Follow the 12-step order, but before writing code, first report
1) file paths to create or change 2) DTOs and Ports to define 3) unit tests to write.
Build after approval,
and report only test results you actually ran.

④ Rule-violation review

/review (Codex: gstack-review skill)

/review
Review the current diff against BACKEND_RULES.md.
Check these first:
- django · rest_framework imports inside business/
- Business rules · amount calculations · direct ORM calls inside Views
- Duplicate implementations of existing Rules
- Exposing raw provider responses, hard-coded Secrets
Report only severity · file · line · evidence, and don't change anything.

Quick Check

File placement quiz: where does this code go?

Ask: "Is it a business rule that can run without Django or a DB?" If yes, it's business/.

0 / 8 correct

10-Day Course Navigation

Click the buttons above to go to the Day 1–10 learning pages.

Learning Workspace

Backend · MVC · Django Videos & Day 5 AI Helper

Ordered as: framework overview → MVC → Django basics → layered and clean architecture.

Related YouTube VideosDay 5 recommended materials
  • MVC pattern
  • 1. MVC Explained in 4 MinutesModel · View · Controller key summaryEN
  • 2. What is MVC? The Simplest Explanation You'll Ever SeeMVC through an analogyEN
  • 3. Learn MVC Pattern with ExpressJS and NodeJSMVC in another framework (Express)EN
  • Backend frameworks
  • 4. Backend Frameworks for Web Development: Which One Should You Learn?Overview of main backend frameworksEN
  • 5. Every Backend Framework Ranked & Explained (FastAPI, Django, Node.js …)Comparing features by frameworkEN
  • Django · DRF
  • 6. Learning the Django framework properly (intro) Part.1 Django BasicDjango's basic structure and how it worksKR
  • 7. Python Django From ScratchIntro you follow from installationKR
  • 8. What is MVT Architecture in Django and How it WorksDjango MTV (MVT) mapped to MVCEN
  • 9. Getting Started With Django REST FrameworkYour first API with DRFEN
  • 10. Django REST Framework Full Course - Beginner to ProFull DRF course (long · for review)EN
  • Layered · clean architecture
  • 11. Where to Put Business Logic in DjangoWhere business logic goes — today's key questionEN
  • 12. Django - service layers and "thin views" for business logicFrom Fat View to Thin ViewEN
  • 13. Clean Architecture vs Django’s Pragmatic DesignPros and cons of Django's default vs layer separationEN
  • 14. Service Layer Design Pattern ExplainedThe service (business) layer patternEN
  • 15. Hexagonal Architecture Explained in 10 MinutesHow Port & Adapter worksEN
  • 16. Ports and Adapters ArchitectureLoosely connecting to outside systemsEN

Videos are embedded public YouTube videos. If playback is restricted by the uploader, open them directly on YouTube.

Day 5 · Daily Feedback

Today's Course Satisfaction Survey

After Day 5 class, please answer a short survey. Your answers help us improve the next class and the course.

Open Day 5 SurveyJoin with the button or QR code
Day 5 Daily Feedback Survey QR codeSCAN TO OPENNigeria AI Training · Day 5