Transparency Disclosure: Company-Owned Product
Unlike our client case studies—where customer corporate identities and proprietary metrics are anonymized under bilateral Non-Disclosure Agreements (NDAs)—AI Dev Planner is our own proprietary SaaS product.
Every architectural diagram, database schema, Zod validation contract, and line of code documented here is inspectable in our production monorepo. This case study demonstrates our actual engineering standards, security practices, and product architecture when building software for ourselves.
1. The Problem: The High-Cost “Pre-Code Gap”
Across hundreds of software engineering consultations, we observed a consistent failure mode: early budgets vanish before writing the first line of code. Founders and product teams frequently spend $15,000 to $50,000 contracting design agencies or initial development sprints before answering foundational questions:
- Unexamined Competitor Landmines: Products built without investigating established market incumbents, leading to feature duplication without differentiation.
- Premature Architecture Commitments: Guessing at backend infrastructure, provisioning complex microservices for simple MVPs, or choosing frameworks unsuited to business constraints.
- Delayed Data Modeling: Delaying relational schema and permission modeling until mid-build, requiring costly database refactoring when multi-tenant isolation is retrofitted.
Generic conversational AI tools failed to solve this. Large Language Models (LLMs) in chat interfaces generate confident, conversational answers regardless of factual basis, cite hallucinated sources, fail to enforce relational constraints, and cannot produce deterministic JSON contracts that engineers can execute against.
2. Product Purpose: Evidence-Grounded Technical Blueprinting
AI Dev Planner was conceived as an automated technical planning platform. Instead of an open-ended conversational bot, it operates as a deterministic research pipeline that transforms a structured business concept into an actionable engineering blueprint:
Gathers real competitor URLs, pricing tables, and user complaints via Firecrawl search APIs before any LLM inference occurs.
Evaluates market demand, technical feasibility, and economic viability, isolating the riskiest assumptions that could sink the build.
Produces a Keep/Pivot/Drop verdict, PostgreSQL schema ERDs, REST API contracts, and a 3-tier milestone sprint roadmap.

The AI Dev Planner interface: interactive validation metrics, assumption testing, and blueprint generation.
3. System Architecture & Monorepo Topology
AI Dev Planner is organized as a Turborepo monorepo with pnpm workspaces. The architecture strictly isolates the consumer-facing marketing site from the authenticated web platform, while binding both to centralized schema and utility packages:
- Startup idea
- Market research
- Evidence report
- Build plan
Figure 1.0: End-to-end data pipeline of AI Dev Planner mapping intake research to validated blueprints.
Public Marketing & Documentation
Next.js 16 App Router on Hostinger Node.js standalone runtime. Server-rendered for instant indexing, sub-second TTFB, and zero client JS waterfalls.
Authenticated SaaS Platform
Multi-tenant SaaS on app.aidevplanner.com. 43 product screens, 38 API route handlers, Supabase Auth integration, and client-side Recharts visualizations.
Shared Zod Contracts
Single source of truth. Shared validation schemas for auth, project intake, research parameters, and LLM output parsing across all monorepo apps.
Shared Component Library
Reusable accessible UI primitives, buttons, dialogs, inputs, and form elements styled with Tailwind CSS and Radix UI primitives.
Core Utilities
Formatting utilities, currency conversions, math algorithms, and class merging (`cn()`) functions.
PostgreSQL Data Layer
Version-controlled SQL migrations defining tables, compound indexes, triggers, and Row-Level Security policies.
The 5-Stage Staged Inference Pipeline
Rather than executing an unconstrained single prompt that risks context token limits, our generation engine (`apps/app/lib/generation/groq.ts`) decomposes research into five sequential stages with explicit data handoffs:
Structured Intake
Collects business context, target audience, budget bounds, and technical constraints via a guided form instead of an unstructured chat box.
Live Evidence Search
Executes 3 targeted web queries via Firecrawl to gather active competitor profiles, market data, and user complaints, de-duplicating by URL.
Structured Research
Extracts validated competitor feature sets, pricing models, and citations with explicit confidence ratings from retrieved web evidence.
Assumption Validation
Scores viability across demand, technical feasibility, and unit economics, isolating the riskiest assumptions that could sink the product.
Actionable Synthesis
Generates an immutable Keep/Pivot/Drop verdict, database ERD schema mappings, API specifications, and a 3-tier milestone sprint blueprint.
4. Database Architecture & RLS Design
User data security was an architectural requirement from day one. In SaaS platforms, application-level authorization checks (`WHERE user_id = req.user.id`) are fragile; a single missed filter in an API handler creates catastrophic cross-tenant data leakage.
We enforced tenant isolation at the PostgreSQL kernel using Supabase Row-Level Security (RLS). Even if an API endpoint executes an unqualified `SELECT * FROM projects`, PostgreSQL intercepts the query and restricts results strictly to the authenticated UUID (`auth.uid()`):
-- Table definition with foreign key cascade to Supabase Auth
CREATE TABLE IF NOT EXISTS public.generation_jobs (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
owner_id uuid NOT NULL REFERENCES auth.users (id) ON DELETE CASCADE,
project_id uuid NOT NULL REFERENCES public.projects (id) ON DELETE CASCADE,
job_type text NOT NULL CHECK (job_type IN
('research', 'validation', 'plan', 'documents', 'report', 'recommendation')),
status text NOT NULL DEFAULT 'pending' CHECK (status IN
('pending', 'running', 'completed', 'failed')),
payload jsonb,
result jsonb,
error text,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now()
);
-- Compound index optimizing project job lookups
CREATE INDEX IF NOT EXISTS generation_jobs_project_idx
ON public.generation_jobs (project_id, created_at DESC);
-- Enable Row-Level Security
ALTER TABLE public.generation_jobs ENABLE ROW LEVEL SECURITY;
-- Kernel-level RLS policies strictly scoped to authenticated user session
CREATE POLICY "generation_jobs_owner_select" ON public.generation_jobs
FOR SELECT USING (owner_id = auth.uid());
CREATE POLICY "generation_jobs_owner_insert" ON public.generation_jobs
FOR INSERT WITH CHECK (owner_id = auth.uid());Version Immutability & Concurrency Guard
To prevent race conditions where two simultaneous inference jobs overwrite the same project analysis, we introduced a unique database constraint (`supabase/migrations/20260913000002_add_report_version_guard.sql`):
-- Prevent concurrent report generations from sharing a report version
CREATE UNIQUE INDEX IF NOT EXISTS reports_project_version_uidx
ON public.reports (project_id, version);5. Security Design & Atomic Throttling
Because founders entrust unreleased startup intellectual property to AI Dev Planner, the application enforces defense-in-depth across the network, session, and database layers:
Cookie-Based Session Hygiene
JWT access and refresh tokens are managed by `@supabase/ssr` using `HttpOnly`, `Secure`, and `SameSite=Lax` cookies, eliminating localStorage cross-site scripting (XSS) attack vectors.
Structured Prompt Injection Defense
Unconstrained chat boxes invite prompt injection and jailbreaks. We intake inputs through strongly typed fields with character limits, passing parameters in JSON mode to enforce output schemas.
Database-Level Rate Throttling
To protect authentication endpoints and model generation triggers against credential stuffing or quota exhaustion, we implemented atomic plpgsql rate limiting directly inside PostgreSQL (`supabase/migrations/20260912120000_auth_security.sql`):
-- Atomic rate limit evaluation in PostgreSQL
CREATE OR REPLACE FUNCTION public.consume_auth_rate_limit(
p_key text,
p_limit integer DEFAULT 5,
p_window_seconds integer DEFAULT 900
) RETURNS boolean LANGUAGE plpgsql SECURITY DEFINER SET search_path = public AS $$
DECLARE allowed boolean;
BEGIN
INSERT INTO auth_rate_limits (key, request_count, expires_at)
VALUES (p_key, 1, now() + make_interval(secs => p_window_seconds))
ON CONFLICT (key) DO UPDATE SET
request_count = CASE WHEN auth_rate_limits.expires_at <= now() THEN 1 ELSE auth_rate_limits.request_count + 1 END,
expires_at = CASE WHEN auth_rate_limits.expires_at <= now() THEN now() + make_interval(secs => p_window_seconds) ELSE auth_rate_limits.expires_at END,
updated_at = now()
RETURNING request_count <= p_limit INTO allowed;
DELETE FROM auth_rate_limits WHERE expires_at < now() - interval '1 day';
RETURN allowed;
END;
$$;6. Validation: Single-Schema Source of Truth
In many full-stack applications, validation rules are duplicated: React Hook Form uses one regex in the browser, API route handlers check another, and database constraints enforce a third. This inevitably causes validation desync bugs.
We eliminated this by isolating all schemas into `@repo/schemas`. A single Zod contract validates client inputs in the browser, guards server actions, and parses Groq model JSON outputs before database ingestion:
import { z } from "zod";
export const signUpSchema = z.object({
fullName: z.string().min(2, "Full name is required"),
email: z.string().min(1, "Email is required").email("Invalid email format"),
phone: z.string().min(10, "Phone number must be at least 10 characters"),
country: z.string().min(2, "Country is required"),
password: z.string()
.min(8, "Password must be at least 8 characters")
.regex(/[A-Z]/, "Password must contain at least one uppercase letter")
.regex(/[0-9]/, "Password must contain at least one number")
.regex(/[^A-Za-z0-9]/, "Password must contain at least one special character"),
confirmPassword: z.string().min(1, "Please confirm your password"),
terms: z.boolean().refine((val) => val === true, "You must accept terms"),
}).refine((data) => data.password === data.confirmPassword, {
message: "Passwords don't match",
path: ["confirmPassword"],
});For model generation, Groq API responses are validated directly against Zod schemas (`reportSchema`, `validationSchema`, `experimentsSchema`). If the model omits a required field or returns invalid types, Zod coerces defaults or triggers a clean retry rather than crashing the front end.
7. Engineering Challenges & Production Resolutions
Challenge 1: Context Window Exhaustion from Raw Web Crawls
Issue: Initial pipeline prototypes ingested entire raw HTML pages from search results. A single verbose competitor homepage or terms document exhausted model token budgets and caused rate-limit crashes.
Resolution: We decoupled research into two tiers: Stage 2 (Research) ingests page content via Firecrawl and extracts compact structured findings. Downstream stages (Validation and Synthesis) receive only the extracted summaries, URLs, and confidence ratings, reducing token consumption by over 80%.
Challenge 2: Hanging External Model Invocations
Issue: During peak provider loads, external LLM API calls occasionally stalled indefinitely without closing the HTTP socket, causing serverless handlers to time out ungracefully.
Resolution: Implemented a 45-second `AbortController` timeout parameter on all Groq fetch invocations. Overrunning stages abort cleanly, log diagnostic telemetry, and return structured error states to the user.
Challenge 3: Client/Server State Synchronization
Issue: Maintaining distinct form validators on the front end and API handlers led to edge cases where the browser accepted inputs that the server rejected.
Resolution: Centralized all contracts into `@repo/schemas`, consumed simultaneously by React Hook Form (`@hookform/resolvers/zod`) and Next.js server actions.
8. Key Architectural Decisions Analyzed
Next.js App Router for Unified Monorepo Full-Stack Delivery
- Our Architectural Choice
- Server Components for SEO marketing pages that require instant indexing, paired with interactive Client Components for complex multi-step intake wizards and Recharts data dashboards.
- Alternatives Considered
- A standalone Vite React SPA for the dashboard paired with a separate static Astro marketing site, or Remix.
- Trade-offs & Constraints
- Server/Client component boundaries require careful discipline around props serialization, and webpack standalone builds take longer.
- Measured Production Outcome
- One framework, one deployment target, and zero duplication of UI packages or validation logic across our marketing and product layers.
PostgreSQL Row-Level Security for Multi-Tenant Isolation
- Our Architectural Choice
- Tenant access rules reside directly inside PostgreSQL, enforcing data isolation natively based on auth.uid().
- Alternatives Considered
- Application-level multi-tenancy where every Node.js query manually includes a user_id filter.
- Trade-offs & Constraints
- Tighter coupling to Supabase PostgreSQL semantics, requiring SQL migration discipline for all schema changes.
- Measured Production Outcome
- Zero possibility of accidental cross-tenant data leakage from forgotten query filters in application code.
Multi-Stage Pipeline vs. Monolithic LLM Prompts
- Our Architectural Choice
- Decomposed research into five discrete calls, each returning a small, Zod-checked JSON object within a fixed token boundary.
- Alternatives Considered
- A single giant prompt asking the model to generate the entire research, validation, and synthesis report at once.
- Trade-offs & Constraints
- Sequential calls add roughly 12–18 seconds of total processing latency compared to a single streaming completion.
- Measured Production Outcome
- Failures pinpoint exact stages; each phase is unit-testable independently; hallucinations in early steps are arrested before corrupting final blueprints.
9. Codebase Metrics (100% Verifiable)
In accordance with our strict trust policy, we do not publish speculative conversion rates, unverified revenue numbers, or fabricated user counts. The figures below reflect the verified structural composition of the AI Dev Planner codebase, audited directly from the monorepo:
Interactive routes across onboarding, research, market intelligence, validation, and exports in apps/app.
Next.js App Router route handlers with strict runtime input validation before touching PostgreSQL.
Modular TypeScript components across apps/app and shared UI packages with zero any types.
PostgreSQL migrations enforcing Row-Level Security (RLS) on all user-owned tables.
Turborepo packages (@repo/ui, @repo/schemas, @repo/types, @repo/utils, @repo/config, @repo/blog).
Sequential AI research pipeline: intake, live evidence, research, validation, and synthesis.
Real-time Firecrawl queries collecting competitor, market size, and customer complaint evidence per run.
Strict AbortController circuit breaker preventing hanging inference requests.
How We Evolved the Product
- v1 (Early 2024): Open conversational chat. Rejected because unstructured prompts resulted in generic advice without technical precision.
- v2 (Mid 2024): Replaced chat with a 4-step structured intake wizard capturing audience, budget, and tech constraints up front.
- v3 (Late 2024): Integrated live Firecrawl search queries to ground all competitor claims in real, active web URLs.
- v4 (2025–2026): Centralized `@repo/schemas` monorepo validation, added unique version guards, and built in-browser PDF/ZIP export generation.
Principles Applied to Client Engagements
- Model Outputs are Untrusted Inputs: Always parse LLM completions against Zod schemas; provide safe fallbacks for unexpected keys.
- Enforce Tenancy in PostgreSQL: Configure Row-Level Security on day one. Retrofitting RLS onto live databases is costly and error-prone.
- Circuit Breakers on All APIs: Set hard execution deadlines on third-party calls to prevent serverless lockups.
- One Source of Truth for Types: Share Zod schemas across client and server layers to eliminate interface divergence.
Explore Client Architecture Case Studies
FinTech Trading Platform Case Study
The client's on-premise monolith experienced database locks and synchronization drift during market open spikes. We architected and deployed an event-driven AWS microservices infrastructure with immutable Kafka event streams and a real-time Next.js trading cockpit.
Healthcare Patient Portal Case Study
Clinic staff spent 40+ minutes per check-in manually photocopying insurance cards and transcribing health histories. We engineered a HIPAA-aligned digital pre-registration portal with automated OCR document extraction and mandatory clinician human-in-the-loop review.
AI Fleet Routing Software Case Study
Static weekly dispatch plans caused fleet idling, missed border appointments, and fuel waste. We engineered an IoT telemetry pipeline ingesting live truck coordinates via AWS IoT Core and a React Native driver app with offline heuristic routing.
Experience the Platform or Build With Our Team
The architecture behind AI Dev Planner represents the quality we deliver for our engineering clients: resilient full-stack systems, multi-tenant databases with RLS, and safe AI workflows.