π― Architecture Patterns & Core ConceptsΒΆ
Welcome to architecture patterns! This section explains the patterns and principles that Neuroglia is built upon. Each pattern is explained for beginners - you don't need prior knowledge.
π Note: Pattern documentation includes beginner-friendly What & Why sections showing problems and solutions, Common Mistakes with anti-patterns, and When NOT to Use guidance.
π― Why These Patterns?ΒΆ
Neuroglia enforces specific architectural patterns because they solve real problems in software development:
- Maintainability: Code that's easy to change as requirements evolve
- Testability: Components that can be tested in isolation
- Scalability: Architecture that grows with your application
- Clarity: Clear separation of concerns and responsibilities
οΏ½ Quick Start Learning PathΒΆ
New to these patterns? Follow this recommended path:
- Foundation: Clean Architecture - Organizing code in layers
- Dependencies: Dependency Injection - Managing components
- Domain Logic: Domain-Driven Design - Modeling business rules
- Application Layer: CQRS - Separating reads from writes
- Integration: Event-Driven Architecture - Reacting to events
- Data Access: Repository - Abstracting persistence
Already familiar? Jump to any pattern for Neuroglia-specific implementation details.
π‘ What Each Guide IncludesΒΆ
- β The Problem: What happens without this pattern
- β The Solution: How the pattern solves it
- π§ In Neuroglia: Framework implementation details
- π§ͺ Testing: How to test code using this pattern
- β οΈ Common Mistakes: Pitfalls to avoid
- π« When NOT to Use: Scenarios where simpler approaches work better
ποΈ Architectural Approaches: A Comparative IntroductionΒΆ
Before diving into specific patterns, it's essential to understand the different architectural philosophies that drive modern system design. The Neuroglia framework draws from multiple architectural approaches, each with distinct strengths and use cases.
π― Core Philosophy ComparisonΒΆ
Domain-Driven Design (DDD) and Declarative Resource-Oriented Architecture represent two powerful but different approaches to managing complex system states:
- DDD: Models systems around business domains, focusing on behavior and state transitions
- Declarative Architecture: Defines desired end states and uses automated processes to achieve them
π Architectural Patterns OverviewΒΆ
| Architecture | Core Philosophy | Primary Actor | Unit of Work | Source of Truth | Flow of Logic | Error Handling | Typical Domain |
|---|---|---|---|---|---|---|---|
| ποΈ Domain-Driven Design | Model around business domain with AggregateRoot as guardian enforcing business rules | Imperative Command: User/system issues explicit commands (AddToppingToPizza) |
Aggregate: Boundary around business objects with atomic transactions | Application Database: Current aggregate state in database | Synchronous & Explicit: CommandHandler β Repository.Get() β Aggregate.Method() β Repository.Update() |
Throws Exceptions: Business rule violations cause immediate failures | Complex Business Logic: E-commerce, banking, booking systems |
| π Declarative Resource-Oriented | Define desired state and let automated processes achieve it | Declarative Reconciliation: Automated Controller continuously matches actual to desired state | Resource: Self-contained state declaration (e.g., Kubernetes Pod manifest) | Declarative Manifest: Configuration file (YAML) defines desired state | Asynchronous & Looping: Watcher detects change β Controller triggers β Reconciliation Loop β Client.UpdateActualState() |
Retries and Converges: Failed operations retry in next reconciliation cycle | Infrastructure & Systems Management: Kubernetes, Terraform, CloudFormation |
π¨ Practical AnalogiesΒΆ
- DDD is like giving a chef specific recipe instructions: "Add 20g of cheese to the pizza" - explicit commands executed immediately
- Declarative Architecture is like giving the chef a photograph of the final pizza: "Make it look like this" - continuous checking and adjustment until the goal is achieved
π‘ Event-Driven Architecture: The FoundationΒΆ
Event-Driven Architecture (EDA) serves as the postal service π¬ of your system - a foundational pattern enabling reactive communication without tight coupling between components.
ποΈ EDA in Domain-Driven DesignΒΆ
In DDD, EDA handles side effects and communication between different business domains (Bounded Contexts):
- Purpose: Reacting to significant business moments
- Mechanism:
AggregateRootpublishesDomainEvents(e.g.,OrderPaid,PizzaBaked) - Benefit: Highly decoupled systems where services don't need direct knowledge of each other
Example: Orders service publishes OrderPaid β Kitchen service receives event and starts pizza preparation
π EDA in Declarative ArchitectureΒΆ
In declarative systems, EDA powers the reconciliation loop:
- Purpose: Reacting to changes in configuration or state
- Mechanism: Watcher monitors resources β generates events β Controller consumes events and reconciles state
- Benefit: Automated state management with continuous convergence toward desired state
Example: YAML file creates Deployment β API server generates "resource created" event β Deployment controller creates required pods
π Integration SummaryΒΆ
| Architecture | How it uses Event-Driven Architecture (EDA) |
|---|---|
| ποΈ Domain-Driven Design | Uses Domain Events to announce significant business actions, triggering workflows in decoupled business domains |
| π Declarative Architecture | Uses State Change Events (from watchers) to trigger controller reconciliation loops, ensuring actual state matches desired state |
π― Choosing Your ApproachΒΆ
Both patterns leverage EDA for reactive, decoupled systems but differ in event nature and granularity:
- DDD: Focus on high-level business events with rich domain behavior
- Declarative: Focus on low-level resource state changes with automated convergence
The Neuroglia framework provides implementations for both approaches, allowing you to choose the right pattern for each part of your system.
οΏ½ποΈ Pattern OverviewΒΆ
| Pattern | Purpose | Key Concepts | What You'll Learn | Mario's Pizzeria Use Case | When to Use |
|---|---|---|---|---|---|
| ποΈ Clean Architecture | Foundation pattern that organizes code into layers with clear dependency rules | β’ Domain-driven layer separation β’ Dependency inversion principle β’ Business logic isolation β’ Infrastructure abstraction |
β’ Four-layer architecture implementation β’ Dependency flow and injection patterns β’ Domain entity design with business logic β’ Integration layer abstraction |
Order processing across API, Application, Domain, and Integration layers | All applications - structural foundation |
| ποΈ Domain Driven Design | Core domain abstractions and patterns for rich business models with event-driven capabilities | β’ Rich domain entities with business logic β’ Aggregate roots and consistency boundaries β’ Domain events and integration events β’ Event sourcing vs traditional approaches |
β’ Entity and aggregate root implementation β’ Domain event design and handling β’ Transaction flows with multiple events β’ Data flow across architectural layers |
Pizza orders with business rules, events, and cross-layer data flow | Complex business domains, rich models |
| ποΈ Persistence Patterns | Alternative persistence approaches with different complexity levels and capabilities | β’ Simple Entity + State Persistence β’ Complex AggregateRoot + Event Sourcing β’ Hybrid approaches β’ Pattern decision frameworks |
β’ Complexity level comparison β’ Implementation patterns for each approach β’ Decision criteria and guidelines β’ Migration strategies between patterns |
Customer profiles (simple) vs Order processing (complex) patterns | All applications - choose right complexity |
| π Unit of Work Pattern | Coordination layer for domain event collection and dispatching across persistence patterns | β’ Aggregate registration and tracking β’ Automatic event collection β’ Pipeline integration β’ Flexible entity support |
β’ UnitOfWork implementation and usage β’ Event coordination patterns β’ Pipeline behavior integration β’ Testing strategies for event workflows |
Order processing with automatic event dispatching after state persistence | Event-driven systems, domain coordination |
| οΏ½ Pipeline Behaviors | Cross-cutting concerns implemented as composable behaviors around command/query execution | β’ Decorator pattern implementation β’ Behavior chaining and ordering β’ Cross-cutting concerns β’ Pre/post processing logic |
β’ Creating custom pipeline behaviors β’ Behavior registration and ordering β’ Validation, logging, caching patterns β’ Transaction and error handling |
Validation, logging, and transaction management around order processing | Cross-cutting concerns, AOP patterns |
| οΏ½π Dependency Injection | Manages object dependencies and lifecycle through inversion of control patterns | β’ Service registration and resolution β’ Lifetime management patterns β’ Constructor injection β’ Interface-based abstractions |
β’ Service container configuration β’ Lifetime scope patterns β’ Testing with mock dependencies β’ Clean dependency management |
PizzeriaService dependencies managed through DI container | Complex dependency graphs, testability |
| π‘ CQRS & Mediation | Separates read/write operations with mediator pattern for decoupled request handling | β’ Command/Query separation β’ Mediator request routing β’ Pipeline behaviors β’ Handler-based processing |
β’ Command and query handler implementation β’ Mediation pattern usage β’ Cross-cutting concerns via behaviors β’ Event integration with CQRS |
PlaceOrderCommand vs GetOrderQuery with mediator routing | Complex business logic, high-scale systems |
| π Event-Driven Architecture | Implements reactive systems using domain events and event handlers | β’ Domain event patterns β’ Event handlers and workflows β’ Asynchronous processing β’ System decoupling |
β’ Domain event design and publishing β’ Event handler implementation β’ Kitchen workflow automation β’ CloudEvents integration |
OrderPlaced β Kitchen processing β OrderReady β Customer notification | Loose coupling, reactive workflows |
| π― Event Sourcing | Stores state changes as immutable events for complete audit trails and temporal queries | β’ Event-based persistence β’ Aggregate state reconstruction β’ Temporal queries β’ Event replay capabilities |
β’ Event-sourced aggregate design β’ Event store integration β’ Read model projections β’ Business intelligence from events |
Order lifecycle tracked through immutable events with full history | Audit requirements, temporal analysis |
| π Reactive Programming | Enables asynchronous event-driven architectures using Observable streams | β’ Observable stream patterns β’ Asynchronous event processing β’ Stream transformations β’ Background service integration |
β’ RxPY integration patterns β’ Stream processing and subscription β’ Real-time data flows β’ Background service implementation |
Real-time order tracking and kitchen capacity monitoring | Real-time systems, high-throughput events |
| πΎ Repository Pattern | Abstracts data access logic with multiple storage implementations | β’ Data access abstraction β’ Storage implementation flexibility β’ Consistent query interfaces β’ Testing with mock repositories |
β’ Repository interface design β’ Multiple storage backend implementation β’ Async data access patterns β’ Repository testing strategies |
OrderRepository with File, MongoDB, and InMemory implementations | Data persistence, testability |
| π Resource-Oriented Architecture | Resource-oriented design principles for building RESTful APIs and resource-centric applications | β’ Resource identification and modeling β’ RESTful API design principles β’ HTTP verb mapping and semantics β’ Resource lifecycle management |
β’ Resource-oriented design principles β’ RESTful API architecture patterns β’ HTTP protocol integration β’ Resource state management |
Orders, Menu, Kitchen as REST resources with full CRUD operations | RESTful APIs, microservices |
| π Watcher & Reconciliation Patterns | Kubernetes-inspired patterns for watching resource changes and implementing reconciliation loops | β’ Resource state observation β’ Reconciliation loop patterns β’ Event-driven state management β’ Declarative resource management |
β’ Resource watching implementation β’ Reconciliation loop design β’ Event-driven update patterns β’ State synchronization strategies |
Kitchen capacity monitoring and order queue reconciliation | Reactive systems, state synchronization |
| β‘ Watcher & Reconciliation Execution | Execution engine for watcher and reconciliation patterns with error handling and monitoring | β’ Execution orchestration β’ Error handling and recovery β’ Performance monitoring β’ Reliable state persistence |
β’ Execution pipeline design β’ Error handling strategies β’ Monitoring and observability β’ Performance optimization |
Automated kitchen workflow execution with retry logic and monitoring | Production systems, reliability requirements |
π Mario's Pizzeria: Unified ExampleΒΆ
All patterns use Mario's Pizzeria as a consistent domain example, showing how patterns work together in a real-world system:
graph TB
subgraph "ποΈ Clean Architecture Layers"
API[π API Layer<br/>Controllers & DTOs]
APP[πΌ Application Layer<br/>Commands & Queries]
DOM[ποΈ Domain Layer<br/>Entities & Events]
INT[π Integration Layer<br/>Repositories & Services]
end
subgraph "π‘ CQRS Implementation"
CMD[Commands<br/>PlaceOrder, StartCooking]
QRY[Queries<br/>GetOrder, GetMenu]
end
subgraph "π Event-Driven Flow"
EVT[Domain Events<br/>OrderPlaced, OrderReady]
HDL[Event Handlers<br/>Kitchen, Notifications]
end
subgraph "πΎ Data Access"
REPO[Repositories<br/>Order, Menu, Customer]
STOR[Storage<br/>File, MongoDB, Memory]
end
API --> APP
APP --> DOM
APP --> INT
APP --> CMD
APP --> QRY
DOM --> EVT
EVT --> HDL
INT --> REPO
REPO --> STOR
style API fill:#e3f2fd
style APP fill:#f3e5f5
style DOM fill:#e8f5e8
style INT fill:#fff3e0
π Pattern IntegrationΒΆ
How Patterns Work TogetherΒΆ
| Order | Pattern | Role in System | Dependencies | Integration Points |
|---|---|---|---|---|
| 1 | Clean Architecture | Structural foundation | None | Provides layer structure for all other patterns |
| 2 | Dependency Injection | Service management foundation | Clean Architecture | Manages service lifetimes across all layers |
| 3 | CQRS & Mediation | Application layer organization | Clean Architecture, DI | Commands/Queries with mediator routing |
| 4 | Event-Driven | Reactive domain workflows | Clean Architecture, CQRS, DI | Domain events published by command handlers |
| 5 | Event Sourcing | Event-based persistence | Event-Driven, Repository, DI | Events as source of truth with aggregate patterns |
| 6 | Reactive Programming | Asynchronous stream processing | Event-Driven, DI | Observable streams for real-time event processing |
| 7 | Repository | Infrastructure abstraction | Clean Architecture, DI | Implements Integration layer data access |
| 8 | Resource-Oriented | API contract definition | Clean Architecture, CQRS, DI | REST endpoints expose commands/queries |
| 9 | Watcher & Reconciliation | Reactive resource management | Event-Driven, Repository, DI | Observes events, updates via repositories |
Implementation OrderΒΆ
flowchart LR
A[1. Clean Architecture<br/>ποΈ Layer Structure] --> B[2. Dependency Injection<br/>π Service Management]
B --> C[3. CQRS & Mediation<br/>π‘ Commands & Queries]
C --> D[4. Event-Driven<br/>π Domain Events]
D --> E[5. Event Sourcing<br/>π― Event Persistence]
E --> F[6. Reactive Programming<br/>π Stream Processing]
F --> G[7. Repository Pattern<br/>πΎ Data Access]
G --> H[8. Resource-Oriented<br/>π API Design]
H --> I[9. Watcher Patterns<br/>π Reactive Management]
style A fill:#e8f5e8
style B fill:#f8bbd9
style C fill:#e3f2fd
style D fill:#fff3e0
style E fill:#ffecb5
style F fill:#b3e5fc
style G fill:#f3e5f5
style H fill:#e1f5fe
style I fill:#fce4ec
π― Business Domain ExamplesΒΆ
| Domain Area | Pattern Application | Implementation Details | Benefits Demonstrated |
|---|---|---|---|
| π Order Processing | Clean Architecture + CQRS + Event Sourcing + DI | Complete workflow from placement to delivery with event history | Layer separation, mediation routing, audit trails, service management |
| π Menu Management | Repository + Resource-Oriented + DI | Product catalog with pricing and availability via REST API | Data abstraction, RESTful design, dependency management |
| π¨βπ³ Kitchen Operations | Event-Driven + Reactive Programming + Watcher Patterns | Real-time queue management with stream processing | Reactive processing, observable streams, state synchronization |
| π± Customer Communications | Event-Driven + Reactive Programming | Real-time notifications through reactive event streams | Stream processing, asynchronous messaging, real-time updates |
| π³ Payment Processing | Clean Architecture + Repository + DI | External service integration with proper abstraction | Infrastructure abstraction, testability, service integration |
| π Analytics & Reporting | Event Sourcing + Reactive Programming | Business intelligence from event streams with real-time views | Temporal queries, stream aggregation, historical analysis |
π§ͺ Testing StrategiesΒΆ
| Testing Type | Scope | Pattern Focus | Tools & Techniques | Example Scenarios |
|---|---|---|---|---|
| π¬ Unit Testing | Individual components | All patterns with isolated mocks | pytest, Mock objects, dependency injection | Test OrderEntity business logic, Command handlers |
| π Integration Testing | Cross-layer interactions | Clean Architecture layer communication | TestClient, database containers | Test API β Application β Domain flow |
| π End-to-End Testing | Complete workflows | Full pattern integration | Automated scenarios, real dependencies | Complete pizza order workflow validation |
| β‘ Performance Testing | Scalability validation | CQRS read optimization, Event throughput | Load testing, metrics collection | Query performance, event processing rates |
π Pattern Learning PathsΒΆ
| Level | Focus Area | Recommended Patterns | Learning Objectives | Practical Outcomes |
|---|---|---|---|---|
| π± Beginner | Foundation & Structure | 1. Clean Architecture 2. Domain Driven Design 3. Dependency Injection 4. Repository Pattern |
β’ Layer separation principles β’ Rich domain model design β’ Service lifetime management β’ Data access abstraction |
Pizza ordering system with rich domain models and proper DI |
| π Intermediate | Separation & Optimization | 1. CQRS & Mediation 2. Event-Driven Architecture 3. Resource-Oriented Architecture |
β’ Read/write operation separation β’ Mediator pattern usage β’ Event-driven workflows β’ RESTful API design |
Scalable pizza API with command/query separation and events |
| β‘ Advanced | Reactive & Distributed | 1. Event Sourcing 2. Reactive Programming 3. Watcher & Reconciliation |
β’ Event-based persistence β’ Stream processing patterns β’ Reactive system design β’ State reconciliation strategies |
Complete event-sourced pizzeria with real-time capabilities |
π Related DocumentationΒΆ
- π Framework Features - Implementation-specific features
- π Implementation Guides - Step-by-step tutorials
- π Mario's Pizzeria - Complete system example
- πΌ Sample Applications - Production-ready examples
- π OAuth, OIDC & JWT - Authentication and authorization patterns
These patterns form the architectural foundation for building maintainable, testable, and scalable applications. Each pattern page includes detailed code examples, Mermaid diagrams, and practical implementation guidance using the Mario's Pizzeria domain.