Project Documentation Request - Generic Template
Contextβ
[Describe your project in 2-3 paragraphs: what problem it solves, who it's for, and the high-level vision]
Deliverables Requestedβ
Generate two complete documents:
- PRD (Product Requirements Document)
- Architecture Document
PART 1: PRD (Product Requirements Document)
1. Executive Summaryβ
- Vision statement (1 paragraph)
- Problem being solved
- Target market and users
- Unique value proposition
2. User Personas (2-4 personas)β
For each persona:
- Name, role, demographics
- Technical proficiency level
- Goals and motivations
- Pain points and frustrations
- How our solution helps them
- Devices and contexts of use
3. Scope Definitionβ
3.1 In Scope (MVP)β
- Core features required for launch
- Minimum viable functionality per module
3.2 In Scope (v1)β
- Features for first major release post-MVP
3.3 Out of Scopeβ
- Explicitly excluded features with reasoning
3.4 Future Considerations (v2+)β
- Roadmap items for future releases
4. Functional Requirementsβ
Organized by module/area:
4.1 Authentication & Authorizationβ
- Sign up methods (email, OAuth providers)
- Sign in / Sign out
- Password reset flow
- Session management
- Role-based access levels
4.2 Core Featuresβ
For each feature:
- Description
- User story
- Acceptance criteria
- Priority (P0/P1/P2)
- Dependencies
4.3 Admin / Back-office Featuresβ
- User management
- Content management
- Analytics dashboard
- Configuration settings
4.4 Integrationsβ
- Third-party services required
- Data sync requirements
- Webhook needs
4.5 Automation Workflowsβ
- Triggered automations (events)
- Scheduled automations (cron)
- User-initiated automations
- Integration automations
5. Non-Functional Requirementsβ
5.1 Performanceβ
- Page load time targets (initial, subsequent)
- Time to interactive
- API response time targets
- Concurrent user capacity
- Database query performance
5.2 Availabilityβ
- Uptime target (99.9%, 99.99%)
- Maintenance window policy
- Disaster recovery requirements
- Backup frequency
5.3 Scalabilityβ
- Expected growth trajectory
- Peak load handling
- Geographic distribution needs
6. Security Requirementsβ
6.1 Complianceβ
- Regulatory standards (GDPR, SOC2, HIPAA, PCI-DSS)
- Data residency requirements
- Audit requirements
6.2 Authentication & Accessβ
- Password policy (length, complexity, rotation)
- MFA requirements
- Session timeout policy
- Failed login handling
6.3 Data Protectionβ
- Data classification levels
- Encryption requirements
- PII handling rules
- Right to deletion (GDPR Article 17)
- Data retention policy
6.4 Audit & Loggingβ
- Actions requiring audit logs
- Log retention period
- Access to audit logs
7. SEO Requirementsβ
7.1 Search Strategyβ
- Target keywords and search intent
- Competitor benchmarks
- Content strategy alignment
7.2 Technical SEOβ
- URL structure requirements
- Meta tags (title, description, OG, Twitter cards)
- Structured data / Schema.org types needed
- Canonical URL strategy
- Hreflang for multi-language
- Sitemap requirements (static, dynamic)
- Robots.txt rules
7.3 Performance SEOβ
- Core Web Vitals targets:
- LCP (Largest Contentful Paint): < 2.5s
- FID (First Input Delay): < 100ms
- CLS (Cumulative Layout Shift): < 0.1
- Mobile-first indexing compliance
- Page speed targets
8. UX Requirementsβ
8.1 User Journeysβ
For each key flow, document:
- Entry points
- Steps to completion
- Success criteria
- Error handling
- Edge cases
Key journeys to document:
- First-time user onboarding
- Core task completion
- Error recovery
- Account management
8.2 Information Architectureβ
- Site map / navigation structure
- Content hierarchy
- Search functionality requirements
8.3 Accessibilityβ
- WCAG compliance level (2.1 AA or AAA)
- Screen reader support
- Keyboard navigation
- Color contrast requirements
- Focus management
- ARIA requirements
8.4 Internationalization (i18n)β
- Supported languages
- RTL language support
- Date/time/currency formatting
- Translation workflow
8.5 Interaction Patternsβ
- Loading states and feedback
- Empty states
- Error messages (tone, format)
- Success confirmations
- Undo capabilities
9. UI Requirementsβ
9.1 Brand & Visual Identityβ
- Brand guidelines reference
- Logo usage rules
- Brand voice and tone
9.2 Design Systemβ
- Typography scale
- Color system (primary, secondary, semantic)
- Spacing system
- Border radius, shadows
- Light/dark mode requirements
9.3 Component Requirementsβ
- Component library choice or custom
- Key components needed
- Responsive breakpoints
- Touch target sizes (mobile)
9.4 Motion & Animationβ
- Animation philosophy (subtle, expressive)
- Transition timing
- Loading animations
- Micro-interactions
10. Quality Requirementsβ
10.1 Test Coverage Targetsβ
| Test Type | Coverage Target |
|---|---|
| Unit tests | 80%+ |
| Integration tests | Critical paths |
| E2E tests | All user journeys |
| Visual regression | UI components |
| Accessibility | WCAG compliance |
| Performance | Core Web Vitals |
10.2 Browser & Device Supportβ
| Browser | Versions |
|---|---|
| Chrome | Last 2 |
| Firefox | Last 2 |
| Safari | Last 2 |
| Edge | Last 2 |
| Mobile Safari | iOS 14+ |
| Chrome Android | Last 2 |
10.3 Critical Test Scenariosβ
- List user flows requiring mandatory e2e coverage
- Regression scenarios
- Edge cases to cover
11. User Storiesβ
Format: "As a [persona], I want to [action] so that [benefit]"
For each story include:
- ID (US-001)
- Priority (P0/P1/P2)
- Persona
- Story
- Acceptance criteria
- Dependencies
- Notes
11.1 Authentication Storiesβ
[List stories]
11.2 Core Feature Storiesβ
[List stories]
11.3 Admin Storiesβ
[List stories]
11.4 Automation Storiesβ
[List stories]
12. Success Metricsβ
12.1 Business KPIsβ
| Metric | Target | Measurement Method | Timeline |
|---|---|---|---|
| [e.g., User signups] | [e.g., 1000/month] | [e.g., Analytics] | [e.g., 3 months] |
12.2 Product KPIsβ
| Metric | Target | Measurement Method |
|---|---|---|
| Task completion rate | >90% | Analytics |
| Time to complete core task | <2 min | Analytics |
| User satisfaction (NPS) | >50 | Surveys |
12.3 Technical KPIsβ
| Metric | Target |
|---|---|
| Uptime | 99.9% |
| Error rate | <0.1% |
| p95 latency | <500ms |
| Core Web Vitals | All green |
13. Risks & Mitigationsβ
| ID | Risk | Probability | Impact | Mitigation | Owner |
|---|---|---|---|---|---|
| R1 | [Description] | High/Med/Low | High/Med/Low | [Strategy] | [Role] |
14. Dependenciesβ
14.1 External Dependenciesβ
- Third-party services
- APIs
- Vendor contracts
14.2 Internal Dependenciesβ
- Other teams/projects
- Shared resources
- Approvals needed
15. Timeline & Milestonesβ
| Milestone | Target Date | Deliverables | Success Criteria |
|---|---|---|---|
| MVP | [Date] | [List] | [Criteria] |
| Beta | [Date] | [List] | [Criteria] |
| v1 Launch | [Date] | [List] | [Criteria] |
PART 2: Architecture Document
1. System Overviewβ
1.1 High-Level Architectureβ
[Provide mermaid diagram]
graph TB
subgraph Client
Web[Web App]
Mobile[Mobile Web]
end
subgraph Edge
CDN[CDN]
WAF[WAF]
end
subgraph Application
FE[Frontend - Next.js]
API[API Routes]
Auth[Auth Service]
end
subgraph Data
DB[(PostgreSQL)]
Cache[(Redis)]
Storage[Object Storage]
end
subgraph External
Email[Email Service]
Payment[Payment Provider]
Analytics[Analytics]
end
subgraph Automation
Workflows[n8n / Automation]
Queue[Job Queue]
end
Web --> CDN --> FE
FE --> API
API --> Auth
API --> DB
API --> Cache
API --> Workflows
1.2 Component Inventoryβ
| Component | Purpose | Technology |
|---|---|---|
| [Name] | [Purpose] | [Tech] |
1.3 Data Flow Overviewβ
[Describe how data flows through the system]
2. Technology Stackβ
For each decision, provide:
- Technology selected
- Alternatives considered
- Rationale
- Trade-offs accepted
2.1 Frontendβ
| Layer | Technology | Rationale |
|---|---|---|
| Framework | Next.js 15 | SSR, App Router, React Server Components |
| Styling | Tailwind CSS | Utility-first, design tokens |
| Components | shadcn/ui | Accessible, customizable |
| State | Zustand / React Query | Lightweight, server state |
| Forms | React Hook Form + Zod | Validation, performance |
2.2 Backendβ
| Layer | Technology | Rationale |
|---|---|---|
| Runtime | Node.js | Ecosystem, team expertise |
| API | Next.js API Routes | Colocation, serverless |
| Validation | Zod | Type-safe, runtime validation |
| ORM | Prisma / Drizzle | Type safety, migrations |
2.3 Databaseβ
| Type | Technology | Rationale |
|---|---|---|
| Primary | PostgreSQL (Supabase) | ACID, JSON support, managed |
| Cache | Redis (Upstash) | Session, rate limiting |
| Search | [if needed] | [rationale] |
2.4 Authenticationβ
| Aspect | Technology | Rationale |
|---|---|---|
| Provider | Supabase Auth / NextAuth | OAuth, JWT, session management |
| Session | JWT + HTTP-only cookies | Security, stateless |
2.5 Infrastructureβ
| Aspect | Technology | Rationale |
|---|---|---|
| Hosting | Vercel | Edge, preview deployments |
| CDN | Vercel Edge Network | Global, automatic |
| Storage | S3 / Supabase Storage | Scalable, cheap |
| DNS | Cloudflare | DDoS protection |
2.6 Automationβ
| Aspect | Technology | Rationale |
|---|---|---|
| Workflows | n8n (self-hosted) / Inngest | Visual, extensible |
| Scheduling | Vercel Cron / n8n | Serverless-friendly |
| Queues | Inngest / BullMQ | Retries, observability |
2.7 Monitoring & Observabilityβ
| Aspect | Technology | Rationale |
|---|---|---|
| Error Tracking | Sentry | Stack traces, context |
| Analytics | PostHog | Product analytics, self-host option |
| Logging | Axiom / Datadog | Structured, searchable |
| Uptime | Better Uptime | Alerting, status page |
2.8 CI/CDβ
| Aspect | Technology | Rationale |
|---|---|---|
| CI | GitHub Actions | Native, free for public |
| CD | Vercel | Automatic, preview |
| Code Quality | ESLint, Prettier, Husky | Consistency |
3. Component Architectureβ
3.1 Frontend Componentsβ
src/
βββ app/ # Next.js App Router
β βββ (auth)/ # Auth routes group
β βββ (dashboard)/ # Dashboard routes group
β βββ (marketing)/ # Public pages
β βββ api/ # API routes
β βββ layout.tsx # Root layout
βββ components/
β βββ ui/ # Base UI components (shadcn)
β βββ features/ # Feature-specific components
β βββ layouts/ # Layout components
β βββ providers/ # Context providers
βββ lib/
β βββ api/ # API client functions
β βββ hooks/ # Custom React hooks
β βββ utils/ # Utility functions
β βββ validations/ # Zod schemas
βββ types/ # TypeScript types
βββ styles/ # Global styles
3.2 API Structureβ
src/app/api/
βββ auth/
β βββ login/route.ts
β βββ logout/route.ts
β βββ register/route.ts
βββ users/
β βββ route.ts # GET (list), POST (create)
β βββ [id]/route.ts # GET, PATCH, DELETE
βββ [resource]/
β βββ ...
βββ webhooks/
βββ stripe/route.ts
βββ [provider]/route.ts
3.3 Component Specificationsβ
For each major component:
| Component | Responsibility | Inputs | Outputs | Dependencies |
|---|---|---|---|---|
| AuthProvider | Manage auth state | children | user context | Supabase |
| DataTable | Display paginated data | data, columns | selection, actions | React Query |
| [Component] | [Responsibility] | [Inputs] | [Outputs] | [Deps] |
4. Data Architectureβ
4.1 Entity-Relationship Diagramβ
erDiagram
User ||--o{ Account : has
User ||--o{ Session : has
User ||--o{ Order : places
User {
uuid id PK
string email UK
string name
enum role
timestamp created_at
timestamp updated_at
}
Account {
uuid id PK
uuid user_id FK
string provider
string provider_account_id
}
Session {
uuid id PK
uuid user_id FK
string token
timestamp expires_at
}
Order ||--|{ OrderItem : contains
Order {
uuid id PK
uuid user_id FK
enum status
decimal total
timestamp created_at
}
OrderItem {
uuid id PK
uuid order_id FK
uuid product_id FK
int quantity
decimal price
}
Product {
uuid id PK
string name
text description
decimal price
boolean active
}
4.2 Database Schemaβ
[Provide complete schema with types, constraints, indexes]
4.3 Data Validation Rulesβ
| Entity | Field | Validation |
|---|---|---|
| User | Valid email, unique | |
| User | password | Min 8 chars, complexity |
| Order | total | Positive decimal |
4.4 Migration Strategyβ
- Use Prisma/Drizzle migrations
- Version control all migrations
- Test migrations on staging before production
- Rollback procedures for each migration
5. API Designβ
5.1 API Conventionsβ
| Aspect | Convention |
|---|---|
| Format | REST with JSON |
| Versioning | URL prefix (/api/v1) or none for internal |
| Authentication | Bearer token in Authorization header |
| Pagination | Cursor-based (?cursor=xxx&limit=20) |
| Filtering | Query params (?status=active) |
| Sorting | ?sort=created_at&order=desc |
| Errors | RFC 7807 Problem Details |
5.2 Endpoint Inventoryβ
| Method | Endpoint | Purpose | Auth Required |
|---|---|---|---|
| POST | /api/auth/login | User login | No |
| POST | /api/auth/register | User registration | No |
| GET | /api/users/me | Get current user | Yes |
| GET | /api/[resource] | List resources | Yes |
| POST | /api/[resource] | Create resource | Yes |
| GET | /api/[resource]/[id] | Get resource | Yes |
| PATCH | /api/[resource]/[id] | Update resource | Yes |
| DELETE | /api/[resource]/[id] | Delete resource | Yes (Admin) |
5.3 Error Response Formatβ
{
"type": "https://api.example.com/errors/validation",
"title": "Validation Error",
"status": 400,
"detail": "The request body contains invalid fields",
"instance": "/api/users",
"errors": [
{
"field": "email",
"message": "Invalid email format"
}
]
}
5.4 Rate Limitingβ
| Endpoint Type | Limit | Window |
|---|---|---|
| Public (auth) | 10 requests | 1 minute |
| Authenticated | 100 requests | 1 minute |
| Admin | 500 requests | 1 minute |
| Webhooks | 1000 requests | 1 minute |
6. Security Architectureβ
6.1 Authentication Flowβ
sequenceDiagram
participant U as User
participant F as Frontend
participant A as API
participant D as Database
participant E as Email
U->>F: Enter credentials
F->>A: POST /auth/login
A->>D: Validate credentials
D-->>A: User data
A->>A: Generate JWT
A-->>F: Set HTTP-only cookie
F-->>U: Redirect to dashboard
6.2 Authorization Modelβ
| Role | Permissions |
|---|---|
| Guest | View public content |
| User | CRUD own resources |
| Admin | Full access |
| Super Admin | System configuration |
6.3 Security Measuresβ
| Threat | Mitigation |
|---|---|
| XSS | CSP headers, output encoding, React's built-in escaping |
| CSRF | SameSite cookies, CSRF tokens for mutations |
| SQL Injection | Parameterized queries (ORM), input validation |
| Auth attacks | Rate limiting, bcrypt, secure session handling |
| Data exposure | Field-level authorization, response filtering |
| Clickjacking | X-Frame-Options, CSP frame-ancestors |
6.4 Security Headersβ
const securityHeaders = {
'Content-Security-Policy': "default-src 'self'; ...",
'X-Frame-Options': 'DENY',
'X-Content-Type-Options': 'nosniff',
'Referrer-Policy': 'strict-origin-when-cross-origin',
'Permissions-Policy': 'camera=(), microphone=(), geolocation=()',
'Strict-Transport-Security': 'max-age=31536000; includeSubDomains'
};
6.5 Secret Managementβ
- Environment variables via Vercel/hosting provider
- No secrets in code or version control
- Rotation policy for API keys
- Separate secrets per environment
6.6 Dependency Securityβ
- Dependabot / Renovate for updates
- npm audit in CI pipeline
- Lock file integrity checks
- SBOM generation
7. SEO Architectureβ
7.1 Rendering Strategyβ
| Page Type | Rendering | Caching | Rationale |
|---|---|---|---|
| Marketing pages | SSG | CDN, revalidate daily | Static content, max performance |
| Blog posts | SSG + ISR | CDN, revalidate on publish | Content updates periodically |
| Dashboard | CSR | None | Private, dynamic |
| Product pages | SSR | CDN, stale-while-revalidate | SEO + fresh data |
7.2 Meta Tag Strategyβ
// Dynamic meta generation
export async function generateMetadata({ params }): Promise<Metadata> {
const page = await getPage(params.slug);
return {
title: page.seoTitle || page.title,
description: page.seoDescription,
openGraph: {
title: page.ogTitle,
description: page.ogDescription,
images: [page.ogImage],
},
twitter: {
card: 'summary_large_image',
},
};
}
7.3 Structured Dataβ
| Page Type | Schema Types |
|---|---|
| Homepage | Organization, WebSite |
| Product | Product, Offer, Review |
| Blog | Article, BreadcrumbList |
| FAQ | FAQPage |
7.4 Technical SEO Implementationβ
| Aspect | Implementation |
|---|---|
| Sitemap | Dynamic generation at /sitemap.xml |
| Robots.txt | Static at /robots.txt |
| Canonical URLs | Automatic via Next.js metadata |
| Image optimization | Next.js Image component, WebP/AVIF |
| Core Web Vitals | Lighthouse CI in pipeline |
8. Frontend Architectureβ
8.1 Design System Implementationβ
// tailwind.config.ts
const config = {
theme: {
extend: {
colors: {
primary: { /* scale */ },
secondary: { /* scale */ },
destructive: { /* scale */ },
// semantic tokens
},
fontFamily: {
sans: ['Inter', 'sans-serif'],
mono: ['JetBrains Mono', 'monospace'],
},
spacing: { /* custom scale */ },
borderRadius: {
DEFAULT: '0.5rem',
// ...
},
},
},
};
8.2 Theme Systemβ
// Light/dark mode with CSS variables
:root {
--background: 0 0% 100%;
--foreground: 222.2 84% 4.9%;
// ...
}
.dark {
--background: 222.2 84% 4.9%;
--foreground: 210 40% 98%;
// ...
}
8.3 Accessibility Implementationβ
| Requirement | Implementation |
|---|---|
| Keyboard navigation | Focus visible, skip links, focus trap in modals |
| Screen readers | Semantic HTML, ARIA labels, live regions |
| Color contrast | WCAG AA minimum (4.5:1 text, 3:1 UI) |
| Reduced motion | prefers-reduced-motion media query |
| Form accessibility | Labels, error messages, field descriptions |
8.4 Performance Optimizationβ
| Technique | Implementation |
|---|---|
| Code splitting | Next.js automatic + dynamic imports |
| Image optimization | next/image with blur placeholders |
| Font optimization | next/font with preload |
| Bundle analysis | @next/bundle-analyzer |
| Prefetching | Link prefetch, route prefetch |
9. Testing Architectureβ
9.1 Test Pyramidβ
/\
/ \ E2E Tests (Playwright)
/----\ - Critical user journeys
/ \ - 10-20 tests
/--------\
/ \ Integration Tests (Vitest + Testing Library)
/------------\ - API routes, component integration
/ \ - 50-100 tests
/----------------\
/ \ Unit Tests (Vitest)
- Utility functions, hooks, validation
- 200+ tests
9.2 Testing Stackβ
| Test Type | Tool | Location |
|---|---|---|
| Unit | Vitest | *.test.ts alongside source |
| Component | Vitest + Testing Library | *.test.tsx |
| Integration | Vitest + MSW | src/test/integration/ |
| E2E | Playwright | e2e/ |
| Visual | Chromatic / Percy | CI only |
| Accessibility | axe-core + Playwright | E2E suite |
| Performance | Lighthouse CI | CI only |
9.3 Test Configurationβ
// vitest.config.ts
export default defineConfig({
test: {
environment: 'jsdom',
globals: true,
setupFiles: ['./src/test/setup.ts'],
coverage: {
provider: 'v8',
reporter: ['text', 'html', 'lcov'],
threshold: {
global: { lines: 80, branches: 80, functions: 80 },
},
},
},
});
9.4 E2E Test Strategyβ
// e2e/user-journey.spec.ts
test.describe('User signup and onboarding', () => {
test('new user can sign up and complete onboarding', async ({ page }) => {
await page.goto('/signup');
await page.fill('[name="email"]', 'test@example.com');
await page.fill('[name="password"]', 'SecurePass123!');
await page.click('button[type="submit"]');
await expect(page).toHaveURL('/onboarding');
// ... complete onboarding steps
await expect(page).toHaveURL('/dashboard');
});
});
9.5 Test Data Managementβ
- Factory functions for test data
- Database seeding scripts
- Isolated test databases
- Cleanup between tests
9.6 CI Test Pipelineβ
# .github/workflows/test.yml
jobs:
test:
steps:
- Checkout
- Install dependencies
- Lint (ESLint, TypeScript)
- Unit & Integration tests (Vitest)
- Build
- E2E tests (Playwright)
- Coverage report
- Performance audit (Lighthouse)
10. Monitoring & Observabilityβ
10.1 Observability Stackβ
graph LR
App[Application] --> Sentry[Sentry - Errors]
App --> PostHog[PostHog - Analytics]
App --> Axiom[Axiom - Logs]
App --> Vercel[Vercel - Web Vitals]
Sentry --> Slack[Slack Alerts]
Axiom --> Slack
BetterUptime[Better Uptime] --> PagerDuty[PagerDuty]
10.2 Error Tracking (Sentry)β
// sentry.client.config.ts
Sentry.init({
dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,
tracesSampleRate: 0.1,
replaysSessionSampleRate: 0.1,
replaysOnErrorSampleRate: 1.0,
integrations: [
Sentry.replayIntegration(),
Sentry.browserTracingIntegration(),
],
});
10.3 Logging Strategyβ
// Structured logging format
const log = {
level: 'info',
message: 'User action completed',
timestamp: '2024-01-15T10:30:00Z',
context: {
userId: 'user_123',
action: 'order_created',
orderId: 'order_456',
duration_ms: 234,
},
request: {
method: 'POST',
path: '/api/orders',
ip: 'xxx.xxx.xxx.xxx',
},
};
10.4 Metrics Collectionβ
| Metric | Type | Purpose |
|---|---|---|
| Request duration | Histogram | API performance |
| Error count | Counter | Error rate |
| Active users | Gauge | Capacity planning |
| Queue depth | Gauge | Automation health |
| Cache hit ratio | Gauge | Cache effectiveness |
10.5 Alerting Strategyβ
| Alert | Condition | Severity | Channel | Action |
|---|---|---|---|---|
| High error rate | >1% errors in 5min | Warning | Slack | Investigate |
| Critical error rate | >5% errors in 5min | Critical | PagerDuty | Immediate |
| API latency | p99 >2s for 5min | Warning | Slack | Investigate |
| Downtime | No response 30s | Critical | PagerDuty | Immediate |
| Workflow failure | 3 consecutive failures | Warning | Slack | Check automation |
10.6 Dashboard Requirementsβ
| Dashboard | Metrics Displayed |
|---|---|
| Overview | Uptime, error rate, active users, response times |
| API Health | Endpoint latencies, error rates by route |
| User Activity | Signups, logins, feature usage |
| Automation | Workflow runs, success rate, duration |
| Infrastructure | CPU, memory, database connections |
10.7 Real User Monitoring (RUM)β
| Metric | Target | Alert Threshold |
|---|---|---|
| LCP | <2.5s | >4s |
| FID | <100ms | >300ms |
| CLS | <0.1 | >0.25 |
| TTFB | <600ms | >1.5s |
11. Automation Architectureβ
11.1 Automation Platformβ
| Aspect | Choice | Rationale |
|---|---|---|
| Platform | n8n (self-hosted) or Inngest | Visual workflows, code fallback |
| Hosting | Docker on Railway/Render | Cost-effective, easy deploy |
| Triggers | Webhooks, cron, events | Flexible activation |
11.2 Workflow Categoriesβ
| Category | Examples | Trigger |
|---|---|---|
| User lifecycle | Welcome email, onboarding nudges | Event |
| Notifications | Order updates, reminders | Event |
| Data sync | CRM updates, analytics export | Scheduled |
| Maintenance | Cleanup, reports | Scheduled |
| Integrations | Third-party sync | Webhook |
11.3 Workflow Design Patternsβ
graph LR
Trigger[Trigger] --> Validate[Validate Input]
Validate --> Process[Process]
Process --> Success{Success?}
Success -->|Yes| Complete[Complete]
Success -->|No| Retry[Retry Logic]
Retry --> DLQ[Dead Letter Queue]
11.4 Error Handlingβ
| Scenario | Strategy |
|---|---|
| Transient failure | Exponential backoff retry (3 attempts) |
| Persistent failure | Move to dead letter queue, alert |
| Partial failure | Transaction rollback, compensating action |
| Timeout | Cancel, log, alert |
11.5 Automation Monitoringβ
| Metric | Alert Condition |
|---|---|
| Workflow success rate | <95% in 1 hour |
| Execution duration | >2x expected |
| Queue depth | >100 pending |
| Dead letter queue | Any items |
12. Infrastructure & Deploymentβ
12.1 Environment Strategyβ
| Environment | Purpose | URL | Data |
|---|---|---|---|
| Local | Development | localhost:3000 | Seed data |
| Preview | PR review | pr-123.vercel.app | Seed data |
| Staging | Pre-production | staging.example.com | Anonymized prod |
| Production | Live | example.com | Real data |
12.2 Deployment Pipelineβ
graph LR
Push[Git Push] --> CI[CI Checks]
CI --> Preview[Preview Deploy]
Preview --> Review[Code Review]
Review --> Merge[Merge to main]
Merge --> Staging[Staging Deploy]
Staging --> Smoke[Smoke Tests]
Smoke --> Prod[Production Deploy]
Prod --> Monitor[Monitor]
12.3 Infrastructure as Codeβ
| Resource | Tool |
|---|---|
| Vercel config | vercel.json |
| Database | Supabase migrations |
| DNS | Terraform (optional) |
| Secrets | Vercel Environment Variables |
12.4 Rollback Proceduresβ
| Scenario | Action |
|---|---|
| Bad deployment | Instant rollback via Vercel UI |
| Database migration issue | Run down migration |
| Configuration error | Revert environment variable |
| Third-party outage | Feature flag disable |
12.5 Backup Strategyβ
| Data | Frequency | Retention | Location |
|---|---|---|---|
| Database | Daily | 30 days | Supabase automatic |
| User uploads | Real-time | Indefinite | S3 versioning |
| Logs | - | 90 days | Axiom |
| Secrets | On change | Version history | Vercel |
13. Development Guidelinesβ
13.1 Code Organizationβ
Follow the component/feature colocation pattern:
- Keep related files together
- Export public API from index files
- Use barrel exports sparingly
13.2 Naming Conventionsβ
| Type | Convention | Example |
|---|---|---|
| Components | PascalCase | UserProfile.tsx |
| Utilities | camelCase | formatDate.ts |
| Constants | SCREAMING_SNAKE | MAX_FILE_SIZE |
| Types | PascalCase | type UserProfile |
| API routes | kebab-case | user-profile/route.ts |
| CSS classes | kebab-case | user-profile-card |
13.3 Git Workflowβ
| Branch | Purpose | Naming |
|---|---|---|
| main | Production | - |
| feature/* | New features | feature/add-user-profile |
| fix/* | Bug fixes | fix/login-redirect |
| chore/* | Maintenance | chore/update-deps |
13.4 PR Requirementsβ
- Descriptive title and description
- Tests added/updated
- No TypeScript errors
- Lint passes
- Preview deployment works
- Self-review completed
13.5 Code Review Guidelinesβ
- Review within 24 hours
- Focus on logic, security, performance
- Use conventional comments (nit:, question:, suggestion:)
- Approve with minor comments when appropriate
Constraints & Contextβ
- Budget range: [specify]
- Team size: [specify]
- Timeline: [specify]
- Existing systems: [list any to integrate]
- Compliance: [GDPR, SOC2, etc.]
- Geographic scope: [regions, data residency]
Output Formatβ
- Use markdown with clear hierarchical headers
- Include mermaid diagrams for architecture and flows
- Use tables for structured information
- Provide rationale for all major decisions
- Flag assumptions that need validation with [ASSUMPTION]
- Mark areas needing user input with [USER INPUT NEEDED]