Skip to content
GrowthVector.io

Architecture

Database & Backend

Why Vibe-Coded Apps Break at Scale

GitClear's 2025 report found duplicated code increased 8x since AI adoption surged. Google's DORA report: a 25% increase in AI usage correlates with a 7.2% decrease in delivery stability. AI generates code that works in isolation but creates architectural debt that compounds fast.

Database Options

Pick a backend that matches your read/write profile and scaling needs.

Supabase (PostgreSQL)

The clear winner for vibe coders. Auth + DB + Storage + Realtime. Requires RLS knowledge.

RecommendedFree: 500MB + 50K MAU

SQLite (Local)

Perfect for read-heavy apps with <100k views/day. Zero config. No connection limits.

# Production tuning (add on startup)

PRAGMA journal_mode=WAL;

PRAGMA busy_timeout=5000;

PRAGMA synchronous=NORMAL;

Neon (Serverless Postgres)

Serverless PostgreSQL. Scales to zero when idle. Branching for preview deployments.

Free: 0.5GBLaunch: usage-based

Firebase / Firestore Trade-offs

Good: Real-time sync, generous free tier (50K reads/day, 20K writes/day), easy auth integration.

Bad: NoSQL document model makes complex queries difficult. Pricing is per-read (one page load with 3 widgets = 4 reads). Data modeling mistakes are expensive to fix because there are no migrations.

Bottom Line: Good for real-time features (chat, notifications). Don't use as your primary database if you need relational queries.

N+1 Query Problem

AI often writes code that fetches a list, then queries the DB for each item in a loop. Result: 1 user = 100 queries. 100 users = 10,000 queries. App crashes.

// Bad: One query per user

const users = await db.user.findMany();

for (const user of users) {

  user.posts = await db.post.findMany({

    where: { authorId: user.id }

  });

}

// Good: One query total

const users = await db.user.findMany({

  include: { posts: true }

});

Missing Database Indexes

Supabase only auto-creates primary key indexes. Foreign key columns, timestamps used for sorting, and columns used in WHERE clauses all need manual indexes.

// Add to your prompt after schema design:

"Review all tables. Add indexes on:

- Every foreign key column

- Every column used in WHERE clauses

- created_at if used for sorting"

Connection Pooling (Serverless)

Each serverless function (API route) opens a new database connection. At 50+ concurrent users, you hit the PostgreSQL connection limit (~100 by default) and the database rejects all new connections.

# Supabase connection string for serverless

DATABASE_URL="postgresql://...

  :6543/postgres?pgbouncer=true"

# Port 6543 = pooled connection

# Port 5432 = direct (use for migrations only)

Safe Database Migrations

Schema changes can take your app down. Follow this safe migration pattern to avoid downtime.

// Step 1: Add column WITH default (no downtime)

ALTER TABLE users ADD COLUMN plan TEXT DEFAULT 'free';

// Step 2: Backfill existing rows

UPDATE users SET plan = 'pro' WHERE stripe_id IS NOT NULL;

// Step 3: Only THEN make it non-nullable

ALTER TABLE users ALTER COLUMN plan SET NOT NULL;

// Rollback if something breaks:

ALTER TABLE users DROP COLUMN plan;

Never Rename Columns in Production

Instead, add a new column, copy data, update code to use the new column, then drop the old one. Renaming breaks all queries instantly.

YAGNI: You Aren't Gonna Need It

Building Now But Shouldn't

  • Multi-tenancy (when you have 5 customers)
  • Team features (when all users are solo)
  • Advanced permissions (when you only need admin/user)
  • Caching layer (when you have 100 users)
  • Kubernetes (when serverless works fine)

Build When You Actually Need It

  • Wait until the pain is real
  • Solve the specific problem you have
  • Not the problem you imagine at 100x scale
  • Every premature feature is code you must maintain
  • Ship the MVP, iterate from real user feedback

Backup Strategies

You will lose data eventually. The question is whether you can recover it.

Supabase

Daily backups on Pro ($25/mo). Point-in-time recovery on Team ($599/mo). Free tier: no backups.

SQLite + Litestream

Continuous streaming backup to S3/GCS. Near-zero RPO. Cost: ~$1/mo for S3 storage.

Manual Export

Schedule pg_dump via cron job to cloud storage. Low-tech but reliable.

Test Your Restores Monthly

A backup you haven't tested restoring isn't a backup. Schedule a monthly "restore drill" where you actually restore from backup to a test environment. Many teams discover their backups are corrupted or incomplete only when they need them.

Frontend Traps

The "100 useEffect" Trap

AI overuses useEffect for derived state. This causes "Boolean Soup" and impossible states.

// Bad: useEffect for derived state

useEffect(() => {

  setFullName(first + ' ' + last);

}, [first, last]);

// Good: Calculate during render

const fullName = `${first} ${last}`;

// No state, no effect, no re-render

Fix: Use React Query / TanStack Query

Replace useEffect + useState data fetching with @tanstack/react-query. It handles loading, error, and caching states automatically. One import eliminates entire categories of bugs.

Missing UI States

AI only generates the "Happy Path".

Loading

Skeleton screens, spinners

Error

Retry buttons, error messages

Empty

"No items yet" illustrations

Offline

Reconnection banners

AI also misses: concurrent editing conflicts, negative quantities in e-commerce, max character limits, and what happens when 2 users edit the same record simultaneously.

Bundle Size Bloat

AI imports entire libraries when you need one function. import _ from "lodash" adds 70KB+ to your bundle when you only need debounce.

// Bad: 70KB+ import

import _ from "lodash";

_.debounce(fn, 300);

// Good: 1KB import

import debounce from "lodash/debounce";

debounce(fn, 300);

Add "Always use named imports. Never import the full library." to your project rules.

Accessibility Failures

Three failures that dominate the WebAIM Million analysis of home pages every year, and that AI-generated UI reproduces by default.

Missing Alt Text

AI generates <img> tags without meaningful alt attributes. Screen readers can't describe images.

No Keyboard Navigation

Custom components lack focus indicators and keyboard event handlers. Users who can't use a mouse are locked out.

Color-Only Indicators

Red for error, green for success with no text labels. Colorblind users can't distinguish states.

Scaling & Monoliths

Start with a Monolith

Don't use Microservices. Don't use Kubernetes. Keep everything in one Next.js app until real scale forces the issue. Groove's founder Alex Turnbull has written candidly that chasing a premature product rebuild cost the company roughly a year with little to show for it. Microservices add network latency, distributed bugs, and immense complexity you don't need early.

Scaling Thresholds

1-100 Users
Everything works.
$20-50/mo server cost
100-1,000 Users
N+1 queries cause lag.
Add indexes, fix queries
1,000-10,000 Users
DB competes for CPU.
Add caching, connection pooling
10,000+ Users
Need auto-scaling.
Read replicas, CDN, background jobs

Choose Boring Technology

Dan McKinley (Etsy): Every company gets approximately 3 "innovation tokens" to spend on new, unproven technology.

AI models are trained on millions of examples of popular, stable frameworks. When you use standard tools, AI produces better, more reliable code. When you use cutting-edge or obscure tools, AI hallucinates APIs and configurations.

Boring (Good)

  • PostgreSQL, SQLite
  • Next.js, Express
  • Tailwind, shadcn/ui
  • Stripe, Resend

Shiny (Risky)

  • GraphQL (when REST suffices)
  • Edge-first architectures
  • Custom auth implementations
  • New ORMs with <1 year history

Project Organization

AI-Friendly Project Structure

A well-organized project helps AI tools produce better, more consistent code. AI performs best when it can see clear patterns.

// Next.js App Router (recommended)

src/

  app/

    (auth)/        # Auth-protected routes

    (marketing)/   # Public pages

    api/           # API routes

    layout.tsx     # Root layout

  components/

    ui/            # shadcn/ui components

    forms/         # Form components

    layout/        # Layout components

  lib/

    db.ts          # Database client

    auth.ts        # Auth helpers

    stripe.ts      # Payment helpers

    utils.ts       # Shared utilities

  types/           # TypeScript types

tests/             # Test files

context/           # Project docs for AI

Keep a context/ directory with markdown files describing architecture decisions and business logic. Tell your AI: "Read context from all files in the context/ folder. Whenever you learn something new about the project, save it there."

README That Saves You Hours

A solid README helps AI tools understand your project instantly, and helps developers (including future you) get started fast.

# Project Name

## Quick Start

git clone ... && npm install && cp .env.example .env.local

npm run dev

## Environment Variables

DATABASE_URL=        # Supabase connection string

STRIPE_SECRET_KEY=  # From Stripe dashboard

RESEND_API_KEY=     # From Resend dashboard

## Tech Stack

Next.js 14 | Supabase | Stripe | Resend | Tailwind

## Testing

npm test             # Run unit tests

npm run test:e2e     # Run Playwright tests

AI Code Quality Anti-Patterns

Recurring anti-patterns in AI-generated codebases, echoed in Evil Martians' engineering write-ups on cleaning up vibe-coded projects.

No Domain Model

Business logic scattered across React components instead of centralized in a service layer.

"God" Components

Single files packing logic, API calls, state management, and UI rendering. 500+ line components.

No Error Handling

Happy path only. No try/catch, no error boundaries, no user-facing error messages.

Inconsistent Patterns

Same problem solved three different ways across the codebase. Data fetching done differently in every component.

Zero Documentation

No comments, no README, no type definitions. Future developers (or future you) can't understand the code.

Duplicated Logic

Same calculation repeated in multiple files. AI generates fresh implementations each time instead of reusing.

Clone and Learn: Well-Built Open Source Apps

Study how professional developers structure production applications. Clone these repos and explore their patterns.

Cal.com

Scheduling platform. Excellent example of a monorepo with Next.js, Prisma, and Stripe. Clean API routes and auth patterns.

Plane

Project management tool. Great example of complex state management, real-time updates, and role-based access control.

Formbricks

Survey platform. Clean Next.js architecture with good testing patterns and Stripe integration.

Twenty

Open-source CRM. Production-grade TypeScript, database design, and API architecture. Complex but well-organized.

Edge Cases Checklist

Ask these 7 questions for every feature you build. AI misses most of these unless you explicitly prompt for them.

What happens when the list is empty?
What if a value is null or undefined?
What if the user is not logged in?
What if two users edit the same record?
What if the network fails mid-request?
What if the user double-submits the form?
What if the input is 10x larger than expected?

Recommended Stacks

Tech Stacks by Use Case

Real monthly costs for common project types. Prices as of early 2026.

Use CaseStackMonthly Cost
Starter / Free TierNext.js + Supabase Free + Vercel Free + Cloudflare DNS$0/mo
Production SaaSNext.js + Supabase Pro + Vercel Pro + Stripe + Resend~$70-$100/mo
Mobile AppReact Native (Expo) + Supabase + EAS Build~$50-$80/mo
Quick PrototypeLovable/Bolt + Supabase Free$20-$50/mo (credits)
Chrome ExtensionVite + Chrome APIs + Supabase Free$0/mo
Landing PageNext.js or Astro + Vercel Free$0-$15/year (domain only)
E-CommerceNext.js + Stripe or Lemon Squeezy + Supabase~$50-$80/mo
Why Stack Popularity Matters for AI

AI models produce the best code for widely-adopted stacks. The more popular your tech stack, the fewer hallucinated APIs and the better autocomplete suggestions you get. Stick with boring, well-documented tools.

Database Hosting Comparison

Pricing and features for the most relevant database providers. Data as of early 2026.

ProviderFree TierPaid StartingBest ForKey Feature
Supabase500MB, 50K MAU$25/mo (8GB)Most vibe codersAuth + DB + Storage + Realtime
Neon0.5GB, scale-to-zeroUsage-based (Launch)Serverless appsScale-to-zero, branching
Turso5GB, 500M reads$4.99/moEdge / read-heavySQLite at the edge, sub-ms reads
MongoDB Atlas512MB (M0)~$8/mo (Flex)Document dataFlexible schema, good for prototypes
PlanetScaleNo free tier (removed Apr 2024)$5/mo (PS-5 Postgres)MySQL / Postgres appsBranching, no free tier
Recommendation

For most vibe-coded apps, start with Supabase. It bundles auth, database, storage, and real-time subscriptions into one platform. Move to Neon if you need serverless scaling (pay only when active). Move to Turso if you need edge performance with sub-millisecond reads.

Payment Processors: When to Choose Each

This is an architectural decision guide, not a full feature comparison. Focus: which processor fits your situation.

ProcessorFeeHandles Tax?Best For
Stripe2.9% + $0.30No (you handle)Most apps, best API docs
Lemon Squeezy5% + $0.50Yes (MoR)Solo devs selling globally
Paddle5% + $0.50Yes (MoR)B2B SaaS, enterprise
Polar5% + $0.50Yes (MoR)Open source, developers
Key Decision: Merchant of Record vs. Self-Managed

If you sell to international consumers and don't want to deal with VAT or sales tax, use a Merchant of Record (Lemon Squeezy or Paddle). The fees are higher but you get zero tax compliance work. Start with MoR for simplicity. Consider migrating to Stripe when revenue exceeds $50K/month, where the fee difference exceeds $1,000/month and justifies handling taxes yourself.

Lemon Squeezy: Evaluate Carefully

Lemon Squeezy was acquired by Stripe in July 2024. Users report errors and delayed payouts since the acquisition. Test thoroughly before committing, and have a migration plan ready.

Authentication Options at a Glance

Quick architectural decision guide. The full provider comparison with security details is in the Security tab.

ProviderFree TierPaidBest For
Supabase Auth50K MAUIncluded in Pro ($25/mo)Already using Supabase
Clerk50K MRU$25/mo + $0.02/MRUBest pre-built UI components
Auth.js (NextAuth)Unlimited (self-hosted)FreeFull control, open source
Firebase Auth50K MAU$0.0055/MAU after 50KGoogle ecosystem
Match Auth to Your Database

Pick the auth provider that matches your database choice. If using Supabase, use Supabase Auth. If using a different database with Next.js, Clerk offers the smoothest developer experience with pre-built sign-in, sign-up, and user profile components that save you from building auth UI by hand.

Detailed Stack Recommendations by App Type

Chrome Extension

Modern React-based Chrome extension development with Plasmo, the fastest path from idea to the Chrome Web Store.

# Recommended Stack

Framework:        Plasmo (React-based, abstracts Chrome extension boilerplate)

Styling:          Tailwind CSS

Backend:          Supabase or Firebase (if needed)

Auth:             Chrome Identity API + Firebase (if needed)

Storage:          Chrome Storage API + sync

Build:            Plasmo build

Deploy:           Chrome Web Store

Cost:             $5 one-time (developer account) + backend costs

Time to Build:    3-7 days

AI Coding Tool:   Cursor with Plasmo docs in context

Plasmo abstracts away Chrome extension boilerplate and gives you modern React patterns. Use Cursor with Plasmo documentation loaded via @docs for best results. You get hot-reload during development, TypeScript support out of the box, and a single command to package your extension for the Chrome Web Store.

Internal Tool / Admin Dashboard

Two paths depending on whether you need code-level control or just need something working today.

No-Code Approach

# No-Code Stack

Platform:      Retool or Airplane

Cost:          $10-$50/user/month

Time:          Hours to days

When to use: Non-developer admins who need to connect to existing databases, run queries, and manage records without writing code. Retool connects directly to Postgres, MySQL, MongoDB, and REST APIs.

Code Approach

# Code Stack

Framework:     Refine (React admin framework)

               OR Next.js + shadcn/ui

Database:      Direct connection to production

               DB (read-only user)

Auth:          SSO if enterprise, otherwise Clerk

Hosting:       Vercel

Cost:          $20-$50/month

Time:          3-5 days

AI Tool:       Cursor, generate CRUD with

               Refine scaffolding

When to use: You need custom business logic, complex workflows, or full design control. Refine gives you pre-built CRUD operations, data tables, and form components that AI tools can scaffold quickly.

Always Use a Read-Only Database User

When connecting an admin dashboard to your production database, create a dedicated read-only user. Never give admin tools write access to production using your main database credentials. If a write is needed, route it through a validated API endpoint with proper authorization checks.

API / Backend Service (No Frontend)

When you only need an API layer, skip the frontend framework entirely and build a lightweight backend service.

# Recommended Stack

Language:         Python (FastAPI) or TypeScript (Express/Hono)

Database:         Supabase or Neon Postgres

API Docs:         Auto-generated (FastAPI) or Swagger

Hosting:          Railway or Render

Auth:             API keys or JWT

Monitoring:       Sentry

Testing:          Pytest or Vitest

Cost:             $7-$25/month

Time to Build:    About 1 week

AI Coding Tool:   Cursor or Claude Code

FastAPI is the top choice for AI-assisted backend development. It auto-generates interactive API documentation, supports Python type hints that AI models understand well, includes built-in async support, and AI models are heavily trained on FastAPI patterns. If you prefer TypeScript, Hono is a lightweight alternative that runs on Cloudflare Workers, AWS Lambda, and Node.js with near-zero cold starts.

FastAPI Strengths

  • Auto-generated OpenAPI docs at /docs
  • Type-safe request/response with Pydantic
  • Native async/await for high concurrency
  • Massive training data = better AI completions

Hono/Express Strengths

  • Same language as your frontend (TypeScript)
  • Share types between frontend and backend
  • Hono: runs on edge, sub-10ms cold starts
  • Express: the most documented Node.js framework

E-Commerce

The one app type where "build it yourself" is almost always the wrong answer.

Do NOT Vibe Code E-Commerce From Scratch

Payment processing, inventory management, shipping calculations, tax compliance, and fraud prevention are too complex for AI-generated code. Each of these domains has years of edge cases baked into battle-tested platforms. Use those platforms instead of reinventing them.

Option 1: Shopify

Use Hydrogen (React-based storefront) if you need custom UI, or Liquid templates if you want simplicity. Shopify handles payments, inventory, shipping, taxes, and fraud out of the box.

Recommended$39/mo+
Option 2: Medusa.js

Open-source Shopify alternative. Self-hosted, fully customizable, headless architecture. Good if you want Shopify-level features without vendor lock-in or monthly platform fees.

Open SourceSelf-Hosted
Option 3: Snipcart

Drop a shopping cart onto any existing website. No backend required. Snipcart handles checkout, payments, and order management. Perfect for adding e-commerce to a content site.

2% transaction feeNo backend needed
If You Insist on Building Custom E-Commerce

# Custom E-Commerce Stack (not recommended)

Framework:       Next.js 14 (App Router)

Payments:        Stripe (with proper security audit)

CMS:             Sanity CMS (product catalog)

Shipping:        ShipStation API

Taxes:           Stripe Tax

Cost:            $100-$200/month

Time to Build:   4-8 weeks + mandatory security audit

Hire a Developer for Payment Logic

If you go the custom route, strongly consider hiring a developer who specializes in payment integrations. One bug in checkout flow, tax calculation, or refund handling can cost you more in chargebacks and compliance issues than the entire cost of hiring a professional. AI-generated payment code should never go to production without a human security audit.