Skip to content

System Overview & Platform Architecture ​


1. What Is Debelu ​

Debelu (originating from the Igbo verb meaning "to keep", "to preserve", or "to safeguard") is a specialized student campus marketplace and closed-loop escrow financial platform engineered for African universities.

1.1 The Core Market Problem ​

Intra-campus commerce in Nigerian tertiary institutions (e.g. UNILAG, University of Ibadan, UNN, OAU, Covenant) suffers from severe structural friction:

  • The Trust Deficit: Fear of non-delivery causes buyers to withhold payments; fear of non-payment causes merchants to withhold goods.
  • Campus Address Ambiguity: Residential halls, departmental blocks, and student dormitories have no formal street addresses or postal codes. Traditional courier services (DHL, FedEx) cannot deliver to hostel room doors.
  • Payment Fraud & Disintermediation: Off-platform transactions executed via direct bank transfer frequently result in unrecoverable exit scams and counterfeit merchandise.

1.2 The Debelu Solution ​

  • PIN-Protected Closed-Loop Escrow: Funds are collected at checkout and held securely. Money is released to the seller only when the buyer provides an authentic 4-digit Delivery PIN upon physical inspection.
  • Hyperlocal Campus Hubs & Student Couriers: Localized order routing, geofenced campus zones, and student ambassador networks.
  • Automated Trust & Safety Guards: Real-time lexical scanners (ChatGuard) preventing off-platform deal diversion, anomaly detection (PriceGuard) stopping price-gouging, and AI vision (MediaModeration) scanning uploads for prohibited items.
  • Nduzi AI Assistant: Gemini-powered conversational agent assisting students with product discovery, order tracking, and campus recommendations.

2. Monorepo Structure & Surface Topology ​

Debelu is organized as an enterprise monorepo using npm workspaces and Turborepo for optimized build caching and dependency linking:

new-debelu-marketplace/
├── apps/
│   └── storefront/          # Buyer & Vendor Web Application (React 18 SPA + Vite + Capacitor)
├── debelu-marketing/        # Public Marketing, Landing Pages & SEO Site (Next.js 15 App Router)
├── debelu-backend/          # Core Domain REST API, Workers & Queues (Node.js + Express + BullMQ)
├── debelu-admin/            # Operations & Governance Portal (React + Vite)
├── packages/
│   ├── core/                # Canonical TypeScript types, Zod schemas & business validation
│   └── ui/                  # Design system, Tailwind tokens, Radix UI component library
├── supabase/                # PostgreSQL DDL, 97+ migrations, RLS policies & Edge Functions
├── scripts/                 # 60+ automated DB verification, concurrency & recovery scripts
└── tests/                   # Pact contract testing, Playwright E2E suites & k6 load tests

Hosting & Infrastructure Matrix ​

SurfaceTechnical StackProduction Hosting ProviderEdge & Networking
Storefront AppReact 18, Vite, TanStack Query, Zustand, TailwindCloudflare PagesCloudflare Edge CDN & Anycast DNS
Mobile AppCapacitor 6, Android APK, iOS IPA, PWAGoogle Play / Apple App StoreDirect to Cloudflare Pages & Backend API
Marketing SiteNext.js 15, React 19 RC, TypeScript, ISRVercelVercel Edge Network
Backend APINode.js 20, Express, TypeScript, BullMQFly.io (London LHR + Frankfurt FRA)Fly Anycast IP Network
Database & AuthPostgreSQL 16, Supabase Auth, Row-Level SecuritySupabase Managed Cloud (AWS eu-central)Direct TLS 1.3 Pooled Connections
Edge FunctionsDeno TypeScript RuntimeSupabase Edge InfrastructureGlobal Deno Deploy Edge
Object StorageCloudflare R2 / Supabase StorageCloudflare R2Signed HTTPS URLs (15-min TTL)

3. C4 Architecture Diagrams ​

3.1 C4 Level 1: System Context Diagram ​

mermaid
graph TD
    subgraph Users
        BUYER[Student Buyer]
        VENDOR[Campus Merchant]
        COURIER[Campus Runner / Courier]
        STAFF[Debelu Operations Staff]
    end

    subgraph Debelu Marketplace System
        DEBELU[Debelu Platform Ecosystem<br/>Web, Mobile, Marketing, API, Database]
    end

    subgraph External Financial & Cloud Services
        PAYSTACK[Paystack Payment Gateway<br/>Card Ingestion & NUBAN Transfers]
        GEMINI[Google Gemini AI<br/>Multimodal Vision & Nduzi LLM]
        META[WhatsApp Business API<br/>Transactional Messaging]
        SENTRY[Sentry.io<br/>Error Telemetry & Performance Monitoring]
        CF_R2[Cloudflare R2<br/>Encrypted Offsite Storage Vault]
    end

    BUYER -->|Browse, Checkout, Escrow PIN| DEBELU
    VENDOR -->|List Products, Manage Orders, Withdraw Funds| DEBELU
    COURIER -->|Campus Pickup, Hostel Delivery| DEBELU
    STAFF -->|Audit Disputes, Reconcile Payouts, Moderate Content| DEBELU

    DEBELU -->|Process Payments & Interbank Transfers| PAYSTACK
    DEBELU -->|Vision Moderation & Conversational AI| GEMINI
    DEBELU -->|Send Order Status WhatsApp Updates| META
    DEBELU -->|Stream Sanitized Error Reports| SENTRY
    DEBELU -->|Offsite Encrypted Backups & Media| CF_R2

3.2 C4 Level 2: Container Diagram ​

mermaid
graph TD
    subgraph Client Applications
        STORE[Storefront SPA<br/>React 18 / Vite / Cloudflare Pages]
        CAP[Native Mobile Shell<br/>Capacitor / Android & iOS]
        MKT[Marketing & Public Site<br/>Next.js 15 / Vercel]
        ADM[Operations Portal<br/>React / Cloudflare Pages]
    end

    subgraph Backend Services on Fly.io
        API[Express REST API<br/>38 Route Namespaces / 64 Services]
        WORKER[BullMQ Background Queue Worker<br/>Payout Batching, Media Scanning, Emails]
        REDIS[(Redis In-Memory Cache<br/>Rate Limiting, Nduzi Cache, Queue State)]
    end

    subgraph Supabase Data Plane
        POSTGRES[(PostgreSQL 16 Database<br/>RLS Policies, Triggers & Security Definer RPCs)]
        AUTH[Supabase Auth Service<br/>JWT Issuance, Sessions & AAL2 MFA]
        EDGE[Supabase Edge Functions<br/>Paystack Webhook & Outbox Handlers]
    end

    STORE -->|HTTPS / WSS| API
    CAP -->|HTTPS / WSS| API
    MKT -->|HTTPS| API
    ADM -->|HTTPS| API

    STORE -->|Auth Handshake| AUTH
    ADM -->|Auth Handshake AAL2| AUTH

    API -->|Read / Write SQL| POSTGRES
    API -->|Enqueue Jobs & Check Cache| REDIS
    WORKER -->|Consume Jobs| REDIS
    WORKER -->|Execute Batch Ledger Posts| POSTGRES

    EDGE -->|Verify HMAC & Lock Escrow| POSTGRES

4. End-to-End Request & Authentication Lifecycle ​

When an authenticated client executes a request against Debelu's API, the request traverses a strict multi-stage security pipeline:

mermaid
sequenceDiagram
    autonumber
    actor Client as Storefront Browser / Mobile
    participant WAF as Cloudflare Edge WAF
    participant MW as Express Auth & Security Middleware
    participant Controller as Domain Controller
    participant Service as Business Domain Service
    participant DB as Postgres (RLS & RPCs)

    Client->>WAF: 1. HTTPS GET /api/orders (Authorization: Bearer <JWT>)
    Note over WAF: Checks IP rate limits, DDoS rules & TLS 1.3
    WAF->>MW: 2. Proxy request to Fly.io Node.js API
    Note over MW: corsMiddleware -> helmet -> requestIdMiddleware
    MW->>MW: 3. authMiddleware: Validate Supabase JWT
    Note over MW: Verifies signature with SUPABASE_JWT_SECRET
    Note over MW: Extracts sub (User ID), role, and aal (AAL1 vs AAL2)
    MW->>Controller: 4. Pass validated req.user context
    Controller->>Service: 5. Invoke OrderService.list(userId, filters)
    Service->>DB: 6. Execute SELECT with RLS (user_id = auth.uid())
    DB-->>Service: 7. Return isolated tenant records
    Service->>Controller: 8. Return domain entity models
    Controller-->>Client: 9. HTTP 200 OK (Strict RFC JSON envelope)

5. Data Flow & Cross-Cutting Architecture ​

5.1 Canonical Type Sharing (@debelu/core) ​

To eliminate contract drift between frontend applications and backend API routes, all domain entity types, validation rules, and error schemas are authored in packages/core:

  • Shared schemas: Product, Order, CampusOrder, PriceAnomaly, MediaScanResult, ChatScanResult.
  • Zero runtime dependency on frontend frameworks; compiles to clean ESM and CJS bundles consumed by Storefront, Marketing, Backend, and Admin.

5.2 Background Processing & Asynchronous Queues ​

Heavy operations are decoupled from the synchronous HTTP request loop using BullMQ backed by Redis:

  • payout-dispatch-queue: Processes approved vendor payout batches sequentially to avoid hitting bank-switch rate limits.
  • media-moderation-queue: Asynchronously triggers Google Gemini computer vision scans on newly uploaded product listings.
  • notification-outbox-queue: Delivers push notifications, WhatsApp transactional messages, and transactional receipt emails.

6. Third-Party Integrations & Resilience Matrix ​

Third-Party ProviderPlatform FunctionCriticalityFallback / Circuit Breaker Behavior
PaystackCard payment collection, USSD, bank account resolution, NUBAN payout transfersCRITICALAutomated circuit breaker trips after 5 consecutive timeouts; storefront switches campus orders to "Pay on Pickup / Campus Reserve" mode.
SupabasePrimary PostgreSQL storage, Auth engine, Row-Level Security, Edge FunctionsCRITICALHigh-availability multi-AZ configuration; point-in-time recovery (PITR); offsite R2 logical backups.
Google Gemini AINduzi conversational assistant, computer vision image moderationHIGHHeuristic fallback: image moderation switches to deterministic URL/keyword filter; chat assistant gracefully disables tools.
CloudflareDNS routing, Edge CDN caching, WAF DDoS protection, R2 object storageHIGHPages deployment maintains instant rollback to previous commit; R2 objects replicated across regional zones.
Meta WhatsApp APITransactional delivery updates and customer notificationsMODERATEInbound messages queued in support_notification_outbox; delivery retries via in-app inbox and email.
SentryDistributed error tracking across frontend and backend surfacesLOWPII and cardholder regex scrubbers sanitize all events before egress; API functions unimpeded if Sentry is unreachable.
UnleashFeature flag evaluation and dynamic kill-switchesMODERATEClient libraries maintain in-memory cached state; defaults to safe hardcoded fallback flags if proxy is offline.

Released under Proprietary Enterprise License.