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.
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 -.-> PayoutWorker1.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.
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
- Environment & Sentry Init:
dotenv.config()loads localized environment overrides.initSentry()initializes distributed exception capturing with trace sampling and release tag pinning (GIT_SHA).
- Reverse Proxy & Header Trust:
app.set('trust proxy', 1)enables accurate client IP resolution (req.ip) behind Railway, Cloudflare, and AWS ALB reverse proxies.
- Trace Correlation:
- Inbound
x-request-idheaders are validated against/^[a-zA-Z0-9-_]{8,64}$/to prevent log injection attacks. Invalid or missing headers trigger automatic generation of a cryptographically securerandomUUID(). - The verified request ID is echoed in the
X-Request-IDHTTP response header and attached to the request context.
- Inbound
- 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).
- Helmet enforces strict HTTP headers:
- Raw vs JSON Body Parsers:
- Webhook routes (
/api/payments/webhookand/api/whatsapp/webhook) useexpress.raw({ type: 'application/json', limit: '1mb' })to preserve pristine byte streams for HMAC SHA-512 signature verification. - Streaming AI routes (
/api/gemini/streamand chat media) support up to8mbpayloads to accommodate base64 image uploads. - Standard routes enforce a strict
1mbJSON body limit to protect against Denial of Service (DoS) memory exhaustion.
- Webhook routes (
- Graceful Shutdown Protocol:
- Captures
SIGTERMandSIGINTsignals 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.
- Captures
3. Middleware Architecture
Debelu enforces an 8-layer middleware stack ensuring perimeter defense, rate control, authentication, caching, and idempotency.
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 File | Key Function / Export | Purpose & Architectural Rules |
|---|---|---|
[auth.ts](file:///c:/Users/frank/OneDrive/Desktop/Chisom/Debelu/New%20Debelu%20Marketplace/debelu-backend/src/middleware/auth.ts) | authenticateUserrequireRolerequireAdminrequireVendorrequireCampusScopeverifyAAL2maintenanceGate | 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) | authLimiterpaymentLimitersearchLimitersupportLimiterpublicLimiter | 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) | aiRateLimiter | Dedicated 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) | cacheMiddlewareclearCache | 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) | requireIdempotency | Enforces 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) | paystackBreakergeminiBreakertermiiBreaker | 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) | validateRequest | Generic 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) | errorHandler | Terminal 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 receipts4.1 Route Namespace Specifications
| Path Pattern | Handler Module | Primary Controller / Service | Auth Scope | Key Responsibilities |
|---|---|---|---|---|
/api/payments | paymentRoutes.ts | PaymentServiceCheckoutPaymentIntent | Public / User / Webhook | Initializes Paystack checkout intents, handles raw HMAC webhooks, queries vendor banks. |
/api/orders | orderRoutes.ts | OrderServiceCampusOrderService | Authenticated Buyer/Vendor | Creates orders, records escrow deposits, verifies 6-digit delivery PINs, confirms handoffs. |
/api/products | productRoutes.ts | ProductServicePriceGuardService | Public / Vendor | Product search, filtering, inventory decrements, PriceGuard anomaly detection. |
/api/gemini | geminiRoutes.ts | GeminiServiceChatOrchestrator | Authenticated Member | Server-Sent Events (SSE) AI streaming, tool calling, product recommendation generation. |
/api/campus | campusOperationsRouter.ts | CampusOperationsService | Campus Rep / Admin | Hyperlocal pickup hub verification, student ambassador order triage, logistics logs. |
/api/disputes | disputeRoutes.ts | DisputeServiceAtomicReturnCaseService | Buyer / Vendor / Staff | Escrow dispute initiation, return evidence uploads, mediation decision recording. |
/api/admin | adminRoutes.ts | AdminServiceControlCommandService | Staff / Admin (AAL2) | Platform governance, financial observation, vendor KYC approval, staff management. |
/api/whatsapp | whatsappWebhookRoutes.ts | WhatsAppService | Meta Signature | Bi-directional customer support messaging and automated order dispatch notifications. |
/api/users/me/privacy-exports | subjectPrivacyExportRoutes.ts | SubjectPrivacyExportService | Authenticated User | Initiates 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:
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
HealthCheckService5.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
ChatGuardServiceto 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.
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]
end6.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 Identifier | Frequency | Database Stored Procedure | Purpose & Parameters |
|---|---|---|---|
generate-private-audit-export | Every 10 seconds | process_audit_export | Assembles encrypted CSV audit log batches requested by compliance officers. |
expire-private-audit-exports | Every 5 minutes | expire_audit_exports | Revokes expired presigned URLs and purges temporary audit staging objects. |
expire-private-privacy-exports | Every 5 minutes | expire_privacy_exports | Deletes unretrieved DSAR personal data export bundles exceeding the 7-day TTL. |
expire-unpaid-checkouts | Every 5 minutes | cleanup_abandoned_orders | Reallocates reserved product inventory for checkouts pending payment $> 30$ mins (p_minutes_old: 30). |
auto-complete-orders | Every 60 minutes | auto_complete_orders | Auto-releases escrow for delivered orders without dispute after 3 days (p_delivered_days: 3, p_shipped_days: 14). |
account-deletions | Every 24 hours | process_account_deletions | Purges 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 Name | Sensitive | Purpose & Target Service | Example / Format |
|---|---|---|---|
NODE_ENV | No | Execution environment toggle | production | development | test |
PORT | No | HTTP listening port for Express | 3000 |
SUPABASE_URL | No | Supabase project API gateway | https://xyzproject.supabase.co |
SUPABASE_SERVICE_ROLE_KEY | Yes | Bypass-RLS administrative key | eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... |
SUPABASE_JWT_SECRET | Yes | Shared secret for signing/verifying JWTs | 64-character hexadecimal string |
DATABASE_URL | Yes | PostgreSQL connection string | postgresql://postgres:[password]@db.xyz.supabase.co:5432/postgres |
PAYSTACK_SECRET_KEY | Yes | Paystack Live Secret Gateway API Key | sk_live_1234567890abcdef... |
GEMINI_API_KEY | Yes | Google AI Studio API Key for Nduzi | AIzaSy... |
R2_ACCOUNT_ID | Yes | Cloudflare R2 Account Identifier | 32-character hexadecimal string |
R2_ACCESS_KEY_ID | Yes | Cloudflare R2 S3-Compatible Access Key | 32-character string |
R2_SECRET_ACCESS_KEY | Yes | Cloudflare R2 Secret Key | 64-character string |
R2_PUBLIC_BUCKET | No | R2 bucket name for public catalog images | debelu-media-production |
7.2 Optional & Scaling Variables
| Variable Name | Default | Purpose |
|---|---|---|
REDIS_URL | undefined | Upgrades in-memory queues and rate limits to a distributed Redis cluster (redis://default:pwd@host:port). |
GEMINI_MODEL | gemini-2.5-flash | Configures the underlying Gemini model utilized by GeminiService. |
WHATSAPP_TOKEN | undefined | Meta WhatsApp Cloud API access token for transactional messaging. |
WHATSAPP_PHONE_NUMBER_ID | undefined | Meta registered phone number identifier. |
TERMII_API_KEY | undefined | Termii SMS gateway API key for campus verification PIN dispatch. |
TERMII_BASE_URL | https://api.ng.termii.com | Account-specific Termii API base URL. |
MAINTENANCE_JOBS | on | Set to off to disable background housekeeping timers on secondary worker nodes. |
8. Build, Testing & Deployment Pipelines
8.1 Build & Quality Verification
# 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-backend8.2 Dockerfile Topology
Production deployments utilize a multi-stage Docker build:
- Builder Stage:
- Node 20 Alpine base.
- Installs build dependencies, executes
npm ci, and compiles TypeScript sources viatsc -p tsconfig.build.json.
- Runner Stage:
- Lean Node 20 Alpine runtime.
- Copies compiled
dist/directory and production-onlynode_modules. - Runs as non-root user
nodefor enhanced container isolation. - Exposes port
3000with container health checks binding toGET /health/live.
9. Document Revision History
| Revision | Date | Lead Author | Scope of Changes | Status |
|---|---|---|---|---|
1.0.0 | 2026-10-05 | Principal Backend Architect | Initial enterprise specification detailing server bootstrap, 8 middlewares, 38 route modules, 64 domain services, BullMQ queues, and maintenance daemons. | Active Living Standard |