Case Study // SaaS & AI System•Full-Stack Software Engineer & AI System Architect

LeadMachine (SaaS-AI)

Autonomous AI Business Platform for Enterprise Lead Discovery & Intelligence

Endpoint Telemetry: /api/v1/leads/enrichment-pipeline
ACTIVE RUNTIME CONTEXT

ai_engine=Google_Gemini • rate_limit=PASS_REDIS • status=ENRICHED_200

Status: Live • Category: SaaS & AI System
Executive Overview

LeadMachine (SaaS-AI) is an autonomous business platform engineered to automate lead discovery, structured firmographic enrichment, predictive outcome scoring, and strategic outreach. Built on Next.js 16 and Prisma ORM, it addresses common operational friction in modern B2B customer acquisition pipelines.

Problem Addressed

Triaging unstructured web inquiries and manual lead research causes severe response delays and lost revenue opportunities. Meanwhile, standard AI implementations often generate non-deterministic responses, lack rate-limiting protection, and risk exposing sensitive tenant context across shared models.

Target Users & Real Use Case

B2B sales teams, growth marketing agencies, and software startups requiring automated, high-precision prospect qualification without hiring dedicated research personnel.

My Role & Engineering Contributions
  • Designed end-to-end system architecture from database relational schemas to Next.js 16 UI and edge middleware.
  • Implemented Upstash Redis rate-limiting guards to protect serverless functions and generative AI budget.
  • Engineered Google AI (Gemini) prompt pipelines enforcing strict JSON schema parsing and fallback states.
  • Created Prisma migration workflows and seed scripts ensuring database consistency across environments.
  • Integrated Inngest event handlers for resilient background processing of lead enrichment queues.
Technical Stack & Framework Breakdown
Frontend & UI Framework
Next.js 16 (App Router)React 19Tailwind CSS v4Lucide React Icons
Backend & Data Layer
Node.js 22 runtimePrisma ORMPostgreSQL databasePrisma Migrations
AI & Event Orchestration
Google AI (Gemini API)Inngest Event WorkersUpstash Redis Rate Limiter
Billing & Infrastructure
Stripe Checkout & WebhooksVercel Edge PlatformTypeScript Strict Mode
Architecture Blueprint & System Topology

LeadMachine (SaaS-AI) System Architecture

A three-tier modern SaaS architecture separating client-side presentation, edge-governed API logic with rate limiting, and an asynchronous data/AI pipeline with PostgreSQL persistence.

Legend:
Verified / Current Component
Planned / Roadmap Component

01. Presentation & Client Layer

Fast, responsive Next.js 16 App Router client with server-driven components.

Tier 1
Executive Dashboard UICurrent

Interactive overview of lead health, forecasts, and conversion funnels

Next.js 16 + React 19
Lead Discovery & Table ViewCurrent

Sortable, filterable list of prospective leads with enrichment status

Tailwind CSS v4
Tenant Settings & BillingCurrent

Subscription tier management and Stripe customer billing portal link

Stripe Elements

02. API & Edge Security Layer

Edge-executed middleware and Next.js route handlers with defensive guards.

Tier 2
Upstash Redis Rate LimiterCurrent

Token-bucket rate limiting defending AI endpoints against abuse & quota exhaustion

Upstash Redis SDK
RBAC Auth & Session ValidatorCurrent

Verifies user permissions before accessing tenant analytics and data mutations

Next.js Route Handlers
Stripe Webhook ReceiverCurrent

Processes invoice events and subscription state changes idempotently

Stripe Webhooks

03. Intelligence & Data Pipeline

AI model orchestration, background task processing, and relational storage.

Tier 3
Google AI (Gemini) IntelligenceCurrent

Analyzes company domains, scores buyer readiness, and structures JSON payloads

Google AI Studio / Gemini API
Inngest Event OrchestratorCurrent

Asynchronous task queue handling multi-step lead enrichment with retries

Inngest SDK
Prisma ORM & PostgreSQLCurrent

Primary relational datastore holding tenants, leads, logs, and billing state

PostgreSQL + Prisma
Vector Embedding SearchPlanned

Semantic retrieval across historical CRM conversations

pgvector / PlannedArchitectural milestone slated for future release.
Verified Components in Repository (6)
  • Next.js 16 App Router UI
  • Prisma ORM Schema & Migrations
  • PostgreSQL Database Connection
  • Upstash Redis Rate Limiting
  • Google AI / Gemini Pipeline
  • Stripe Billing Webhook Integration
Documented Future Roadmap (2)
  • Vector Embedding Store (pgvector)
  • Microsoft 365 / Google Workspace Bi-Directional OAuth Mail Sync
Key Engineering Decisions & Architectural Trade-offs

#1: Defensive Edge Rate-Limiting with Upstash Redis

Decision Record
Context & Constraints

Generative AI API endpoints incur direct cost per token and are vulnerable to malicious scraping or runaway loops.

Architectural Decision

Implemented Upstash Redis token-bucket rate limiting in middleware before any LLM API invocation or database compute is reached.

Trade-offs Accepted

Adds a negligible ~15ms network hop to Redis on API requests, but completely eliminates runaway LLM billing spikes and denial-of-wallet vectors.

Evidence: Verified in repository dependencies and documentation reports (phase48_system_command_center_report.md).

#2: Prisma Schema Migration Discipline over Ad-Hoc DB Writes

Decision Record
Context & Constraints

Fast-moving prototype code often introduces database schema drift between local, preview, and production environments.

Architectural Decision

Enforced all database modifications through version-controlled Prisma migration files (migrations/) and explicit prisma.config.ts configuration.

Trade-offs Accepted

Requires running migration scripts for every schema iteration instead of direct DB mutations, but ensures 100% reproducible environments and type safety.

Evidence: Repository contains dedicated migrations/ directory and seed.mjs script for deterministic database initialization.

#3: Asynchronous Enrichment Decoupling with Inngest

Decision Record
Context & Constraints

Firmographic scraping and LLM evaluation take several seconds, risking serverless HTTP gateway timeouts if handled synchronously.

Architectural Decision

Decoupled HTTP intake from enrichment work using Inngest event queues, returning an immediate 202 response to the user while background jobs execute.

Trade-offs Accepted

Requires client polling or real-time event updates to reflect completed state, but prevents HTTP 504 timeouts and offers automatic retry backoff.

Evidence: Implemented and documented in project architecture overview and dependency manifests.
Security & Reliability Controls
Input Validation & Rate Limiting

Upstash Redis rate-limiting guards applied on public routes with strict token bucket allocations per IP and tenant ID.

Verification Scope:Verified via edge middleware configuration and verified documentation reports in repository.
Authentication & RBAC

Role-based permissions governing administrative endpoints, restricting billing modifications to tenant owner accounts.

Verification Scope:Route handlers enforce session validation and organization ID matching before executing mutations.
Auditability & Logging

Audit trails recorded across administrative actions, documented in phase 48 observability and system readiness reports.

Verification Scope:Committed reports (phase48_system_command_center_report.md) confirm logging standards and verification evidence.

Repository Audit & Evidence // LeadMachine (SaaS-AI)

Verified software artifacts and production verification scope for LeadMachine (SaaS-AI)

Public GitHub Repository (MIT)
Verified Commits41 commits
Core LanguageTypeScript
LicenseMIT License
Automated TestsVerified
Inspected Files & Structural Manifest
prisma/schema.prismaprisma.config.tsmigrations/src/app/tests/seed.mjsphase48_system_command_center_report.mdphase48_1_security_truth_hardening_report.md
Quality Assurance & Testing Evidence:Repository includes automated tests directory (tests/) and npm test script. Validated phase stabilization reports committed to version control.
Integrity & Scope Disclosure:

Microsoft 365 OAuth sync and multi-tenant vector embedding collections are documented as planned future roadmap items; not yet merged into production main.

Core Engineering Challenges Resolved
Preventing LLM Output Hallucinations and Schema Variance

Configured Google AI Gemini prompts with strict JSON schema definitions and created Zod validation boundary checks to parse and sanitize all model responses.

Database Schema Drift across Environments

Maintained explicit version-controlled migrations in the migrations/ folder and automated seed scripts to guarantee reproducible test environments.

Current Implementation Status & Technical RoadmapLive

Live Production Prototype. The core application, AI enrichment pipeline, Prisma migrations, and Stripe integration are deployed and operational at https://saas-ai-sooty.vercel.app.

Documented Upcoming Milestones
  • Vector embedding store with pgvector for semantic CRM lookups.
  • Direct OAuth integration for Microsoft 365 and Google Workspace email dispatch.
  • Team collaboration workspaces with granular sub-user permissions.

Related Systems in RANA.OS

View All Projects →