Skip to content

Backend API Architecture & Engineering Reference (debelu-backend) ​

This document is the authoritative engineering specification for debelu-backend, the production Node.js/Express and TypeScript REST API powering all Debelu consumer, vendor, and administrative surfaces. Grounded directly in [server.ts](file:///c:/Users/frank/OneDrive/Desktop/Chisom/Debelu/New%20Debelu%20Marketplace/debelu-backend/src/server.ts), 38 domain route modules, 64 domain services, 8 perimeter middlewares, and BullMQ queue orchestrators, this specification details the server lifecycle, security perimeters, service contracts, and operational execution patterns.


1. System Overview & Monorepo Topology ​

debelu-backend operates as an enterprise-grade RESTful API service deployed as a containerized workload on Railway at api.debelu.com. It serves as the single source of truth for platform state, orchestrating Postgres transactions via Supabase, managing real-time AI conversations via Gemini 1.5 Flash, executing financial workflows through Paystack, storing media in Cloudflare R2, and coordinating background jobs via Redis and BullMQ.

mermaid
graph TD
    Client[Web Storefront / Mobile PWA / Admin Portal] -->|HTTPS / WSS| Perimeter[Express Perimeter: Helmet + CORS + Rate Limiter]
    
    subgraph debelu_backend [debelu-backend Service Architecture]
        Perimeter --> Tracing[Request Tracing: x-request-id + Morgan]
        Tracing --> Auth[Authentication & RBAC: Supabase JWT + Role Verification]
        Auth --> Validation[Input Validation: Zod Schemas]
        Validation --> Routes[38 Express Route Namespaces]
        
        Routes --> Controllers[HTTP Controllers]
        Controllers --> Services[64 Domain Services]
        
        Services --> DB[(Supabase PostgreSQL)]
        Services --> Cache[(Redis Cache & Session Store)]
        Services --> Queues[BullMQ Webhook & Dispatch Queues]
        Services --> External[External Gateways: Paystack, Gemini, R2, Termii]
    end

    subgraph Workers [Background Daemon Pipeline]
        Maintenance[Housekeeping: jobs/maintenance.ts]
        CampaignWorker[InboxCampaignWorker]
        OutboxWorker[SupportNotificationOutbox]
        PayoutWorker[ReviewedPayoutDispatchWorker]
        WebhookWorker[BullMQ Webhook Worker]
    end

    Queues --> WebhookWorker
    Services -.-> Maintenance
    Services -.-> CampaignWorker
    Services -.-> OutboxWorker
    Services -.-> PayoutWorker

1.1 Technical Stack & Core Invariants ​

  • Runtime: Node.js 20 LTS (Alpine Docker base).
  • Language: TypeScript 5.x executed with strict compiler flags (noImplicitAny, strictNullChecks, exactOptionalPropertyTypes).
  • Web Framework: Express 4.x with explicit connection pooling and timeout handling.
  • Data Layer: Supabase PostgreSQL with Row Level Security (RLS) and Prisma/PostgREST client libraries.
  • Asynchronous Processing: Redis 7.x + BullMQ for guaranteed at-least-once message delivery and exponential backoff retry semantics.
  • Observability: Sentry error tracking, Winston structured JSON logger, and Google SRE multi-window burn rate telemetry.

2. Server Bootstrap & Lifecycle (server.ts) ​

The backend entrypoint [server.ts](file:///c:/Users/frank/OneDrive/Desktop/Chisom/Debelu/New%20Debelu%20Marketplace/debelu-backend/src/server.ts) implements an enterprise startup and graceful shutdown lifecycle designed for zero-downtime rolling deployments in Kubernetes, Railway, and Cloud Run environments.

mermaid
sequenceDiagram
    autonumber
    participant OS as Operating System / Orchestrator
    participant Srv as server.ts Bootstrap
    participant Jobs as Background Daemons
    participant Conn as Postgres & Redis Pools

    OS->>Srv: Process Start (NODE_ENV=production)
    Srv->>Srv: dotenv.config() + initSentry()
    Srv->>Srv: Configure Trust Proxy (trust proxy = 1)
    Srv->>Srv: Register Request Tracing (UUID v4)
    Srv->>Srv: Mount Security Headers (Helmet CSP, HSTS, COEP)
    Srv->>Srv: Register 38 Route Modules
    Srv->>Conn: Initialize Database & Cache Connections
    Srv->>Jobs: Start Maintenance, Outbox & Payout Workers
    Srv-->>OS: HTTP Server Listening on PORT (Ready)

    Note over OS,Srv: Running State (Handles Inbound Traffic)

    OS->>Srv: SIGTERM / SIGINT Signal Received
    Srv->>Jobs: Stop Maintenance Timers & Workers
    Srv->>Srv: Stop Accepting New HTTP Connections (server.close)
    Srv->>Conn: Disconnect Redis & Webhook Queues
    Srv-->>OS: Process Exit (Code 0) [Max 10s Timeout]

2.1 Initialization Sequence ​

  1. Environment & Sentry Init:
    • dotenv.config() loads localized environment overrides.
    • initSentry() initializes distributed exception capturing with trace sampling and release tag pinning (GIT_SHA).
  2. Reverse Proxy & Header Trust:
    • app.set('trust proxy', 1) enables accurate client IP resolution (req.ip) behind Railway, Cloudflare, and AWS ALB reverse proxies.
  3. Trace Correlation:
    • Inbound x-request-id headers are validated against /^[a-zA-Z0-9-_]{8,64}$/ to prevent log injection attacks. Invalid or missing headers trigger automatic generation of a cryptographically secure randomUUID().
    • The verified request ID is echoed in the X-Request-ID HTTP response header and attached to the request context.
  4. Security Perimeter (Helmet & CORS):
    • Helmet enforces strict HTTP headers:
      • Content-Security-Policy: Restricts script and object execution; whitelists Supabase, Paystack, and Gemini endpoints; binds violation telemetry to /api/csp-report.
      • Strict-Transport-Security: Enforces 1-year max-age (31536000), subdomain inclusion, and preload eligibility.
      • Cross-Origin-Opener-Policy: same-origin-allow-popups (enables Paystack popups).
      • Cross-Origin-Resource-Policy: cross-origin (supports Supabase and R2 media).
  5. Raw vs JSON Body Parsers:
    • Webhook routes (/api/payments/webhook and /api/whatsapp/webhook) use express.raw({ type: 'application/json', limit: '1mb' }) to preserve pristine byte streams for HMAC SHA-512 signature verification.
    • Streaming AI routes (/api/gemini/stream and chat media) support up to 8mb payloads to accommodate base64 image uploads.
    • Standard routes enforce a strict 1mb JSON body limit to protect against Denial of Service (DoS) memory exhaustion.
  6. Graceful Shutdown Protocol:
    • Captures SIGTERM and SIGINT signals emitted by container runtimes during rolling deployments.
    • Halts all cron timers (stopMaintenanceJobs(), stopInboxCampaignWorker(), stopSupportOutbox(), stopReviewedPayoutDispatch()).
    • Closes the active HTTP server listener, allowing in-flight requests to terminate cleanly.
    • Disconnects Redis connections, terminates BullMQ webhook workers, and tears down queue connections.
    • Enforces a 10-second hard fallback timeout (setTimeout(() => process.exit(1), 10000)) preventing zombie container deadlocks.

3. Middleware Architecture ​

Debelu enforces an 8-layer middleware stack ensuring perimeter defense, rate control, authentication, caching, and idempotency.

mermaid
flowchart TD
    Req[Inbound HTTP Request] --> M1[Request Tracing: x-request-id]
    M1 --> M2[Security Perimeter: Helmet & CORS]
    M2 --> M3[Global Rate Limiter: 1000 req/15min]
    M3 --> M4[Maintenance Gate: maintenanceGate]
    M4 --> M5[Authentication & RBAC: auth.ts]
    M5 --> M6[Idempotency Key Verification: idempotency.ts]
    M6 --> M7[Route-Specific Rate & Circuit Breakers]
    M7 --> M8[Request Schema Validation: validateRequest.ts]
    M8 --> Handler[Route Controller Handler]
    Handler --> ErrorCatch[Global Error Handler: errorHandler.ts]

3.1 Middleware Inventory & Specifications ​

Middleware FileKey Function / ExportPurpose & Architectural Rules
[auth.ts](file:///c:/Users/frank/OneDrive/Desktop/Chisom/Debelu/New%20Debelu%20Marketplace/debelu-backend/src/middleware/auth.ts)authenticateUser
requireRole
requireAdmin
requireVendor
requireCampusScope
verifyAAL2
maintenanceGate
Extracts Supabase JWT from Authorization: Bearer <token>, validates cryptographic signature, fetches member profile and active staff roles. Implements dynamic role degradation (disables staff permissions if user status is suspended). Enforces campus isolation and Authenticator Assurance Level 2 (AAL2) MFA for privileged operations. Blocks traffic during maintenance except for webhooks and status probes.
[rateLimiters.ts](file:///c:/Users/frank/OneDrive/Desktop/Chisom/Debelu/New%20Debelu%20Marketplace/debelu-backend/src/middleware/rateLimiters.ts)authLimiter
paymentLimiter
searchLimiter
supportLimiter
publicLimiter
Implements fine-grained token bucket rate limits per endpoint category. Uses Draft-7 standard headers (RateLimit-Limit, RateLimit-Remaining, RateLimit-Reset). Skips internal health probes to prevent load balancer blacklisting.
[aiRateLimiter.ts](file:///c:/Users/frank/OneDrive/Desktop/Chisom/Debelu/New%20Debelu%20Marketplace/debelu-backend/src/middleware/aiRateLimiter.ts)aiRateLimiterDedicated throttling for Nduzi / Gemini LLM invocations to prevent upstream quota exhaustion and token denial-of-wallet attacks. Evaluates client IP and authenticated user ID.
[cacheMiddleware.ts](file:///c:/Users/frank/OneDrive/Desktop/Chisom/Debelu/New%20Debelu%20Marketplace/debelu-backend/src/middleware/cacheMiddleware.ts)cacheMiddleware
clearCache
Redis-backed HTTP response caching for read-heavy, publicly cacheable catalog and platform status queries. Implements automatic ETag generation and conditional 304 Not Modified returns.
[idempotency.ts](file:///c:/Users/frank/OneDrive/Desktop/Chisom/Debelu/New%20Debelu%20Marketplace/debelu-backend/src/middleware/idempotency.ts)requireIdempotencyEnforces mandatory Idempotency-Key header on all financial mutations (checkout payment intent creation, escrow releases, wallet refunds, and payout disbursements). Stores request fingerprints in Redis/Postgres to prevent duplicate charges during network retries.
[circuitBreakers.ts](file:///c:/Users/frank/OneDrive/Desktop/Chisom/Debelu/New%20Debelu%20Marketplace/debelu-backend/src/middleware/circuitBreakers.ts)paystackBreaker
geminiBreaker
termiiBreaker
Protects downstream third-party services from cascading failure loops. Automatically trips to OPEN state upon detecting 5 consecutive gateway timeouts or 5xx errors, returning instantaneous 503 responses without saturating worker threads.
[validateRequest.ts](file:///c:/Users/frank/OneDrive/Desktop/Chisom/Debelu/New%20Debelu%20Marketplace/debelu-backend/src/middleware/validateRequest.ts)validateRequestGeneric request body, query parameter, and route parameter validator executing Zod schemas. Emits RFC 7807 formatted 400 Bad Request error structures on validation failures.
[errorHandler.ts](file:///c:/Users/frank/OneDrive/Desktop/Chisom/Debelu/New%20Debelu%20Marketplace/debelu-backend/src/middleware/errorHandler.ts)errorHandlerTerminal Express error handling middleware. Formats all exceptions into RFC 7807 Problem Details. Dispatches unexpected runtime exceptions to Sentry with attached requestId. Masks raw database connection strings and internal Postgres error codes (42501, 23505) from client responses.

4. Route Namespaces (38 Domain Modules) ​

The Debelu backend modularizes its HTTP API across 38 dedicated route files registered under /api/*:

debelu-backend/src/routes/
├── adminRoutes.ts                          # Comprehensive staff & platform management
├── bannerRoutes.ts                         # Marketing banners & campus announcements
├── campusOperationsRouter.ts               # Hyperlocal campus hubs & student rep controls
├── cartRoutes.ts                           # Shopping cart persistence & checkout prep
├── catalogRoutes.ts                        # Public category hierarchies & search facets
├── categoryCommissionRoutes.ts             # Maker-Checker category commission overrides
├── chatRoutes.ts                           # Buyer-vendor messaging & ChatGuard enforcement
├── conversationRoutes.ts                   # Nduzi AI conversational thread persistence
├── couponRoutes.ts                         # Discount coupon creation & validation
├── disputeRoutes.ts                        # Escrow dispute escalation & evidence filing
├── flashSaleRoutes.ts                      # Time-bounded discounted flash sale listings
├── geminiRoutes.ts                         # Nduzi AI assistant streaming & tool invocations
├── inboxCampaignRoutes.ts                  # Broadcast notifications & promotional campaigns
├── logRoutes.ts                            # Client-side error beacon ingestion
├── moderationAppealRoutes.ts               # Vendor suspension appeal intake & triage
├── moderationCaseRoutes.ts                 # Trust & Safety moderation investigations
├── notificationRoutes.ts                   # In-app push notifications & alerts
├── orderRoutes.ts                          # Order placement, escrow lifecycle, PIN delivery
├── paymentIntentInspectionRoutes.ts        # Payment intent reconciliation & audit inspection
├── paymentRoutes.ts                        # Paystack checkout intents, webhooks, bank queries
├── payoutExceptionObservationsRoutes.ts    # Automated payout anomaly & failure tracking
├── payoutTransferReconciliationRoutes.ts   # Maker-Checker dual authorization payout restitution
├── platformConfigurationProposalRoutes.ts  # 4-Eyes platform settings modification proposals
├── privacyErasureExecutionRoutes.ts        # Right to be Forgotten (RTBF) batch execution
├── privacyErasurePlanRoutes.ts             # NDPA data erasure impact assessment plans
├── privacyExportArtifactRoutes.ts          # Subject access request (DSAR) artifact downloads
├── productRoutes.ts                        # Product CRUD, inventory tracking, image uploads
├── queueObservationsRoutes.ts              # BullMQ queue depth and dead-letter monitoring
├── reviewRoutes.ts                         # Verified-buyer product reviews & ratings
├── reviewedPayoutBatchRoutes.ts            # Batched vendor payout dispatches
├── reviewedWalletRefundRoutes.ts           # Maker-Checker escrow wallet refund command execution
├── subjectPrivacyExportRoutes.ts           # NDPA personal data export generation
├── supportRoutes.ts                        # Customer support tickets & dispute communication
├── transactionRoutes.ts                    # Double-entry ledger audit queries
├── userRoutes.ts                           # User profile, addresses, university enrollment
├── vendorRoutes.ts                         # Vendor onboarding, KYC, payouts, catalog settings
├── vibeRoutes.ts                           # Campus vibe feeds & curated product groupings
└── whatsappWebhookRoutes.ts                # Meta WhatsApp Cloud API webhooks & delivery receipts

4.1 Route Namespace Specifications ​

Path PatternHandler ModulePrimary Controller / ServiceAuth ScopeKey Responsibilities
/api/paymentspaymentRoutes.tsPaymentService
CheckoutPaymentIntent
Public / User / WebhookInitializes Paystack checkout intents, handles raw HMAC webhooks, queries vendor banks.
/api/ordersorderRoutes.tsOrderService
CampusOrderService
Authenticated Buyer/VendorCreates orders, records escrow deposits, verifies 6-digit delivery PINs, confirms handoffs.
/api/productsproductRoutes.tsProductService
PriceGuardService
Public / VendorProduct search, filtering, inventory decrements, PriceGuard anomaly detection.
/api/geminigeminiRoutes.tsGeminiService
ChatOrchestrator
Authenticated MemberServer-Sent Events (SSE) AI streaming, tool calling, product recommendation generation.
/api/campuscampusOperationsRouter.tsCampusOperationsServiceCampus Rep / AdminHyperlocal pickup hub verification, student ambassador order triage, logistics logs.
/api/disputesdisputeRoutes.tsDisputeService
AtomicReturnCaseService
Buyer / Vendor / StaffEscrow dispute initiation, return evidence uploads, mediation decision recording.
/api/adminadminRoutes.tsAdminService
ControlCommandService
Staff / Admin (AAL2)Platform governance, financial observation, vendor KYC approval, staff management.
/api/whatsappwhatsappWebhookRoutes.tsWhatsAppServiceMeta SignatureBi-directional customer support messaging and automated order dispatch notifications.
/api/users/me/privacy-exportssubjectPrivacyExportRoutes.tsSubjectPrivacyExportServiceAuthenticated UserInitiates NDPA personal data exports; packages encrypted ZIP bundles for download.

5. Domain Service Layer (64 Specialized Services) ​

The backend business logic is strictly encapsulated within 64 single-responsibility domain services:

mermaid
mindmap
  root((64 Domain Services))
    Core Commerce
      OrderService
      PaymentService
      ProductService
      VendorService
      UserService
      CartService
      CampusOrderService
      CategoryService
      CouponService
      FlashSaleService
      ReviewService
      VibeService
    AI & Chat
      ChatOrchestrator
      GeminiService
      ChatService
      ChatGuardService
      IntentRouter
      ToolSelector
      ToolResultFormatter
      ConversationService
      ConversationMemory
      NduziCache
    Finance & Escrow
      CheckoutPaymentIntent
      CanonicalPayoutTransfer
      PayoutTransferReconciliationService
      ReviewedPayoutBatchService
      ReviewedWalletRefundService
      PriceGuardService
      FinancialObservationService
      PaymentIntentInspectionService
      PayoutExceptionObservationsService
      TransactionService
      WalletAdjustmentCommandService
      CommissionService
    Trust & Moderation
      ModerationCaseService
      ModerationAppealService
      MediaModerationService
      AtomicReturnCaseService
    Support & Comms
      SupportService
      SupportNotificationOutbox
      NotificationService
      WhatsAppService
      InboxCampaignService
      InboxCampaignWorker
    Admin & Governance
      AdminService
      CampusOperationsService
      CategoryGovernanceService
      CategoryCommissionProposalService
      PlatformConfigurationProposalService
      ControlCommandService
      StaffAccessCommandService
      StaffInvitationService
      ImpersonationService
    Privacy & Compliance
      PrivacyCaseService
      PrivacyErasurePlanService
      PrivacyErasureExecutionService
      SubjectPrivacyExportService
      PrivacyExportArtifactService
    Telemetry & Audit
      AuditExportService
      ChunkedAuditExportService
      QueueObservationsService
      HealthCheckService

5.1 Highlighted Service Capabilities ​

A. OrderService.ts & CampusOrderService.ts ​

  • Implements the strict 9-state Order Finite State Machine (pending_payment $\rightarrow$ paid_escrow $\rightarrow$ processing $\rightarrow$ shipped $\rightarrow$ delivered_pending_verification $\rightarrow$ completed).
  • Enforces atomic stock reservations with rollback triggers upon payment expiration.
  • Validates the buyer's 6-digit delivery confirmation PIN (orders.delivery_pin) using constant-time comparison before escrow funds are unlocked.

B. ChatOrchestrator.ts & GeminiService.ts ​

  • Orchestrates Nduzi, the campus AI assistant powered by Gemini 1.5 Flash.
  • Implements a 7-stage conversational pipeline: Intent Classification $\rightarrow$ Semantic Memory Retrieval $\rightarrow$ Context Trimming $\rightarrow$ Function Calling / Tool Execution $\rightarrow$ Content Shielding $\rightarrow$ SSE Stream Generation.
  • Embeds security guards via ChatGuardService to detect off-platform payment attempts, contact leaks, and harassment.

C. PayoutTransferReconciliationService.ts & ReviewedPayoutBatchService.ts ​

  • Enforces the 4-Eyes Principle (Maker-Checker): Payout reversals, batch approvals, and manual wallet adjustments require two distinct authenticated staff actors (reviewedBy !== requestedBy).
  • Validates bank account details against NUBAN check-digit standards via Paystack APIs.
  • Maintains the double-entry general ledger invariant: $$\Delta \text{Assets} = \Delta \text{Liabilities} + \Delta \text{Equity}$$

D. AdminService.ts ​

  • The platform's comprehensive administrative command hub (~120 KB), encapsulating staff user role provisioning, vendor catalog compliance inspections, campus hub administration, and platform-wide emergency controls.

6. Background Jobs, Queues & Daemons ​

Debelu employs a hybrid background processing model, utilizing BullMQ over Redis for external asynchronous events and lightweight in-process daemons for continuous platform housekeeping.

mermaid
graph LR
    subgraph BullMQ_Infrastructure [BullMQ Queue Engine]
        PaystackWebhook[Inbound Paystack Webhook] --> WQ[(webhook-queue)]
        WQ -->|Concurrency: 10<br/>Max: 20/sec| WW[Webhook Worker]
        WW -->|Success| Complete[Completed Jobs]
        WW -->|Max Retries Exceeded: 5| DLQ[(webhook-dead-letter)]
    end

    subgraph InProcess_Daemons [In-Process Maintenance Jobs]
        Timer[Node.js Timers: maintenance.ts] -->|Every 10s| J1[process_audit_export]
        Timer -->|Every 5m| J2[expire_audit_exports]
        Timer -->|Every 5m| J3[expire_privacy_exports]
        Timer -->|Every 5m| J4[cleanup_abandoned_orders]
        Timer -->|Every 60m| J5[auto_complete_orders]
        Timer -->|Every 24h| J6[process_account_deletions]
    end

    subgraph Service_Workers [Domain Event Workers]
        SW1[InboxCampaignWorker: Every 10s]
        SW2[SupportNotificationOutbox: Every 15s]
        SW3[ReviewedPayoutDispatchWorker: Every 30s]
    end

6.1 Webhook Queue & Dead Letter Policy (webhookQueue.ts) ​

  • Queue Name: webhook-queue
  • Concurrency: 10 concurrent jobs with a rate limiter of 20 jobs/second.
  • Retry Policy: 5 attempts with exponential backoff (delay: 2000 ms, increasing exponentially: 2s, 4s, 8s, 16s, 32s).
  • Dead Letter Queue (DLQ): Jobs failing all 5 attempts are automatically transitioned to webhook-dead-letter. DLQ entries are preserved without eviction (removeOnComplete: false, removeOnFail: false) for forensic inspection and manual replay via administrative CLI tools.

6.2 Maintenance Daemon (jobs/maintenance.ts) ​

Implements six scheduled PostgreSQL stored procedure invocations:

Job IdentifierFrequencyDatabase Stored ProcedurePurpose & Parameters
generate-private-audit-exportEvery 10 secondsprocess_audit_exportAssembles encrypted CSV audit log batches requested by compliance officers.
expire-private-audit-exportsEvery 5 minutesexpire_audit_exportsRevokes expired presigned URLs and purges temporary audit staging objects.
expire-private-privacy-exportsEvery 5 minutesexpire_privacy_exportsDeletes unretrieved DSAR personal data export bundles exceeding the 7-day TTL.
expire-unpaid-checkoutsEvery 5 minutescleanup_abandoned_ordersReallocates reserved product inventory for checkouts pending payment $> 30$ mins (p_minutes_old: 30).
auto-complete-ordersEvery 60 minutesauto_complete_ordersAuto-releases escrow for delivered orders without dispute after 3 days (p_delivered_days: 3, p_shipped_days: 14).
account-deletionsEvery 24 hoursprocess_account_deletionsPurges personal data for accounts past the 30-day statutory grace period (p_grace_days: 30).

7. Environment Configuration Reference ​

The following environment variables govern the execution of debelu-backend:

7.1 Required Production Variables ​

Variable NameSensitivePurpose & Target ServiceExample / Format
NODE_ENVNoExecution environment toggleproduction | development | test
PORTNoHTTP listening port for Express3000
SUPABASE_URLNoSupabase project API gatewayhttps://xyzproject.supabase.co
SUPABASE_SERVICE_ROLE_KEYYesBypass-RLS administrative keyeyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
SUPABASE_JWT_SECRETYesShared secret for signing/verifying JWTs64-character hexadecimal string
DATABASE_URLYesPostgreSQL connection stringpostgresql://postgres:[password]@db.xyz.supabase.co:5432/postgres
PAYSTACK_SECRET_KEYYesPaystack Live Secret Gateway API Keysk_live_1234567890abcdef...
GEMINI_API_KEYYesGoogle AI Studio API Key for NduziAIzaSy...
R2_ACCOUNT_IDYesCloudflare R2 Account Identifier32-character hexadecimal string
R2_ACCESS_KEY_IDYesCloudflare R2 S3-Compatible Access Key32-character string
R2_SECRET_ACCESS_KEYYesCloudflare R2 Secret Key64-character string
R2_PUBLIC_BUCKETNoR2 bucket name for public catalog imagesdebelu-media-production

7.2 Optional & Scaling Variables ​

Variable NameDefaultPurpose
REDIS_URLundefinedUpgrades in-memory queues and rate limits to a distributed Redis cluster (redis://default:pwd@host:port).
GEMINI_MODELgemini-2.5-flashConfigures the underlying Gemini model utilized by GeminiService.
WHATSAPP_TOKENundefinedMeta WhatsApp Cloud API access token for transactional messaging.
WHATSAPP_PHONE_NUMBER_IDundefinedMeta registered phone number identifier.
TERMII_API_KEYundefinedTermii SMS gateway API key for campus verification PIN dispatch.
TERMII_BASE_URLhttps://api.ng.termii.comAccount-specific Termii API base URL.
MAINTENANCE_JOBSonSet to off to disable background housekeeping timers on secondary worker nodes.

8. Build, Testing & Deployment Pipelines ​

8.1 Build & Quality Verification ​

bash
# Execute static type checking across the backend package
npm run typecheck --workspace=debelu-backend

# Execute backend unit and integration test suite
npm run test --workspace=debelu-backend

# Compile TypeScript to JavaScript distribution bundle
npm run build --workspace=debelu-backend

8.2 Dockerfile Topology ​

Production deployments utilize a multi-stage Docker build:

  1. Builder Stage:
    • Node 20 Alpine base.
    • Installs build dependencies, executes npm ci, and compiles TypeScript sources via tsc -p tsconfig.build.json.
  2. Runner Stage:
    • Lean Node 20 Alpine runtime.
    • Copies compiled dist/ directory and production-only node_modules.
    • Runs as non-root user node for enhanced container isolation.
    • Exposes port 3000 with container health checks binding to GET /health/live.

9. Document Revision History ​

RevisionDateLead AuthorScope of ChangesStatus
1.0.02026-10-05Principal Backend ArchitectInitial enterprise specification detailing server bootstrap, 8 middlewares, 38 route modules, 64 domain services, BullMQ queues, and maintenance daemons.Active Living Standard

Released under Proprietary Enterprise License.