Architecture Patterns
Consolidated architecture validation and enforcement patterns covering clean architecture, backend layer separation, project structure conventions, and test standards. Each category has individual rule files in references/ loaded on-demand.
Quick Reference
| Category |
Rules |
Impact |
When to Use |
| Clean Architecture |
3 |
HIGH |
SOLID principles, hexagonal architecture, ports & adapters, DDD |
| Project Structure |
2 |
HIGH |
Folder conventions, nesting depth, import direction, barrel files |
| Backend Layers |
3 |
HIGH |
Router/service/repository separation, DI, file naming |
| Test Standards |
3 |
MEDIUM |
AAA pattern, naming conventions, coverage thresholds |
| Right-Sizing |
2 |
HIGH |
Architecture tier selection, over-engineering prevention, context-aware enforcement |
Total: 13 rules across 5 categories
Quick Start
# Clean Architecture: Dependency Inversion via Protocol
class IUserRepository(Protocol):
async def get_by_id(self, id: str) -> User | None: ...
class UserService:
def __init__(self, repo: IUserRepository):
self._repo = repo # Depends on abstraction, not concretion
# FastAPI DI chain: DB -> Repository -> Service
def get_user_service(db: AsyncSession = Depends(get_db)) -> UserService:
return UserService(PostgresUserRepository(db))
# Project Structure: Unidirectional Import Architecture
shared/lib -> components -> features -> app
(lowest) (highest)
# Backend Layers: Strict Separation
Routers (HTTP) -> Services (Business Logic) -> Repositories (Data Access)
Clean Architecture
SOLID principles, hexagonal architecture, ports and adapters, and DDD tactical patterns for maintainable backends.
| Rule |
File |
Key Pattern |
| Hexagonal Architecture |
${CLAUDE_SKILL_DIR}/references/clean-hexagonal-ports-adapters.md |
Driving/driven ports, adapter implementations, layer structure |
| SOLID & Dependency Rule |
${CLAUDE_SKILL_DIR}/references/clean-solid-dependency-rule.md |
Protocol-based interfaces, dependency inversion, FastAPI DI |
| DDD Tactical Patterns |
${CLAUDE_SKILL_DIR}/references/clean-ddd-tactical-patterns.md |
Entities, value objects, aggregate roots, domain events |
Key Decisions
| Decision |
Recommendation |
| Protocol vs ABC |
Protocol (structural typing) |
| Dataclass vs Pydantic |
Dataclass for domain, Pydantic for API |
| Repository granularity |
One per aggregate root |
| Transaction boundary |
Service layer, not repository |
| Event publishing |
Collect in aggregate, publish after commit |
Project Structure
Feature-based organization, max nesting depth, unidirectional imports, and barrel file prevention.
| Rule |
File |
Key Pattern |
| Folder Structure & Nesting |
${CLAUDE_SKILL_DIR}/references/structure-folder-conventions.md |
React/Next.js and FastAPI layouts, 4-level max nesting, barrel file rules |
| Import Direction & Location |
${CLAUDE_SKILL_DIR}/references/structure-import-direction.md |
Unidirectional imports, cross-feature prevention, component/hook placement |
Blocking Rules
| Rule |
Check |
| Max Nesting |
Max 4 levels from src/ or app/ |
| No Barrel Files |
No index.ts re-exports (tree-shaking issues) |
| Component Location |
React components in components/ or features/ only |
| Hook Location |
Custom hooks in hooks/ or features/*/hooks/ only |
| Import Direction |
Unidirectional: shared -> components -> features -> app |
Backend Layers
FastAPI Clean Architecture with router/service/repository layer separation and blocking validation.
| Rule |
File |
Key Pattern |
| Layer Separation |
${CLAUDE_SKILL_DIR}/references/backend-layer-separation.md |
Router/service/repository boundaries, forbidden patterns, async rules |
| Dependency Injection |
${CLAUDE_SKILL_DIR}/references/backend-dependency-injection.md |
Depends() chains, auth patterns, testing with DI overrides |
| File Naming & Exceptions |
${CLAUDE_SKILL_DIR}/references/backend-naming-exceptions.md |
Naming conventions, domain exceptions, violation detection |
Layer Boundaries
| Layer |
Responsibility |
Forbidden |
| Routers |
HTTP concerns, request parsing, auth checks |
Database operations, business logic |
| Services |
Business logic, validation, orchestration |
HTTPException, Request objects |
| Repositories |
Data access, queries, persistence |
HTTP concerns, business logic |
Test Standards
Testing best practices with AAA pattern, naming conventions, isolation, and coverage thresholds.
| Rule |
File |
Key Pattern |
| AAA Pattern & Isolation |
${CLAUDE_SKILL_DIR}/references/testing-aaa-isolation.md |
Arrange-Act-Assert, test isolation, parameterized tests |
| Naming Conventions |
${CLAUDE_SKILL_DIR}/references/testing-naming-conventions.md |
Descriptive behavior-focused names for Python and TypeScript |
| Coverage & Location |
${CLAUDE_SKILL_DIR}/references/testing-coverage-location.md |
Coverage thresholds, fixture scopes, test file placement rules |
Coverage Requirements
| Area |
Minimum |
Target |
| Overall |
80% |
90% |
| Business Logic |
90% |
100% |
| Critical Paths |
95% |
100% |
| New Code |
100% |
100% |
Right-Sizing
Context-aware backend architecture enforcement. Rules adjust strictness based on project tier detected by scope-appropriate-architecture.
Enforcement procedure:
- Read project tier from
scope-appropriate-architecture context (set during brainstorm/implement Step 0)
- If no tier set, auto-detect using signals in
Read("${CLAUDE_SKILL_DIR}/rules/right-sizing-tiers.md")
- Apply tier-based enforcement matrix — skip rules marked OFF for detected tier
- Security rules are tier-independent — always enforce SQL parameterization, input validation, auth checks
| Rule |
File |
Key Pattern |
| Architecture Sizing Tiers |
${CLAUDE_SKILL_DIR}/rules/right-sizing-tiers.md |
Interview/MVP/production/enterprise sizing matrix, LOC estimates, detection signals |
| Right-Sizing Decision Guide |
${CLAUDE_SKILL_DIR}/rules/right-sizing-decision.md |
ORM, auth, error handling, testing recommendations per tier, over-engineering tax |
Tier-Based Rule Enforcement
| Rule |
Interview |
MVP |
Production |
Enterprise |
| Layer separation |
OFF |
WARN |
BLOCK |
BLOCK |
| Repository pattern |
OFF |
OFF |
WARN |
BLOCK |
| Domain exceptions |
OFF |
OFF |
BLOCK |
BLOCK |
| Dependency injection |
OFF |
WARN |
BLOCK |
BLOCK |
| OpenAPI documentation |
OFF |
OFF |
WARN |
BLOCK |
Manual override: User can set tier explicitly to bypass auto-detection (e.g., "I want enterprise patterns for this take-home to demonstrate skill").
Decision Flowchart
Is this a take-home or hackathon?
YES --> Flat architecture. Single file or 3-5 files. Done.
NO -->
Is this a prototype or MVP with < 3 months runway?
YES --> Simple layered. Routes + services + models. No abstractions.
NO -->
Do you have > 5 engineers or complex domain rules?
YES --> Clean architecture with ports/adapters.
NO --> Layered architecture. Add abstractions only when pain appears.
When NOT to Use
Not every project needs architecture patterns. Match complexity to project tier:
| Pattern |
Interview |
Hackathon |
MVP |
Growth |
Enterprise |
Simpler Alternative |
| Repository pattern |
OVERKILL (~200 LOC) |
OVERKILL |
BORDERLINE |
APPROPRIATE |
REQUIRED |
Direct ORM calls in service (~20 LOC) |
| DI containers |
OVERKILL (~150 LOC) |
OVERKILL |
LIGHT ONLY |
APPROPRIATE |
REQUIRED |
Constructor params or module-level singletons (~10 LOC) |
| Event-driven arch |
OVERKILL (~300 LOC) |
OVERKILL |
OVERKILL |
SELECTIVE |
APPROPRIATE |
Direct function calls between services (~30 LOC) |
| Hexagonal architecture |
OVERKILL (~400 LOC) |
OVERKILL |
OVERKILL |
BORDERLINE |
APPROPRIATE |
Flat modules with imports (~50 LOC) |
| Strict layer separation |
OVERKILL (~250 LOC) |
OVERKILL |
WARN |
BLOCK |
BLOCK |
Routes + models in same file (~40 LOC) |
| Domain exceptions |
OVERKILL (~100 LOC) |
OVERKILL |
OVERKILL |
BLOCK |
BLOCK |
Built-in ValueError/HTTPException (~5 LOC) |
Rule of thumb: If a pattern shows OVERKILL for the detected tier, do NOT use it. Use the simpler alternative. A take-home with hexagonal architecture signals over-engineering, not skill.
Anti-Patterns (FORBIDDEN)
# CLEAN ARCHITECTURE
# NEVER import infrastructure in domain layer
from app.infrastructure.database import engine # In domain layer!
# NEVER leak ORM models to API layer
@router.get("/users/{id}")
async def get_user(id: str, db: Session) -> UserModel: # Returns ORM model!
# NEVER have domain depend on framework
from fastapi import HTTPException
class UserService:
def get(self, id: str):
raise HTTPException(404) # Framework in domain!
# PROJECT STRUCTURE
# NEVER create files deeper than 4 levels from src/
# NEVER create barrel files (index.ts re-exports)
# NEVER import from higher layers (features importing from app)
# NEVER import across features (use shared/ for common code)
# BACKEND LAYERS
# NEVER use database operations in routers
# NEVER raise HTTPException in services
# NEVER instantiate services without Depends()
# TEST STANDARDS
# NEVER mix test files with source code
# NEVER use non-descriptive test names (test1, test, works)
# NEVER share mutable state between tests without reset
Related Skills
ork:scope-appropriate-architecture - Project tier detection that drives right-sizing enforcement
ork:quality-gates - YAGNI gate uses tier context to validate complexity
ork:distributed-systems - Distributed locking, resilience, idempotency patterns
ork:api-design - REST API design, versioning, error handling
ork:testing-unit - Unit testing: AAA pattern, fixtures, mocking, factories
ork:testing-e2e - E2E testing: Playwright, page objects, visual regression
ork:testing-integration - Integration testing: API endpoints, database, contracts
ork:python-backend - FastAPI, SQLAlchemy, asyncio patterns
ork:database-patterns - Schema design, query optimization, migrations
Converted and distributed by TomeVault — claim your Tome and manage your conversions.
1---2name: architecture-patterns-113description: Architecture validation and patterns for clean architecture, backend structure enforcement, project structure validation, test standards, and context-aware sizing. Use when designing system boundaries, enforcing layered architecture, validating project structure, defining test standards, or choosing the right architecture tier for project scope. Use when this capability is needed.4---56# Architecture Patterns78Consolidated architecture validation and enforcement patterns covering clean architecture, backend layer separation, project structure conventions, and test standards. Each category has individual rule files in `references/` loaded on-demand.910## Quick Reference1112| Category | Rules | Impact | When to Use |13|----------|-------|--------|-------------|14| [Clean Architecture](#clean-architecture) | 3 | HIGH | SOLID principles, hexagonal architecture, ports & adapters, DDD |15| [Project Structure](#project-structure) | 2 | HIGH | Folder conventions, nesting depth, import direction, barrel files |16| [Backend Layers](#backend-layers) | 3 | HIGH | Router/service/repository separation, DI, file naming |17| [Test Standards](#test-standards) | 3 | MEDIUM | AAA pattern, naming conventions, coverage thresholds |18| [Right-Sizing](#right-sizing) | 2 | HIGH | Architecture tier selection, over-engineering prevention, context-aware enforcement |1920**Total: 13 rules across 5 categories**2122## Quick Start2324```python25# Clean Architecture: Dependency Inversion via Protocol26class IUserRepository(Protocol):27 async def get_by_id(self, id: str) -> User | None: ...2829class UserService:30 def __init__(self, repo: IUserRepository):31 self._repo = repo # Depends on abstraction, not concretion3233# FastAPI DI chain: DB -> Repository -> Service34def get_user_service(db: AsyncSession = Depends(get_db)) -> UserService:35 return UserService(PostgresUserRepository(db))36```3738```39# Project Structure: Unidirectional Import Architecture40shared/lib -> components -> features -> app41(lowest) (highest)4243# Backend Layers: Strict Separation44Routers (HTTP) -> Services (Business Logic) -> Repositories (Data Access)45```4647## Clean Architecture4849SOLID principles, hexagonal architecture, ports and adapters, and DDD tactical patterns for maintainable backends.5051| Rule | File | Key Pattern |52|------|------|-------------|53| Hexagonal Architecture | `${CLAUDE_SKILL_DIR}/references/clean-hexagonal-ports-adapters.md` | Driving/driven ports, adapter implementations, layer structure |54| SOLID & Dependency Rule | `${CLAUDE_SKILL_DIR}/references/clean-solid-dependency-rule.md` | Protocol-based interfaces, dependency inversion, FastAPI DI |55| DDD Tactical Patterns | `${CLAUDE_SKILL_DIR}/references/clean-ddd-tactical-patterns.md` | Entities, value objects, aggregate roots, domain events |5657### Key Decisions5859| Decision | Recommendation |60|----------|----------------|61| Protocol vs ABC | Protocol (structural typing) |62| Dataclass vs Pydantic | Dataclass for domain, Pydantic for API |63| Repository granularity | One per aggregate root |64| Transaction boundary | Service layer, not repository |65| Event publishing | Collect in aggregate, publish after commit |6667## Project Structure6869Feature-based organization, max nesting depth, unidirectional imports, and barrel file prevention.7071| Rule | File | Key Pattern |72|------|------|-------------|73| Folder Structure & Nesting | `${CLAUDE_SKILL_DIR}/references/structure-folder-conventions.md` | React/Next.js and FastAPI layouts, 4-level max nesting, barrel file rules |74| Import Direction & Location | `${CLAUDE_SKILL_DIR}/references/structure-import-direction.md` | Unidirectional imports, cross-feature prevention, component/hook placement |7576### Blocking Rules7778| Rule | Check |79|------|-------|80| Max Nesting | Max 4 levels from src/ or app/ |81| No Barrel Files | No index.ts re-exports (tree-shaking issues) |82| Component Location | React components in components/ or features/ only |83| Hook Location | Custom hooks in hooks/ or features/*/hooks/ only |84| Import Direction | Unidirectional: shared -> components -> features -> app |8586## Backend Layers8788FastAPI Clean Architecture with router/service/repository layer separation and blocking validation.8990| Rule | File | Key Pattern |91|------|------|-------------|92| Layer Separation | `${CLAUDE_SKILL_DIR}/references/backend-layer-separation.md` | Router/service/repository boundaries, forbidden patterns, async rules |93| Dependency Injection | `${CLAUDE_SKILL_DIR}/references/backend-dependency-injection.md` | Depends() chains, auth patterns, testing with DI overrides |94| File Naming & Exceptions | `${CLAUDE_SKILL_DIR}/references/backend-naming-exceptions.md` | Naming conventions, domain exceptions, violation detection |9596### Layer Boundaries9798| Layer | Responsibility | Forbidden |99|-------|---------------|-----------|100| Routers | HTTP concerns, request parsing, auth checks | Database operations, business logic |101| Services | Business logic, validation, orchestration | HTTPException, Request objects |102| Repositories | Data access, queries, persistence | HTTP concerns, business logic |103104## Test Standards105106Testing best practices with AAA pattern, naming conventions, isolation, and coverage thresholds.107108| Rule | File | Key Pattern |109|------|------|-------------|110| AAA Pattern & Isolation | `${CLAUDE_SKILL_DIR}/references/testing-aaa-isolation.md` | Arrange-Act-Assert, test isolation, parameterized tests |111| Naming Conventions | `${CLAUDE_SKILL_DIR}/references/testing-naming-conventions.md` | Descriptive behavior-focused names for Python and TypeScript |112| Coverage & Location | `${CLAUDE_SKILL_DIR}/references/testing-coverage-location.md` | Coverage thresholds, fixture scopes, test file placement rules |113114### Coverage Requirements115116| Area | Minimum | Target |117|------|---------|--------|118| Overall | 80% | 90% |119| Business Logic | 90% | 100% |120| Critical Paths | 95% | 100% |121| New Code | 100% | 100% |122123## Right-Sizing124125Context-aware backend architecture enforcement. Rules adjust strictness based on project tier detected by `scope-appropriate-architecture`.126127**Enforcement procedure:**1281. Read project tier from `scope-appropriate-architecture` context (set during brainstorm/implement Step 0)1292. If no tier set, auto-detect using signals in `Read("${CLAUDE_SKILL_DIR}/rules/right-sizing-tiers.md")`1303. Apply tier-based enforcement matrix — skip rules marked OFF for detected tier1314. **Security rules are tier-independent** — always enforce SQL parameterization, input validation, auth checks132133| Rule | File | Key Pattern |134|------|------|-------------|135| Architecture Sizing Tiers | `${CLAUDE_SKILL_DIR}/rules/right-sizing-tiers.md` | Interview/MVP/production/enterprise sizing matrix, LOC estimates, detection signals |136| Right-Sizing Decision Guide | `${CLAUDE_SKILL_DIR}/rules/right-sizing-decision.md` | ORM, auth, error handling, testing recommendations per tier, over-engineering tax |137138### Tier-Based Rule Enforcement139140| Rule | Interview | MVP | Production | Enterprise |141|------|-----------|-----|------------|------------|142| Layer separation | OFF | WARN | BLOCK | BLOCK |143| Repository pattern | OFF | OFF | WARN | BLOCK |144| Domain exceptions | OFF | OFF | BLOCK | BLOCK |145| Dependency injection | OFF | WARN | BLOCK | BLOCK |146| OpenAPI documentation | OFF | OFF | WARN | BLOCK |147148**Manual override:** User can set tier explicitly to bypass auto-detection (e.g., "I want enterprise patterns for this take-home to demonstrate skill").149150### Decision Flowchart151152```153Is this a take-home or hackathon?154 YES --> Flat architecture. Single file or 3-5 files. Done.155 NO -->156157Is this a prototype or MVP with < 3 months runway?158 YES --> Simple layered. Routes + services + models. No abstractions.159 NO -->160161Do you have > 5 engineers or complex domain rules?162 YES --> Clean architecture with ports/adapters.163 NO --> Layered architecture. Add abstractions only when pain appears.164```165166## When NOT to Use167168Not every project needs architecture patterns. Match complexity to project tier:169170| Pattern | Interview | Hackathon | MVP | Growth | Enterprise | Simpler Alternative |171|---------|-----------|-----------|-----|--------|------------|---------------------|172| Repository pattern | OVERKILL (~200 LOC) | OVERKILL | BORDERLINE | APPROPRIATE | REQUIRED | Direct ORM calls in service (~20 LOC) |173| DI containers | OVERKILL (~150 LOC) | OVERKILL | LIGHT ONLY | APPROPRIATE | REQUIRED | Constructor params or module-level singletons (~10 LOC) |174| Event-driven arch | OVERKILL (~300 LOC) | OVERKILL | OVERKILL | SELECTIVE | APPROPRIATE | Direct function calls between services (~30 LOC) |175| Hexagonal architecture | OVERKILL (~400 LOC) | OVERKILL | OVERKILL | BORDERLINE | APPROPRIATE | Flat modules with imports (~50 LOC) |176| Strict layer separation | OVERKILL (~250 LOC) | OVERKILL | WARN | BLOCK | BLOCK | Routes + models in same file (~40 LOC) |177| Domain exceptions | OVERKILL (~100 LOC) | OVERKILL | OVERKILL | BLOCK | BLOCK | Built-in ValueError/HTTPException (~5 LOC) |178179**Rule of thumb:** If a pattern shows OVERKILL for the detected tier, do NOT use it. Use the simpler alternative. A take-home with hexagonal architecture signals over-engineering, not skill.180181## Anti-Patterns (FORBIDDEN)182183```python184# CLEAN ARCHITECTURE185# NEVER import infrastructure in domain layer186from app.infrastructure.database import engine # In domain layer!187188# NEVER leak ORM models to API layer189@router.get("/users/{id}")190async def get_user(id: str, db: Session) -> UserModel: # Returns ORM model!191192# NEVER have domain depend on framework193from fastapi import HTTPException194class UserService:195 def get(self, id: str):196 raise HTTPException(404) # Framework in domain!197198# PROJECT STRUCTURE199# NEVER create files deeper than 4 levels from src/200# NEVER create barrel files (index.ts re-exports)201# NEVER import from higher layers (features importing from app)202# NEVER import across features (use shared/ for common code)203204# BACKEND LAYERS205# NEVER use database operations in routers206# NEVER raise HTTPException in services207# NEVER instantiate services without Depends()208209# TEST STANDARDS210# NEVER mix test files with source code211# NEVER use non-descriptive test names (test1, test, works)212# NEVER share mutable state between tests without reset213```214215## Related Skills216217- `ork:scope-appropriate-architecture` - Project tier detection that drives right-sizing enforcement218- `ork:quality-gates` - YAGNI gate uses tier context to validate complexity219- `ork:distributed-systems` - Distributed locking, resilience, idempotency patterns220- `ork:api-design` - REST API design, versioning, error handling221- `ork:testing-unit` - Unit testing: AAA pattern, fixtures, mocking, factories222- `ork:testing-e2e` - E2E testing: Playwright, page objects, visual regression223- `ork:testing-integration` - Integration testing: API endpoints, database, contracts224- `ork:python-backend` - FastAPI, SQLAlchemy, asyncio patterns225- `ork:database-patterns` - Schema design, query optimization, migrations226227---228> Converted and distributed by [TomeVault](https://tomevault.io/claim/yonatangross) — claim your Tome and manage your conversions.229<!-- tomevault:4.0:skill_md:2026-04-11 -->