Case Study · Freelance Work

Enlearn Academy

Lead generation platform, admin panel with lead collection, custom mini CRM, and CMS — built with a layered repository architecture and asynchronous outbox workers.

Next.jsExpressTypeScriptMongoDBRedisPM2Hostinger VPS

Layered Modular Architecture & Repository Pattern

Problem: Controllers directly queried Mongoose models, and middleware was tightly coupled to feature schemas, creating circular dependencies and un-testable business logic.
Implementation:
  • Refactored all 10 core modules (auth, courses, leads, cms, blogs, etc.) into a strict 5-tier pipeline: Route → Controller → Service → Repository → Model.
  • Inverted dependencies between authentication middleware and user models using runtime lookup providers (configureAuthUserLookup).
  • Added automated architectural boundary linting via dependency-cruiser (npm run arch:check) to fail CI builds on direct controller-to-model imports or cross-module repository leaks.
  • Isolated business logic with Vitest unit tests mocking repository and caching layers.
Impact: 0 circular dependencies and 0 architectural violations across 101 TypeScript modules; 100% unit-test execution without live database instances.

Transactional Outbox Pattern & Phone Deduplication

Problem: Lead capture (POST /api/leads) ran synchronous Google Sheets API syncs and Excel generation inside the HTTP request loop, causing ~3.07s response times and duplicate lead creation on repeat submissions.
Implementation:
  • Transactional Outbox: Decoupled external syncs. The API writes the lead record and an atomic OutboxEvent (status: pending) to MongoDB, returning HTTP 201 in under 160ms.
  • Resilient Background Worker: A dedicated worker atomically claims events (findOneAndUpdate), syncs Google Sheets and Excel asynchronously, auto-recovers stale locks (>2 min), and retries failures with exponential backoff (5s → 10s → 20s → 40s → 80s).
  • 30-Day Silent Deduplication: Checked incoming phone numbers via findRecentLeadByPhoneInDB(phone, 30). Existing leads have their course interest updated silently without generating duplicate rows or redundant external webhook calls.
Impact: Response latency dropped from 3,075 ms to 150 ms (~20x speedup); eliminated duplicate rows across MongoDB and Google Sheets.

Fail-Open Redis Cache-Aside Layer

Problem: High-traffic public endpoints (/api/courses, /api/cms, /api/blogs) made repeated database queries on every page hit for data that rarely changed.
Implementation:
  • Integrated a fail-open ioredis cache-aside client (getOrSetCache, invalidateCache). If Redis crashes or times out, the service safely falls back to MongoDB with zero user-facing downtime.
  • Configured 5–15 minute TTLs on public reads with automated, non-blocking SCAN-based prefix invalidation triggered on admin mutations (create, update, delete).
Impact: GET /api/cms improved from 90.5 ms to 36.3 ms (~2.5x faster); GET /api/courses improved from 122.4 ms to 56.9 ms (~2.1x faster).

Rotating Refresh Tokens & Family Replay Detection

Problem: Admin portal previously relied on static long-lived JWTs without server-side revocation or token theft detection.
Implementation:
  • Implemented single-use refresh tokens stored in secure HttpOnly cookies, mapped to a familyId in Redis.
  • Built automatic token-family replay revocation: if an already-invalidated refresh token is reused, the entire token family is immediately purged from Redis, the user tokenVersion increments in MongoDB, and all active sessions are terminated.
Impact: Closed session hijacking attack vectors with automated replay detection and instantaneous session revocation.

Structured Logging & Distributed Correlation (pino)

Problem: Unstructured console.log statements made debugging concurrent requests and error tracking impossible on production VPS logs.
Implementation:
  • Replaced native logging with pino and pino-http.
  • Injected unique crypto.randomUUID() request correlation IDs via X-Request-ID across every HTTP lifecycle.
  • Configured automatic field redaction for sensitive keys (authorization, cookie, password).
Impact: Traceable request lifecycles across concurrent workloads with sanitized, JSON-structured output.

Frontend SSR/ISR & BFF Architecture

Problem: Modular landing page sections fired redundant parallel calls to /api/cms and /api/courses, while public pages suffered from layout shifts due to client-side useEffect data fetching.
Implementation:
  • TanStack Query Request Deduplication: Unified concurrent component queries into single in-flight network requests with a 5-minute memory cache.
  • Server Components & ISR: Converted /blogs and /books to Server Components with Incremental Static Regeneration (revalidate = 300), serving pre-rendered HTML without client-side loading spinners.
  • BFF Proxy: Added a Next.js API catch-all proxy with centralized fetchWithAuth interceptors for seamless 401 background token refresh and optimistic UI updates on admin actions.
Impact: Eliminated duplicate homepage API waterfalls and client-side loading spinners on public content pages.