Skip to content

LBS Foundry Architecture Overview

This guide provides a comprehensive overview of the LBS Foundry architecture, design patterns, and core principles.

High-Level Architecture

LBS Foundry is built using a modular monolith architecture with clear separation of concerns and modern design patterns.

┌─────────────────────────────────────────────────────────────────┐
│                           LBS Foundry                          │
├─────────────────────────────────────────────────────────────────┤
│                        Presentation Layer                       │
│  ┌─────────────────┐  ┌─────────────────┐  ┌─────────────────┐ │
│  │   SvelteKit     │  │   FastEndpoints │  │   OpenAPI Docs  │ │
│  │   (Frontend)    │  │   (REST API)    │  │   (Swagger)     │ │
│  └─────────────────┘  └─────────────────┘  └─────────────────┘ │
├─────────────────────────────────────────────────────────────────┤
│                       Application Layer                         │
│  ┌─────────────────┐  ┌─────────────────┐  ┌─────────────────┐ │
│  │   Commands      │  │    Queries      │  │    Imports      │ │
│  │  (Write Side)   │  │  (Read Side)    │  │ (Data Ingestion)│ │
│  └─────────────────┘  └─────────────────┘  └─────────────────┘ │
├─────────────────────────────────────────────────────────────────┤
│                         Domain Layer                            │
│  ┌─────────────────┐  ┌─────────────────┐  ┌─────────────────┐ │
│  │   Aggregates    │  │     Events      │  │   Projections   │ │
│  │ (Business Logic)│  │ (Event Store)   │  │ (Read Models)   │ │
│  └─────────────────┘  └─────────────────┘  └─────────────────┘ │
├─────────────────────────────────────────────────────────────────┤
│                      Infrastructure Layer                       │
│  ┌─────────────────┐  ┌─────────────────┐  ┌─────────────────┐ │
│  │   PostgreSQL    │  │   Background    │  │   External      │ │
│  │   (Marten)      │  │     Jobs        │  │     APIs        │ │
│  └─────────────────┘  └─────────────────┘  └─────────────────┘ │
└─────────────────────────────────────────────────────────────────┘

Core Architectural Patterns

1. Event Sourcing

  • All state changes captured as immutable events
  • Complete audit trail and replay capability
  • Event store implemented with Marten/PostgreSQL
  • See Event Sourcing Guide

2. CQRS (Command Query Responsibility Segregation)

  • Separate models for read and write operations
  • Commands: Modify state and generate events
  • Queries: Optimized read models and projections
  • See Query/Command Alignment Design

3. Domain-Driven Design (DDD)

4. Hexagonal Architecture

  • Clean separation of concerns
  • Domain logic independent of infrastructure
  • Dependency injection and inversion of control

Project Structure

src/
├── Apps/                           # Application entry points
│   ├── LBS.Api/                   # Main REST API (FastEndpoints)
│   └── foundry-web/               # SvelteKit frontend application
├── Aspire/                        # .NET Aspire orchestration
│   └── LBS.AspireHost/            # Development host
├── Core/                          # Shared core libraries
│   ├── LBS.Anchor/               # Foundation utilities (no dependencies)
│   ├── LBS.Augment/              # Extended utilities (external deps)
│   └── EventSourcing/            # Event sourcing framework
├── Domain/                        # Domain logic and infrastructure
│   ├── LBS.Domain.Core/          # Core domain (Users, Teams, etc.)
│   ├── LBS.Domain.Fantasy/       # Fantasy sports domain
│   └── LBS.Domain.Infrastructure/ # Infrastructure implementations
├── DataHarvesters/                # External data ingestion
└── Tests/                         # Unit and integration tests

Core Components

Domain Aggregates

  • Competition: Sports competitions (NRL, AFL, etc.)
  • Season: Competition seasons and rounds
  • SportingEvent: Individual games/matches
  • Team: Sports teams and rosters
  • Participant: Individual players/athletes
  • User: System users and authentication
  • RugbyGameState: Real-time game state

Infrastructure Services

  • Command Execution: SecurityCommandExecutor with authorization
  • Query Processing: SecurityQueryService with role-based access
  • Data Import: IImporter pattern for bulk operations
  • Background Jobs: Declarative [Timer] attributes and BackgroundService implementations
  • Authentication: Dual auth (Clerk + Basic)

External Integrations

  • Fox Sports API: Live sports data
  • NRL API: Official rugby league data
  • Clerk: User authentication and management
  • Azure Services: Storage and hosting

Security Architecture

Authentication Methods

┌─────────────────┐    ┌─────────────────┐
│  Human Users    │    │ Service Accounts│
│                 │    │                 │
│ Clerk JWT ──────┼────┤ Basic Auth      │
│ Frontend Auth   │    │ API Access      │
│ User Management │    │ M2M Integration │
└─────────────────┘    └─────────────────┘
           │                     │
           └─────────┬───────────┘
              ┌─────────────────┐
              │  LBS Foundry    │
              │  Authorization  │
              │  System         │
              └─────────────────┘

Authorization Flow

  1. Authentication at endpoint level
  2. Authorization at executor level via SecurityCommandExecutor/SecurityQueryService
  3. Role-based access control using [RequiresRoles] attribute
  4. System bypass for internal operations

See Security Guide for complete details.

Data Flow Patterns

Command Flow (Write Operations)

HTTP Request → CommandEndpoint → SecurityCommandExecutor → Aggregate → Events → Event Store
                                                              Projections → Read Models

Query Flow (Read Operations)

HTTP Request → ReadModelEndpoint → SecurityQueryService → Query Handler → Read Models → Response

Import Flow (Data Ingestion)

External Data → ImportEndpoint → IImporter → Commands → SecurityCommandExecutor → Events

Layered Architecture

1. Presentation Layer

  • SvelteKit Frontend: User interface and interactions
  • FastEndpoints: REST API with OpenAPI documentation
  • Authentication: JWT validation and user context

2. Application Layer

  • Commands: Business operations that modify state
  • Queries: Data retrieval with optimized projections
  • Imports: Bulk data operations and transformations
  • Security: Role-based authorization enforcement

3. Domain Layer

  • Aggregates: Business entities with behavior
  • Events: Domain events representing state changes
  • Value Objects: Immutable domain concepts
  • Domain Services: Cross-aggregate business logic

4. Infrastructure Layer

  • Event Store: Marten/PostgreSQL for event persistence
  • Projections: Read model building from events
  • External APIs: Integration with third-party services
  • Background Jobs: Scheduled and triggered processing

Design Principles

SOLID Principles

  • Single Responsibility: Each class has one reason to change
  • Open/Closed: Open for extension, closed for modification
  • Liskov Substitution: Subtypes must be substitutable
  • Interface Segregation: Many specific interfaces over one general
  • Dependency Inversion: Depend on abstractions, not concretions

Domain-Driven Design

  • Ubiquitous Language: Shared vocabulary between business and tech
  • Bounded Contexts: Clear boundaries between domain areas
  • Aggregate Boundaries: Consistency boundaries within the domain
  • Event-First Design: Events as first-class citizens

Event Sourcing Principles

  • Immutable Events: Events never change once stored
  • Complete Audit Trail: Every state change is recorded
  • Temporal Queries: Query state at any point in time
  • Event Versioning: Handle schema evolution gracefully

Performance Considerations

Read Performance

  • CQRS Projections: Optimized read models
  • Database Indexing: Strategic indexes on query patterns
  • Caching: Memory caching for frequently accessed data
  • Async Operations: Non-blocking I/O operations

Write Performance

  • Event Batching: Process multiple events together
  • Background Processing: Offload heavy operations
  • Connection Pooling: Efficient database connections
  • Command Validation: Early validation to prevent failures

Scalability

  • Horizontal Scaling: Stateless application design
  • Database Scaling: Read replicas and partitioning
  • Event Store Optimization: Efficient event storage patterns
  • Resource Management: Proper disposal and memory management

Monitoring & Observability

Logging

  • Structured Logging: JSON-formatted logs with context
  • Security Logging: Complete audit trail for authorization
  • Performance Logging: Request timing and resource usage
  • Error Logging: Detailed error context and stack traces

Metrics

  • Application Metrics: Request rates, response times
  • Business Metrics: Domain-specific KPIs
  • Infrastructure Metrics: Database, CPU, memory usage
  • Security Metrics: Authentication attempts, authorization failures

Tracing

  • Distributed Tracing: Request flow across services
  • Command Tracing: Complete command execution path
  • Query Tracing: Read operation performance analysis
  • Background Job Tracing: Async operation monitoring

Next Steps

For New Developers

  1. Start with Event Sourcing Guide
  2. Understand Query/Command alignment
  3. Learn Security implementation

For Architects

  1. Review ADRs for design decisions
  2. Understand performance considerations
  3. Study the Database Schema and Multi-Host Concurrency Design

For DevOps

  1. Review the CI/CD Pipeline and Deployment Pipeline Setup
  2. Understand monitoring requirements
  3. Review security considerations