Newton Aigbokhan System Design
Live Beta · Multi-Surface .NET 10 + Self-Hosted AI Platform

Adaraflow — Modular .NET 10 & Self-Hosted AI Language Platform

Multi-tenant AI-powered German language learning platform built for professionals and immigrants who need real conversation practice, pronunciation coaching, and structured CEFR progression rather than static flashcards. Engineered as a 23-module .NET 10 modular monolith serving 3 React 19/TypeScript web applications, a Flutter mobile client, provider-agnostic AI orchestration, and a real-time LiveKit WebRTC voice tutor that runs 100% locally on CPU when desired.

23 Bounded-Context Modules (.NET 10 Vertical Slices + .Contracts)
498 Automated Test Files (15 NetArchTest suites + Testcontainers)
< 50 ms Zero-Token German Deterministic Fast-Path before LLM fallback
100% Local Single env-var toggle for fully self-hosted Voice STT/TTS

System Architecture

End-to-End Platform & Data Flow Topology

Every client surface talks to a single modular .NET 10 composition root enforced by strict contract assemblies, out-of-band migrations, and isolated multi-tenant persistence.

Layer 01 // Clients

Multi-Surface Web & Mobile Clients

React 19 · Vite 7 · TypeScript · Flutter
clients/web (Learner SPA)

af-learn.newtonly.net — React 19, TanStack Query v5, SSE live updates, interactive lesson & voice UI.

clients/dashboard (Tenant Portal)

af-app.newtonly.net — Tenant administration, analytics, SSE feeds, and organization workspace.

clients/admin (Operator CMS)

af-admin.newtonly.net — RBAC-guarded CMS, AI prompt template management, and tenant billing.

clients/mobile (Flutter)

iOS & Android white-label tenant flavors with Riverpod, Dio, go_router, FCM push, and voice tutor.

Layer 02 // Core API

.NET 10 Modular Monolith (Adaraflow.Api & Aspire)

ASP.NET Core 10 · Mediator 3.x · Finbuckle 10.x
Vertical Slice Modules (23)

Each bounded context exposes only its .Contracts assembly; cross-module calls use contracts or Outbox/Inbox events.

Source-Gen Mediator + FluentValidation

public sealed CQRS handlers returning ValueTask<T>, paired 1:1 with validators enforced by architecture tests.

Finbuckle Default-ON Tenant Isolation

BaseDbContext enforces per-tenant query filters on every entity unless explicitly marked IGlobalEntity.

Adaraflow.DbMigrator + Hangfire

Migrations run strictly out-of-band via DbMigrator (never at API startup); background workers run on Hangfire.

Layer 03 // Persistence & Edge

State, Caching, Object Storage & Reverse Proxy

PostgreSQL · Redis/Valkey · RustFS · Coolify/Traefik
PostgreSQL (EF Core 10)

Npgsql persistence with migrations organized cleanly by module folder inside Adaraflow.Migrations.PostgreSQL.

Redis / Valkey

HybridCache + atomic concurrency lock keys (ai:tutor:active_voice:{tenantId}:{userId}) for voice sessions.

RustFS (S3-Compatible Storage)

Presigned audio/media uploads and static course assets served via internal Docker network + CORS rules.

Coolify / Traefik & Terraform

Containerized internal routing via expose, TrustedProxyOptions forwarding, plus AWS ECS/RDS/ElastiCache Terraform.

Layer 04 // AI & Voice Plane

Provider-Agnostic AI & LiveKit WebRTC Voice Sidecar

Microsoft.Extensions.AI · Python LiveKit · Silero VAD · Faster-Whisper · Kokoro/Piper
Modules.AI Orchestrator

Microsoft.Extensions.AI + IAIProvider, versioned prompt templates, ProviderCircuitBreaker, and quota metering.

Hybrid Evaluator & State Machine

Deterministic German normalizer (<50ms) + structured JSON LLM fallback + 15-state TutorProgressionPolicy.

services/voice-agent (Python)

Stateless LiveKit WebRTC worker running Silero VAD, Groq or local Faster-Whisper STT, and local Kokoro/Piper TTS.

Live .NET Aspire Runtime Resource Graph
Live Run · Multi-Container Local Topology
Snapshot from Adaraflow.AppHost wiring API, one-shot DB migrator/seeder, containers, and frontends in one local run.

Orchestrated Dependency Topology

One dotnet run command launches the full distributed environment with health-checked dependency ordering before the API and web apps begin accepting traffic.

Core Host & Migrations adaraflow-api waits on one-shot adaraflow-db-migrator and adaraflow-demo-seeder.
Data, Cache & Object Storage postgres (fsh-db + pgadmin), redis (+ redis-insight), and rustfs (+ rustfs-init).
AI, Voice & Dev Services livekit WebRTC SFU, transapi translation service, and mailpit SMTP sink.
3 React 19 SPAs adaraflow-web, adaraflow-dashboard, and adaraflow-admin with dependency installers.

Learning & Pedagogical Core

10 Modules

Curriculum delivery, spaced repetition, lexeme knowledge graphs, interactive exercise evaluation, and CMS authoring.

Learning Vocabulary Grammar Exercise Conversation Pronunciation Writing Progress Analytics ContentManagement

AI & Realtime Voice

1 Module + Sidecar

Unified AI provider abstraction inside Modules.AI paired with an independent LiveKit WebRTC media worker for low-latency audio.

AI (Microsoft.Extensions.AI) TutorProgressionPolicy GermanTextNormalizer ProviderCircuitBreaker services/voice-agent

Enterprise SaaS Foundation

12 Modules

Multi-tenant identity, subscription billing, push notifications, webhooks, presigned file storage, and compliance auditing.

Identity Multitenancy Billing TenantBilling Catalog Chat Files Notifications Tickets Webhooks Auditing Platform

Pedagogical AI Pipeline

Hybrid Deterministic + LLM Tutor Engine

Rather than sending every learner keystroke straight to an expensive LLM, Adaraflow routes answers through German text normalization, a <50ms zero-token fast-path, a circuit-broken semantic evaluator, and a 15-state backend state machine.

4-Stage Answer Evaluation & Progression Pipeline
Zero-Token Fast-Path · Anti-Leak State Machine
Stage 01 // Normalize

German Text Normalizer

Compiled [GeneratedRegex] cleans punctuation/whitespace and transliterates umlauts & sharp-s (ä→ae, ö→oe, ü→ue, ß→ss) alongside Levenshtein distance scoring.

GeneratedRegex Umlaut Folding Levenshtein
Stage 02 // Fast-Path

Zero-Token Deterministic Match

DeterministicExerciseEvaluator checks exact matches, accepted alternatives, and transliteration equivalents in under 50ms—eliminating unnecessary LLM latency and token cost.

< 50ms Latency Zero LLM Cost Exact & Alt
Stage 03 // Fallback

Semantic LLM + Pronunciation

Ambiguous inputs fall back to provider-agnostic Microsoft.Extensions.AI JSON evaluation (TutorEvaluationContractV1) guarded by ProviderCircuitBreaker (60s cooldown), plus fault-isolated acoustic scoring.

Circuit Breaker Structured JSON Audio Scoring
Stage 04 // Policy

15-State Anti-Leak Engine

TutorProgressionPolicy governs 15 teaching states: hints never leak the expected answer before MaxAttempts, and once revealed, learners must repeat with ≥0.85 similarity to advance.

15 States Anti-Leak Rule ≥ 0.85 Gate
TutorAnswerEvaluator.cs Hybrid deterministic fast-path, LLM semantic fallback & fault-isolated audio scoring
src/Modules/AI/Modules.AI/Services/Evaluator/TutorAnswerEvaluator.cs C# · .NET 10
public async ValueTask<TutorEvaluationContractV1> EvaluateAsync(
    TutorExercise exercise,
    string learnerAnswer,
    string targetLanguage,
    string cefrLevel,
    string nativeLanguage,
    Stream? audioStream = null,
    CancellationToken cancellationToken = default)
{
    ArgumentNullException.ThrowIfNull(exercise);
    var normalizer = _normalizerRegistry.GetNormalizer(targetLanguage);

    // 1. Check Deterministic Fast Path (<50ms, zero LLM tokens)
    var deterministicResult = DeterministicExerciseEvaluator.Evaluate(
        learnerAnswer, exercise.ExpectedAnswer, exercise.AcceptedAlternativesJson,
        normalizer, targetLanguage);

    TutorEvaluationContractV1 evaluation;
    if (deterministicResult.IsHandled && deterministicResult.Evaluation is not null)
    {
        evaluation = deterministicResult.Evaluation;
    }
    else
    {
        // 2. Fall back to provider-agnostic LLM semantic evaluation
        evaluation = await llmEvaluator.EvaluateAsync(
            exercise, learnerAnswer, targetLanguage, cefrLevel, nativeLanguage, cancellationToken)
            .ConfigureAwait(false);
    }

    // 3. Optional acoustic pronunciation check (never blocks text evaluation)
    if (audioStream is not null && pronunciationService is not null)
    {
        try
        {
            var assessment = await pronunciationService.AssessAsync(
                audioStream, exercise.ExpectedAnswer, targetLanguage, cancellationToken).ConfigureAwait(false);
            if (assessment.PronScore < 70.0) { /* append PhoneticClarity feedback */ }
        }
        catch (Exception ex)
        {
            logger.LogWarning(ex, "Pronunciation assessment failed; continuing with text evaluation.");
        }
    }
    return evaluation;
}
TutorProgressionPolicy.cs Pure domain policy enforcing anti-leak attempts & ≥ 0.85 repetition mastery gate
src/Modules/AI/Modules.AI/Domain/Tutor/TutorProgressionPolicy.cs C# · Domain State Machine
// 1. If awaiting repetition of a revealed answer, require >= 0.85 Levenshtein similarity
if (exercise.CurrentState == TutorTeachingState.AwaitingRepetition ||
    exercise.CurrentState == TutorTeachingState.RevealingAnswer)
{
    bool repetitionPassed = (similarityWithExpected ?? 0.0) >= 0.85 ||
        string.Equals(learnerAnswer?.Trim(), expectedAnswer.Trim(), StringComparison.OrdinalIgnoreCase);

    return repetitionPassed
        ? new ProgressionDecision(TutorTeachingState.ExerciseCompleted, CanAdvance: true,
            RetryRequired: false, RevealAnswer: false,
            GuidanceMessage: "Sehr gut! You repeated the correct answer. Moving to the next exercise.")
        : new ProgressionDecision(TutorTeachingState.AwaitingRepetition, CanAdvance: false,
            RetryRequired: true, RevealAnswer: true,
            GuidanceMessage: $"Please repeat the correct answer: \"{expectedAnswer}\"");
}

// 4. Anti-leak guard: guide without revealing the answer until MaxAttempts is exhausted
int newAttemptCount = exercise.Attempts + 1;
if (newAttemptCount < exercise.MaxAttempts)
{
    TutorTeachingState nextState = outcome switch
    {
        TutorEvaluationOutcome.PartiallyCorrect => TutorTeachingState.PartiallyCorrect,
        TutorEvaluationOutcome.GrammarError or TutorEvaluationOutcome.VocabularyError => TutorTeachingState.ExplainingMistake,
        _ => TutorTeachingState.AwaitingRetry
    };
    return new ProgressionDecision(nextState, CanAdvance: false, RetryRequired: true, RevealAnswer: false,
        GuidanceMessage: $"Not quite. Let's try again! (Attempt {newAttemptCount} of {exercise.MaxAttempts})");
}

return new ProgressionDecision(TutorTeachingState.RevealingAnswer, CanAdvance: false, RetryRequired: true,
    RevealAnswer: true, GuidanceMessage: $"The correct answer is: \"{expectedAnswer}\". Now, please repeat it after me.");
ProviderCircuitBreaker.cs Lock-free fail-fast cooldown gate across outbound AI providers using TimeProvider
src/Modules/AI/Modules.AI/Services/ProviderCircuitBreaker.cs C# · Resilience
public sealed class ProviderCircuitBreaker(TimeProvider? timeProvider = null)
{
    public static readonly TimeSpan DefaultCooldown = TimeSpan.FromSeconds(60);

    private readonly TimeProvider _time = timeProvider ?? TimeProvider.System;
    private readonly ConcurrentDictionary<string, DateTimeOffset> _openUntil = new(StringComparer.OrdinalIgnoreCase);

    public bool IsOpen(string key)
    {
        if (!_openUntil.TryGetValue(key, out var until)) return false;
        if (_time.GetUtcNow() < until) return true;
        _openUntil.TryRemove(key, out _);
        return false;
    }

    public void RecordFailure(string key, TimeSpan? cooldown = null) =>
        _openUntil[key] = _time.GetUtcNow().Add(cooldown ?? DefaultCooldown);

    public void RecordSuccess(string key) => _openUntil.TryRemove(key, out _);

    public static bool IsHardFailureStatus(int statusCode) =>
        statusCode is 401 or 403 or 407 or 408 or 429 || statusCode >= 500;
}

Self-Hosted Voice Infrastructure

Real-Time WebRTC Voice & 100% Local On-Premise Mode

Designed so the exact same Docker Compose stack can optimize for low-CPU cloud acceleration or run completely self-hosted on private servers with zero external API keys or audio egress.

Cloud-Accelerated Mode (Low CPU)

Optional Speedup

Activated automatically when GROQ_API_KEY is configured in Coolify—ideal for lean VPS nodes where saving RAM and CPU cycles matters.

  • Routes Speech-to-Text to Groq whisper-large-v3-turbo (~150ms transcription turnaround).
  • Bypasses loading local Faster-Whisper weights, saving ~1.2 GB of RAM on the host container.
  • Text-to-Speech continues running locally on CPU via Kokoro & Piper; backend LLM uses llama-3.3-70b-versatile.

100% Local Private Server Mode

Zero Data Egress

Clearing GROQ_API_KEY with VOICE_STACK_MODE=local flips the LiveKit worker onto pure local CPU inference on self-managed infrastructure.

  • Runs Silero VAD + Faster-Whisper (Systran/faster-whisper-small int8) + Kokoro / Piper TTS locally.
  • Spoken learner audio stays inside your own LiveKit WebRTC & Docker network—zero third-party API calls.
  • Pairs naturally with private on-premise LLM endpoints via the provider-agnostic IAIProvider interface.

Stateless Worker & Security Trust Boundary

The Python voice-agent holds zero business state. It captures WebRTC audio, detects speech boundaries via Silero VAD, and forwards each transcribed turn back to Adaraflow.Api over an authenticated callback boundary. Meanwhile, .NET owns tenant isolation, progression state, single-session concurrency locks in Redis (ai:tutor:active_voice:{tenantId}:{userId}), and 10-second heartbeat allowance metering.

HMAC Header: X-Voice-Agent-Signature Tenant Context: tenant + X-Voice-Session-Id Replay Protection: UUID Idempotency-Key Redis Lock + 10s Heartbeat Metering
adaraflow_client.py Stateless LiveKit worker callback signing with HMAC, tenant scope & UUID idempotency keys
services/voice-agent/adaraflow_voice_agent/adaraflow_client.py Python · LiveKit Voice Sidecar
class AdaraflowClient:
    """
    HTTP client communicating with Adaraflow.Api voice-agent endpoints.
    Signs every request with the HMAC callback token and includes tenant and voiceSession headers.
    """

    def _get_headers(self) -> Dict[str, str]:
        return {
            "tenant": self.tenant_id,
            "X-Voice-Session-Id": self.voice_session_id,
            "X-Voice-Agent-Signature": self.callback_token,
            "Idempotency-Key": str(uuid.uuid4()),
            "Content-Type": "application/json",
            "Accept": "application/json",
        }

    async def evaluate_turn(
        self, transcript: str, duration_ms: int = 0, client_turn_id: Optional[str] = None
    ) -> Dict[str, Any]:
        url = f"{self.base_url}/api/v1/ai/tutor/voice-agent/sessions/{self.session_id}/turns"
        payload = {
            "transcript": transcript,
            "durationMs": duration_ms,
            "clientTurnId": client_turn_id or str(uuid.uuid4()),
        }
        async with httpx.AsyncClient(timeout=45.0, follow_redirects=True, verify=self._verify_ssl) as client:
            resp = await client.post(url, json=payload, headers=self._get_headers())
            resp.raise_for_status()
            return resp.json()

Engineering Quality & AI Tooling

AI-Assisted Delivery with Automated CI Guardrails

AI coding agents accelerate slice scaffolding and refactoring—but engineering ownership stays human through strict spec workflows, compiler enforcement, Testcontainers integration suites, and 15 executable architecture tests.

Structured .agents/ Harness

Developer Productivity

Tool-agnostic conventions stored inside the repository so Claude Code, Antigravity, Codex, and Copilot follow identical architecture rules.

  • Canonical AGENTS.md bridged to CLAUDE.md & GEMINI.md, backed by 18+ rule files covering backend, React, and Flutter.
  • 19 repeatable skills (add-feature, add-module, create-migration, add-react-page, add-flutter-screen).
  • Spec-Driven Development (/spec:create → /spec:execute → /spec:review) keeping requirements and docs synced in docs/ and features/.

Executable Architecture Guardrails

Zero-Trust Verification

Every PR—human or AI-assisted—must pass automated static, architectural, and real-container integration checks across 498 test files.

  • 15 NetArchTest suites: TenantIsolationTests, ModuleArchitectureTests, CircularReferenceTests, ContractsPurityTests, HandlerValidatorPairingTests, and more.
  • TreatWarningsAsErrors builds + protected shared src/BuildingBlocks + path-scoped Backend/Frontend CI checks.
  • Real PostgreSQL Testcontainers integration suites verifying EF migrations, Finbuckle tenancy, and API endpoints end-to-end.
TenantIsolationTests.cs Architecture test preventing accidental cross-tenant data leaks across all 23 modules
src/Tests/Architecture.Tests/TenantIsolationTests.cs C# · xUnit + EF Core Reflection
[Fact]
public void BaseDbContext_Entities_Should_Be_TenantIsolated_Or_Marked_Global()
{
    var violations = new List<string>();

    foreach (var ctxType in DiscoverBaseDbContextTypes())
    {
        using var ctx = ConstructDbContext(ctxType);
        var model = ctx.Model;

        foreach (var entityType in model.GetEntityTypes())
        {
            if (entityType.IsOwned()) continue;
            if (entityType.ClrType is null) continue;
            if (entityType.FindPrimaryKey() is null) continue;
            if (typeof(IGlobalEntity).IsAssignableFrom(entityType.ClrType)) continue;

            if (entityType.FindAnnotation(FinbuckleAnnotation) is null)
            {
                violations.Add($"{ctxType.Name} → {entityType.ClrType.FullName} is missing IsMultiTenant() and not marked IGlobalEntity");
            }
        }
    }

    violations.ShouldBeEmpty(
        "Every entity in a BaseDbContext-derived DbContext must be tenant-isolated. " +
        "Apply via builder.IsMultiTenant() in EF config, OR opt out by implementing IGlobalEntity.");
}

Live Beta Environment

Explore the Live Adaraflow Deployments

Three production-wired React 19 + TypeScript interfaces backed by the live .NET 10 API, Coolify reverse proxy, and self-hosted LiveKit voice stack.

Live Beta clients/web

Learner Web Application

https://af-learn.newtonly.net/

Interactive German CEFR A1 lesson player, phonics flashcard studio, spaced repetition practice, and AI tutor interface.

Live Beta clients/dashboard

Tenant Operations Dashboard

https://af-app.newtonly.net/

Multi-tenant organization workspace featuring real-time SSE streams, learner cohorts, and runtime config injection.

Live Beta clients/admin

Operator Admin Console

https://af-admin.newtonly.net/

Curriculum CMS, versioned AI prompt template management, RBAC role guards, quota controls, and tenant billing.

Private Repository · Live Technical Walkthrough Available

Adaraflow's source repository is currently private during active beta testing. If you are reviewing this as part of an engineering interview, I am happy to walk through the live codebase, .NET Aspire stack, EF Core migrations, and NetArchTest suites in a 15-minute call.