# System Architecture Design
*For: Web-Based Advisory Framework for Edge Computing Implementation in the Transportation Sector*
**Author:** Precious Olusola
**Version:** 1.0
**Date:** August 18, 2025
---
## 1. Architectural Goals
* Meet NFRs: <3s responses, 10k concurrent users, GDPR-compliant, maintainable modular codebase.
* Keep the web app standalone while allowing future integrations (simulation engines, external datasets).
* Favor conventional, proven patterns: layered architecture, stateless services, clear separation of concerns, strong typing (TypeScript), and CI/CD discipline.
---
## 2. High‑Level View (Logical Architecture)
**Layers & Core Components**
1. **Presentation (Next.js 15 + App Router)**
* Pages: Dashboard, Input Wizard, Recommendations, Case Studies, Roadmaps, Admin.
* Client components for rich UX; Server Components for data-fetching.
* Accessibility first (WCAG), Tailwind CSS.
2. **API Layer (Next.js Route Handlers / Edge & Node Runtimes)**
* `/api/recommendations` – orchestrates recommendation pipeline.
* `/api/case-studies`, `/api/challenges`, `/api/roadmaps` – content APIs.
* `/api/admin/*` – content management endpoints with RBAC.
3. **Domain Services**
* **Recommendation Engine Service** (TypeScript): rules + scoring + templates; calls Knowledge Base and optional Simulation Service.
* **Knowledge Base Service** (TypeScript): typed query layer over Postgres; supports faceted search & context tagging (urban/rural, fleet type, etc.).
* **Report Generator**: composes PDF/MDX/HTML deliverables from templates.
* **Simulation Adapter** (optional): abstraction for future engines; invoked asynchronously via jobs.
4. **Data & State**
* **Supabase (Postgres)** for users, inputs, case studies, challenges, roadmaps, reports.
* **Supabase Auth** (Email/OAuth) + RLS policies.
* **Redis (optional)** for caching hot KB queries and recommendation outputs.
* **Object Storage** (Supabase Storage) for generated reports and media.
5. **Asynchronous Processing**
* **Job Queue** (BullMQ on Redis) for long-running simulations/report rendering.
6. **Observability & Security**
* OpenTelemetry traces + logs; metrics dashboards.
* HTTPS everywhere, JWT sessions, RBAC, audit logs, DPO workflows.
> See Diagram: `01_high_level_architecture.png` (linked below in chat).
---
## 3. Deployment View
* **Frontend**: Next.js deployed to Vercel (Edge where suitable; Node runtime for heavy endpoints).
* **API/Services**: Next.js Route Handlers; heavier jobs can run as background workers on Fly.io/Render/Node VM.
* **Database & Auth**: Supabase project (Postgres + RLS + Storage + Auth).
* **Cache/Queue**: Managed Redis (Upstash/Valkey-on-managed host).
* **CDN**: Vercel CDN for static assets.
* **Secrets**: Vercel/Supabase encrypted secrets management.
> See Diagram: `02_deployment_view.png`.
---
## 4. Data Model (ERD – Simplified)
**Key Entities**
* `users` (id, email, role, profile)
* `sessions` (supabase-managed)
* `inputs` (id, user\_id, fleet\_size, fleet\_type, data\_needs, constraints, created\_at)
* `recommendations` (id, input\_id, score, summary, detail, created\_at)
* `reports` (id, input\_id, url, format, checksum)
* `case_studies` (id, title, context\_tags\[], summary, body, source\_url)
* `challenges` (id, type, title, severity, mitigation)
* `roadmaps` (id, tier, steps jsonb)
* `admin_actions` (id, actor\_id, entity, action, before, after, at)
RLS enforces per-user access; admins have broader scopes.
> See Diagram: `03_database_erd.png`.
---
## 5. Key Flows
### 5.1 Recommendation Generation (Happy Path)
1. User submits domain input (fleet size/type, goals, constraints).
2. API validates & normalizes; stores `inputs` row.
3. Recommendation Engine:
* Loads rules & weights; queries Knowledge Base (case studies, challenges).
* Scores candidate recommendations; selects top-N.
* Writes `recommendations`; kicks async report job (PDF) if requested.
4. API returns consolidated response in <3s (uses caching for KB lookups).
> See Sequence Diagram: `04_sequence_recommendation.png`.
### 5.2 Admin Content Update
* Admin authenticates → RBAC check → content write via service layer → audit log entry in `admin_actions`.
---
## 6. Technology Choices & Rationale
* **Next.js 15 + App Router**: SSR/ISR, RSC performance, edge-capable.
* **Supabase**: Unified Postgres, Auth, RLS, Storage; speeds delivery while keeping SQL durability.
* **TypeScript everywhere**: compile-time safety; easier maintenance.
* **Redis + BullMQ (optional)**: predictable performance for jobs & caching.
Compatibility with SRS:
* Performance (<3s): SSR + caching + precomputation.
* Usability: accessible components, semantic HTML, keyboard support.
* Security/GDPR: HTTPS, encryption at rest (Supabase), data minimization, consent flows.
* Scalability (10k CCU): stateless edge/API, CDN, database connection pooling, read replicas if needed.
* Maintainability: clean architecture modules; CI with tests.
---
## 7. Security Architecture
* **Auth**: Supabase Auth (email/OAuth); short-lived access tokens; refresh rotation.
* **RBAC**: roles `user`, `admin`, optional `researcher`.
* **RLS**: row-level policies on `inputs`, `recommendations`, `reports`.
* **Data Protection**: PII hashing where possible; S3-compatible storage with signed URLs; backups.
* **Auditability**: all admin writes go to `admin_actions`.
* **Compliance**: consent banner, data retention policy, right-to-erasure endpoints; DPA with vendors.
---
## 8. Performance & Scalability Tactics
* Cache KB queries and recommendation templates.
* Precompute popular roadmaps with ISR.
* Use connection pooling (pgBouncer); consider read replicas.
* Rate limiting on write-heavy endpoints.
* Background jobs for PDF generation & simulations.
---
## 9. Testing & Quality Gates
* **Unit**: services, rules, scoring.
* **Integration**: API ↔ DB ↔ services (Playwright/MSW for frontend flows).
* **Contract**: Zod schemas for all API payloads.
* **Load**: k6/Artillery targets 10k CCU; SLOs measured.
* **Accessibility**: axe-core automated checks + manual keyboard testing.
---
## 10. CI/CD Pipeline
* PR checks: typecheck, lint, unit tests, integration tests.
* Preview deploys (Vercel). Main → production after green gates.
* DB migrations with Prisma or SQL migrations (typed).
* Feature flags for staged rollout.
---
## 11. Evolution & Extensibility
* Plug-in interface for Simulation Adapter (future engines).
* Rule packs per region (EU/US/NG) and transport mode.
* Optional ML reranker once data accumulates; keep rule-based as baseline.
---
## 12. Artifacts
The following diagrams are provided as downloadable PNGs in chat:
* `01_high_level_architecture.png`
* `02_deployment_view.png`
* `03_database_erd.png`
* `04_sequence_recommendation.png`
---
## 13. Appendix – API Surface (Sketch)
* `POST /api/recommendations` { input } → { recommendations, report\_url? }
* `GET /api/case-studies?tags=...`
* `GET /api/challenges?type=technical|human`
* `GET /api/roadmaps/:tier`
* `POST /api/admin/case-studies`
* `PUT /api/admin/challenges/:id`
* `GET /api/reports/:id` (signed URL)
---
*End of Architecture Document*