Executive Summary: Problem, Solution & Results
| Dimension | Project Insight |
|---|---|
| Business Problem | Operational friction and lost revenue in informal retail caused by chat vs. physical stock desynchronization, customer no-shows (“plantones”), and empirical delivery pricing. |
| Engineering Solution | Distributed ecosystem featuring NestJS Hexagonal Architecture, PostgreSQL connection-level RLS (AsyncLocalStorage), a two-phase inventory reservation state machine, Next.js web portal, and real-time AI WhatsApp bot (Baileys). |
| Measurable Impact | Production-grade multi-tier ecosystem engineered solo in 3 months, elimination of countertop overselling through two-phase reservation, PostgreSQL-backed Signal session persistence, and top-tier academic honors. |
1. The Vision: Going Far Beyond a Standard Backend
Origin and Engineering Motivation
This project was built between March and June of this year as the final assignment for a university course focused strictly on backend engineering. The baseline academic requirement was simply to deliver a standard REST API or conventional CRUD; however, driven by curiosity to explore distributed real-world systems and build something far more interesting and technically rewarding than a textbook assignment, I chose not to stop at the minimum requirement.
I decided to expand the project into a complete omnichannel ecosystem: solving a tangible problem in emerging informal commerce—where independent vendors lose sales to chaotic WhatsApp chats, suffer from buyer no-shows (“plantones”), and guess delivery costs—by building not just the backend server, but also a web administrative portal, dynamic public storefronts, an offline-capable mobile companion app, and an AI conversational sales bot.
[!NOTE] Defense Reaction: During the final project evaluation, the course professor initially doubted that a single student had engineered such a vast architecture in an individual assignment (Hexagonal NestJS backend, PostgreSQL with RLS, Next.js web portal, React Native mobile client, and real-time WhatsApp Web socket engine). Walking through the codebase line by line and demonstrating the live end-to-end transactional flow proved full individual authorship and earned top-tier honors.
2. Architecture & Engineering Decisions
To ensure the backend adhered to professional engineering standards and cleanly supported multiple clients, I implemented advanced architectural patterns:
Strict Multi-Tenancy via PostgreSQL RLS & AsyncLocalStorage
To guarantee zero cross-tenant data leakage without relying solely on error-prone manual WHERE tenant_id = ... queries:
- PostgreSQL Row-Level Security (RLS) was enforced across all sensitive relational tables.
- A global NestJS interceptor extracts the tenant context from the incoming request, binds it to Node.js
AsyncLocalStorage, and executes on the database connection:
SELECT set_config('app.current_tenant_id', $1, true). - This offloads tenant isolation directly to the PostgreSQL engine, making cross-tenant data access structurally impossible regardless of application-level bugs.
Two-Phase Inventory State Machine
To eliminate race conditions between in-person market sales and chat orders:
- When an order is scheduled (via web catalog, app, or WhatsApp bot), inventory is not immediately depleted; it transitions into a
stockReservadopool under apendienteorder state. - Once the order is handed over and paid, a transactional operation executes
confirmarEntregaDesdeReservaBatch, recording the final accounting deduction. - If the buyer cancels or fails to show up (“plantón”),
liberarReservaBatchimmediately restores the units back to available stock without manual intervention.
Distributed WhatsApp Session Persistence (Baileys + PostgreSQL)
By default, the @whiskeysockets/baileys library writes cryptographic keys and authentication tokens directly to the local disk file system, making container restarts or horizontal scaling impossible without forcing merchants to re-scan QR codes:
- I built a custom adapter (
WhatsappAuthAdapter) implementing Baileys’ Signal auth interface, intercepting identity keys, registration state, and credentials, and persisting them in PostgreSQL (bot_session_auth) usingBufferJSONrevivers. - To safeguard merchant phone lines against automated spam detection, I implemented browser fingerprint rotation (Chrome Linux pool), randomized human typing delays (1–3 seconds), and suspended aggressive reconnect loops during WhatsApp’s nightly maintenance windows (2:00–5:00 AM).
Geospatial Pricing Engine with Turf.js
The delivery module validates customer GPS coordinates in real time:
- Runs
booleanPointInPolygonto verify whether the buyer’s drop-off point lies inside the merchant’s free-delivery coverage zone. - Calculates precise point-to-point road distances using the Haversine formula to price excess mileage dynamically, automatically rejecting addresses outside the allowable operational radius.
EmprendeMás Technology Stack
Modular monolithic backend designed with Hexagonal Architecture, multi-tenant interceptors, and pg-boss job queues.
Administrative web dashboard (React 19, TanStack Query v5, Tailwind CSS v4, and MapLibre GL for geofencing).
Mobile companion app for physical stalls featuring local SQLite caching, biometric auth, and push notifications.
Relational persistence engine with connection-level Row-Level Security isolation.
Object-relational mapping, versioned migrations, transactional managers, and analytical queries.
Multi-session WhatsApp Web socket engine with custom database-backed Signal cryptographic state.
Conversational order intake assistant with multi-provider fallback and financial anomaly detection.
Containerized deployment with Docker Compose and production Kubernetes manifests with health probes.
3. Technical Post-Mortem: Challenges, Trade-offs & Lessons
The project successfully concluded with top evaluation marks upon defense. It did not transition into prolonged commercial operation primarily because the codebase expanded rapidly in a very short window, requiring dedicated operational bandwidth and optimization passes that exceeded my availability as a student. However, it served as the most transformative engineering sandbox of my journey:
1. Massive Context Injection vs. Structured Tool Calling
- The early mistake: Before reliable Function Calling standards matured in affordable models, the WhatsApp bot attempted to “memorize” the store’s entire catalog by serializing raw inventory text directly into the system prompt, coupled with uppercase directives like
STRICT RULES: NEVER hallucinate products. - The consequence: As product catalogs expanded, token overhead and prompt latency skyrocketed, and the model occasionally confused similar sizes or ignored instructions during protracted dialogs.
- Modern engineering takeaway: Commerce agents must never memorize inventory via raw system prompt stuffing. They must interface through deterministic Tool Calling, fetching real-time stock via dedicated internal APIs and validating inputs and outputs against strict schemas (e.g., Zod) before replying to customers.
2. Premature Hexagonal Over-Engineering
- The early mistake: Enforcing strict Hexagonal Architecture with exhaustive layer separation (Domain, Application, Infrastructure, Interfaces) across all 15 system modules from week one.
- The consequence: Substantial boilerplate overhead (DTOs, interface contracts, mapper services) that slowed iteration velocity during product discovery when business requirements were still fluid.
- Modern engineering takeaway: During early prototype phases, pragmatic modularity (Vertical Slice Architecture) maximizes shipping speed, reserving deep hexagonal decoupling strictly for complex, high-volatility transactional cores.
3. Concurrency between Digital Messaging and Countertop Sales
- The challenge: The risk of selling an item physically at the market stall at the exact instant an online buyer was confirming it over WhatsApp.
- The outcome: Introducing the two-phase state machine (
stockRealvs.stockReservado) with automatic reservation expiration proved that finite state machines are essential for zero-error omnichannel operations.
4. Conclusion
EmprendeMás marked my transition from completing standard university exercises to managing the genuine complexity of a distributed platform: engine-level database security, fault-tolerant socket connections, offline resilience, and AI conversational workflows. Choosing to go far beyond what the backend course requested taught me firsthand the trade-offs between architectural purity, development speed, and maintainability—insights that shape how I design every system today.



