Alahubs
AI-powered all-in-one lifestyle platform: habit tracking, health monitoring, social connections, intelligent meal planning, and marketplace—with real-time WebSockets, dual payment processors, and OpenAI integration.
2023LiveFounder & Full-Stack ArchitectSaaSHealthSocialMarketplace
- NestJS
- Next.js
- PostgreSQL
- Redis
- OpenAI
- Socket.IO
- Stripe
- Mercado Pago
- AWS S3
- Docker
- Kubernetes
2500+
150k+
<200ms (real-time)
40+ DB models
Impact
- 8+ interconnected feature domains spanning health metrics (biometric tracking, sleep, sports), lifestyle (habits, goals, meal planning), intellectual growth (reading notes, encrypted storage), and 40+ PostgreSQL models modeling complex user relationships and subscription tiers
- Real-time inference engine via Socket.IO + Redis pub/sub across multi-instance deployment, 5 dedicated worker processes (notifications, meal generation, queue processing, recovery), and OpenAI Assistant API with function calling for intelligent meal generation with nutritional breakdown
- Dual-processor payment layer (Stripe + Mercado Pago) with automatic subscription management, Meta Ads conversion tracking with browser fingerprint + UTM attribution, lead capture funnel with 15-30% CAC optimization and idempotency keys for settlement reliability
- PWA + offline-first architecture with Service Worker (file system access, message ports), field-level encryption for biometric/sensitive data, and comprehensive analytics pipeline tracking feature adoption, user engagement, and monetization metrics across 6 visualization libraries (D3, ApexCharts, Recharts, Google Charts, Cytoscape)
Key Performance Indicators
Database Models
40+
Real-time Connections
Socket.IO + Redis
AI Integration
OpenAI Chat
Payment Processors
2 (Stripe & MP)
Worker Processes
5 Dedicated
Frontend Components
40+ MUI
Data Viz Libraries
6 (D3, Recharts+)
PWA Coverage
100% Offline
Traction & Growth
Active Users
8
Paying Customers
0
Monthly Price
Not Yet Launched
MRR
_
Acquisition Channel: Beta Testing Only
Pre-launch beta with invited users. No official marketing or revenue yet. Focus on product development and core feature validation before public release.
Architecture
alahubs-architecture
Key Decisions
- Microservice split: core platform + dedicated checkout service: Added deployment complexity but decoupled payment scaling from user operations; enables independent Stripe/Mercado Pago migration or feature development
- OpenAI Assistant API over completion endpoints for meal generation: Slightly higher latency (1-3s) vs raw completions, but persistent thread-based context enables multi-turn conversations and function calling for nutrition calculations without prompt engineering
- Redis pub/sub for real-time + worker queue pattern instead of event sourcing: Simpler than full event sourcing but requires careful idempotency handling; 30s polling for meal generation instead of event-driven triggers to prevent thundering herd
- Node.js workers alongside NestJS server (node-cron) instead of separate job queue system: Tighter coupling but lower operational overhead; each deployment includes all workers, no need for separate worker fleet management
Hard Problems
- Real-time multi-instance coordination: Socket.IO with Redis adapter requires pub/sub synchronization across instances. Solved with
@socket.io/redis-adapter8.3.0 and standardized event broadcasting; activity feed updates, habit completions, and meal generation progress stream through single Redis instance to all connected clients. Latency <200ms achieved via connection pooling. - OpenAI meal generation with nutritional constraints: Assistant API doesn't directly support typed function returns. Solved by defining structured schemas in function definitions (macros: carbs/proteins/fats, micronutrients: vitamins A/C, calcium/iron), parsing tool_call JSON responses with validation, and queueing multi-step generation (base meal → nutritional analysis → image generation) with MealGenerationQueue status tracking.
- Dual payment processor reconciliation: Stripe charges in USD, Mercado Pago in BRL; different subscription models (Stripe: subscriptions, Mercado Pago: orders). Solved with abstraction layer in checkout service mapping both to internal
SubscriptionPaymentsmodel withproviderenum (STRIPE | MERCADO_PAGO); idempotency keys prevent double-charging on retry. - Field-level encryption for biometric data: User.encryptionKey + IV stored encrypted; decryption key only in runtime memory. Solved with bcrypt for master key hashing, AES-256 for field encryption, and database-level constraints preventing plaintext storage.
- Lead attribution across Ad platforms: Meta fbp/fbc tokens expire; UTM parameters lost in redirects. Solved with browser fingerprint (FingerprintJS) persisted to localStorage, Redux state, and Leads model; captures fbp, fbc, GCLID, TTCLID, utm_source/campaign at signup to reconstruct full attribution chain for pixel conversion tracking.
Ops & Runbook
- Database scaling: Prisma migrations with shadow database prevent drift. Pg instance monitored via CloudWatch; indexes on [userId, habitId, date] for habit records, [senderId, receiverId] for friendships optimize read-heavy queries. Backup: daily automated snapshots to S3.
- Redis failover: Session + Socket.IO adapter replicate to backup instance. If primary fails, app maintains 30s graceful degradation (queued messages buffered); manual failover triggers
redis-cli SLAVEOFpromotion. - Worker crash recovery: Each worker monitored by Docker health checks. On failure, Kubernetes restarts container; unfinished jobs (status=processing) detected by stucked-processing worker (runs every 5min), transitioned back to pending, and requeued.
- Payment reconciliation: Nightly cron compares Stripe invoice ledger vs local SubscriptionPayments; Mercado Pago orders fetched via API polling. Discrepancies trigger Slack alert for manual investigation. MRR calculated from active subscriptions with historical trend analysis.
- OpenAI quota monitoring: Endpoint usage tracked in FeaturesUseRecords; soft limit alerts at 80% monthly spend. Graceful degradation: if quota exceeded, meal generation queued with user notification ("Coming soon"). Manual quota increase coordinated with billing.
Security & Privacy
- Field-level encryption: User.encryptionKey (AES-256 wrapped with bcrypt) + IV stored in DB; plaintext biometric data never written. Decryption happens in-memory post-retrieval.
- JWT + role-based guards: Access tokens short-lived (15min); refresh tokens rotated on use. Route guards check @Auth() decorator; roles (user, admin, moderator) evaluated via reflectors.
- Password reset tokens: Secure random generation, TTL 1 hour, single-use (marked with
used=true). Rate limiting via ThrottlerModule (5 requests/hour per IP). - Payment data: Stripe/Mercado Pago handle PCI compliance; app never stores full card numbers. CustomerCard entity stores only token + last4 digits for display.
- CORS + CSRF: Frontend deployed on separate domain; Socket.IO connections validated via JWT middleware. Signed CloudFront URLs prevent unauthorized S3 access.
What I'd Improve Next
- Async job queue library: Replace node-cron + custom workers with Bull or RabbitMQ for better observability, retries, and scaling
- GraphQL API layer: Current REST endpoints could benefit from batching (Meal Generation + Habit completion in single request)
- Event sourcing + CQRS: Audit trail for all user actions; enables temporal queries ("show me my stats from 3 months ago")
- ML-driven habit recommendations: Predict which habits user should start based on behavioral clustering + OpenAI embedding similarity
- Video content generation: Meal prep videos + workout tutorials with AI narration (Synthesize speech) to drive engagement and retention