All Templates
Day 4 of 77-Day AI Build Challenge

Architecture Document Template

System architecture template for SaaS products. The same depth the AI generates — system diagrams, full data models, API maps, file trees, and deployment guides.

Download .md
1

System Overview

2-3 sentences describing the system, its purpose, and its major components.

Tech Stack:

  • Frontend: (e.g., Next.js 14 App Router + React + TypeScript)
  • Backend: (e.g., Convex serverless functions / Express / FastAPI)
  • Database: (e.g., Convex / PostgreSQL / MongoDB)
  • Auth: (e.g., Clerk / NextAuth / Supabase Auth)
  • Payments: (e.g., Stripe Checkout + Webhooks)
  • AI: (e.g., OpenRouter → Claude Sonnet 4.5)
  • Email: (e.g., Resend / SendGrid)
  • Hosting: (e.g., Vercel + Convex Cloud)
  • Monitoring: (e.g., Sentry / LogRocket)

System Diagram

Map every service and how they connect. Include external APIs, webhooks, and data flows.

┌──────────────────────────────────────────────────────────────┐
│                        Client (Browser)                       │
│  Next.js App Router — React + TypeScript + Tailwind           │
└──────────┬───────────────────┬───────────────────┬───────────┘
           │                   │                   │
           │ Auth              │ Data/API          │ Payments
           ▼                   ▼                   ▼
┌──────────────────┐ ┌──────────────────┐ ┌──────────────────┐
│   Auth Provider   │ │     Backend      │ │     Stripe       │
│   (e.g., Clerk)   │ │  (e.g., Convex)  │ │   Checkout +     │
│                    │ │                  │ │   Webhooks       │
│  - Sign up/in     │ │  - Queries       │ │                  │
│  - Session mgmt   │ │  - Mutations     │ │  - Subscriptions │
│  - Webhooks →     │ │  - Actions       │ │  - Webhooks →    │
└──────────────────┘ └────────┬─────────┘ └──────────────────┘
                              │
                    ┌─────────┼─────────┐
                    │         │         │
                    ▼         ▼         ▼
             ┌──────────┐ ┌───────┐ ┌──────────┐
             │ Database │ │  AI   │ │  Email   │
             │          │ │ (API) │ │ (Resend) │
             └──────────┘ └───────┘ └──────────┘

Modify this diagram to match your actual architecture. Add/remove services as needed.

2

Data Model

Define every table in your database. For each: name, all fields with types, indexes, and relationships.

users

FieldTypeDescriptionIndex?
_idIDAuto-generated primary keyPK
clerkIdstringExternal auth provider IDYes — by_clerkId
emailstringUser emailYes — by_email
namestringDisplay name
imageUrlstring (optional)Profile photo URL
planstring"free" or "pro"
stripeCustomerIdstring (optional)Stripe customer ID
stripeSubscriptionIdstring (optional)Active subscription ID
createdAtnumberUnix timestamp

projects

FieldTypeDescriptionIndex?
_idIDAuto-generated primary keyPK
userIdID (users)Owner referenceYes — by_userId
namestringProject name
descriptionstring (optional)Short description
stagestringCurrent stage: "discover" through "launch"
typestring"builder" or "cleaner"
githubUrlstring (optional)Imported repo URL (cleaner path)
createdAtnumberUnix timestamp

messages

FieldTypeDescriptionIndex?
_idIDAuto-generated primary keyPK
projectIdID (projects)Parent projectYes — by_project_stage
stageKeystringWhich stage this message belongs toYes — by_project_stage
rolestring"user", "assistant", or "system"
contentstringMessage text (markdown)
modelstring (optional)AI model used for this response
tokenCountnumber (optional)Tokens used
createdAtnumberUnix timestamp

documents

FieldTypeDescriptionIndex?
_idIDAuto-generated primary keyPK
projectIdID (projects)Parent projectYes — by_project_type
typestring"prd", "architecture", "claude-md", etc.Yes — by_project_type
titlestringDocument title
contentstringFull markdown content
versionnumberVersion number
generatedBystring (optional)Which AI model generated this
createdAtnumberUnix timestamp
updatedAtnumberUnix timestamp

Add more tables as needed. Every feature in your PRD should map to at least one table.

3

API / Server Functions

List every API route or server function. Group by domain.

Auth Functions

FunctionTypeInputOutputAuth Required?
getUserquerynoneUser or nullYes
createUsermutationclerkId, email, nameUser IDInternal only
updateUsermutationfields to updatevoidYes
deleteUsermutationnonevoidYes

Project Functions

FunctionTypeInputOutputAuth Required?
getByUserquerynoneProject[]Yes
getByIdqueryprojectIdProject or nullYes + ownership
createmutationname, description, typeProject IDYes
updatemutationprojectId, fieldsvoidYes + ownership
deletemutationprojectIdvoidYes + ownership

Message Functions

FunctionTypeInputOutputAuth Required?
getByStagequeryprojectId, stageKeyMessage[]Yes + ownership
sendmutationprojectId, stageKey, content, roleMessage IDInternal only

AI Functions

FunctionTypeInputOutputAuth Required?
chatactionprojectId, stageKey, messages, modelAI response textYes + ownership
generateDocumentactionprojectId, type, contextDocument contentYes + ownership
summarizeContextactionprojectId, stageKeySummary textInternal only

Payment Functions

FunctionTypeInputOutputAuth Required?
createCheckoutactionpriceIdCheckout URLYes
handleWebhookhttpActionStripe event200 OKWebhook signature
getSubscriptionquerynoneSubscription statusYes

Add functions for every feature. If a PRD feature doesn't have corresponding functions, something is missing.

4

File Structure

Map your entire file tree. Every file should have a one-line description.

project/
├── app/
│   ├── (marketing)/
│   │   ├── page.tsx                    # Landing page with hero + features
│   │   ├── pricing/page.tsx            # Pricing page with Stripe checkout
│   │   ├── templates/
│   │   │   ├── page.tsx                # Template gallery grid
│   │   │   └── [slug]/page.tsx         # Individual template with copy/download
│   │   └── layout.tsx                  # Marketing layout (no sidebar)
│   ├── (app)/
│   │   ├── dashboard/page.tsx          # Project list + create new
│   │   ├── project/
│   │   │   └── [projectId]/
│   │   │       ├── page.tsx            # Project overview + stage navigation
│   │   │       ├── [stageKey]/page.tsx  # Stage conversation interface
│   │   │       └── documents/page.tsx   # Generated documents viewer
│   │   ├── settings/page.tsx           # Account + billing settings
│   │   └── layout.tsx                  # App layout (sidebar + header)
│   ├── (auth)/
│   │   ├── sign-in/[[...sign-in]]/page.tsx
│   │   └── sign-up/[[...sign-up]]/page.tsx
│   ├── api/
│   │   ├── webhooks/
│   │   │   ├── clerk/route.ts          # Clerk user sync webhook
│   │   │   └── stripe/route.ts         # Stripe subscription webhook
│   │   └── [...catch-all]/route.ts     # 404 for unknown API routes
│   ├── layout.tsx                      # Root layout (providers, fonts)
│   └── globals.css                     # Tailwind base + custom tokens
├── components/
│   ├── ui/                             # shadcn/ui components (button, input, etc.)
│   ├── shared/
│   │   ├── model-picker.tsx            # AI model selector dropdown
│   │   ├── chat-panel.tsx              # Reusable chat interface
│   │   ├── document-viewer.tsx         # Markdown document renderer
│   │   └── stage-nav.tsx               # Stage progression sidebar
│   ├── marketing/
│   │   ├── hero.tsx                    # Landing page hero section
│   │   ├── features.tsx                # Feature showcase grid
│   │   └── email-capture-form.tsx      # Newsletter/waitlist form
│   └── app/
│       ├── project-card.tsx            # Dashboard project card
│       ├── stage-chat.tsx              # Stage-specific chat wrapper
│       └── document-export.tsx         # Export docs as zip
├── convex/
│   ├── schema.ts                       # Database schema (all tables + indexes)
│   ├── users.ts                        # User queries + mutations
│   ├── projects.ts                     # Project CRUD
│   ├── messages.ts                     # Message storage + retrieval
│   ├── documents.ts                    # Document generation + storage
│   ├── ai.ts                           # OpenRouter API calls (actions only)
│   ├── stripe.ts                       # Payment functions
│   └── _generated/                     # Auto-generated types (don't edit)
├── lib/
│   ├── utils.ts                        # cn() helper + shared utilities
│   ├── models.ts                       # AI model definitions + pricing
│   ├── stages.ts                       # Stage definitions + system prompts
│   └── templates.ts                    # Template content for /templates pages
├── public/                             # Static assets (favicon, OG images)
├── .env.local                          # Local environment variables (git-ignored)
├── convex.json                         # Convex project config
├── next.config.js                      # Next.js configuration
├── tailwind.config.ts                  # Tailwind + custom theme
├── tsconfig.json                       # TypeScript strict config
└── package.json                        # Dependencies + scripts

Modify this tree to match your actual structure. Every file should be listed.

5

Auth Flow

How does authentication work from signup to authenticated request?

Signup Flow

  • User clicks "Sign Up" → Clerk hosted UI or embedded component
  • User enters email/password or OAuth (Google, GitHub)
  • Clerk creates user, issues session token
  • Clerk webhook fires user.created → hits /api/webhooks/clerk
  • Webhook handler calls createUser mutation → stores user in database with clerkId
  • User redirected to /dashboard with active session

Authentication on Every Request

  • Client-side: Clerk's useAuth() hook provides session
  • Convex functions: ctx.auth.getUserIdentity() returns identity or null
  • Every query/mutation validates: identity exists AND user owns the resource
  • Unauthenticated requests throw → client redirects to sign-in

Session Management

  • Sessions managed by Clerk (JWT-based)
  • Token refresh handled automatically by Clerk SDK
  • Logout clears session and redirects to landing page
6

AI Integration

If your product uses AI, document the full integration.

Provider Setup

  • Gateway: (e.g., OpenRouter — single API for multiple models)
  • API Key Storage: (e.g., Convex environment variable, never exposed to client)
  • Call Pattern: (Client → Convex action → OpenRouter API → response stored via mutation)

Models Used

ModelUse CaseCost (input/output per M tokens)
Primary conversations$ / $
Summarization$ / $
Document generation$ / $

Context Management

  • Max context window: ___ tokens
  • Strategy: (Recent N messages verbatim + summary of older messages)
  • Summarization trigger: (Every N messages, or when context exceeds X tokens)
  • Summary storage: (Field on the stage/conversation record)

Prompt Architecture

  • System prompt: (Static template with dynamic variables: stage, project context, user preferences)
  • User context injected: (PRD summary, architecture summary, previous stage outputs)
  • Output format: (Markdown for documents, plain text for chat, structured JSON for data)

Rate Limiting

  • Per user: ___ requests per minute
  • Per project: ___ requests per hour
  • Enforcement: (Tracked in database, checked in action before API call)

Cost Controls

  • Max tokens per request: ___
  • Monthly budget alert at: $___
  • Free tier limit: ___ messages per project
7

Security

For each area, describe your specific approach. Don't just check boxes — explain how it works.

Authentication & Authorization

  • Every Convex query and mutation calls ctx.auth.getUserIdentity()
  • After loading any resource, verify resource.userId === currentUser._id
  • No public queries expose other users' data
  • Admin functions (if any) check a specific role field

Data Validation

  • All mutation arguments validated with Convex v validators (types, ranges, enums)
  • String inputs sanitized before storage (trim, length limits)
  • File uploads validated for type and size (max ___ MB)
  • No raw user input passed into system prompts without sanitization template

Rate Limiting

  • AI actions: max ___ requests per minute per user
  • Auth endpoints: max ___ attempts per minute per IP
  • Webhook endpoints: signature verification required
  • Abuse detection: (How you detect and handle abuse)

Secrets Management

  • All API keys stored as environment variables (never in code)
  • Convex env vars set via npx convex env set
  • .env.local git-ignored, .env.example committed (without values)
  • Stripe webhook secret verified on every webhook call
  • Clerk webhook secret verified via svix library

Data Privacy

  • User data deletion: handled on user.deleted webhook (soft delete or hard delete?)
  • Data export: (Do users have a way to export their data?)
  • Third-party data sharing: (What data goes to OpenRouter, Stripe, etc.?)
8

Deployment

Step-by-step deployment process for your specific stack.

Prerequisites

  • Node.js ___ or higher
  • npm / pnpm / yarn
  • Accounts: [list every service account needed]

Environment Variables

List every required environment variable and where to get it:

# Auth (from [provider] dashboard → API Keys)
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=
CLERK_SECRET_KEY=

# Database (from [provider] dashboard → Settings)
NEXT_PUBLIC_CONVEX_URL=

# Payments (from Stripe dashboard → Developers → API Keys)
STRIPE_SECRET_KEY=
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=
STRIPE_WEBHOOK_SECRET=

# AI (from OpenRouter dashboard → API Keys)
OPENROUTER_API_KEY=

# App
NEXT_PUBLIC_APP_URL=

Deployment Steps

  • Database: Deploy backend functions — npx convex deploy
  • Frontend: Push to main branch → auto-deploys via Vercel (or: vercel --prod)
  • Environment: Set all env vars in Vercel dashboard + Convex dashboard
  • Webhooks: Configure webhook URLs in Stripe + Clerk dashboards
  • Domain: Point DNS to Vercel, wait for SSL
  • Verify: Test signup → checkout → core feature → logout flow

Post-Deployment Checks

  • Can sign up and sign in on production domain
  • Stripe checkout works with live card
  • Webhooks are receiving and processing events
  • AI features return responses
  • Error monitoring is capturing events
  • All pages load without console errors

Want the AI to generate this for your project? Try Build a Startup →

Skip the manual work

Want the AI to fill this out for you?

Build a Startup walks you through every step with a conversational AI that asks the right questions and pushes back on bad decisions.

Try Build a Startup — Free