Architecture
System Overview

System Overview

HiveForge is a full-stack SaaS platform built with modern technologies and best practices.

High-Level Architecture

┌─────────────────────────────────────────────────────────────┐
│                         End Users                            │
└────────────────┬────────────────────────────────────────────┘

    ┌────────────┴────────────┐
    │   CDN / Edge Network    │
    │      (Netlify)          │
    └────────────┬────────────┘

    ┌────────────▼────────────┐
    │   Next.js Frontend      │
    │   - App Router          │
    │   - React Components    │
    │   - Client-side Logic   │
    └────┬───────────────┬────┘
         │               │
         │               └──────────────┐
         │                              │
    ┌────▼────────┐            ┌───────▼──────┐
    │  Supabase   │            │ FastAPI      │
    │  - Auth     │            │ Backend      │
    │  - Database │            │ (Railway)    │
    │  - Storage  │            └───┬──────────┘
    └─────────────┘                │

         ┌─────────────────────────┼─────────────────────┐
         │                         │                     │
    ┌────▼─────┐          ┌───────▼──────┐      ┌──────▼─────┐
    │  Stripe  │          │   Resend     │      │  OpenAI    │
    │ Billing  │          │   Email      │      │    AI      │
    └──────────┘          └──────────────┘      └────────────┘

Technology Stack

Frontend

  • Framework: Next.js 14 (App Router)
  • Language: TypeScript
  • UI: React + Tailwind CSS
  • State: React Context + Hooks
  • Forms: React Hook Form + Zod
  • API Client: Fetch + SWR
  • Auth: Supabase Auth Client
  • Deployment: Netlify

Backend

  • Framework: FastAPI
  • Language: Python 3.11+
  • Database: PostgreSQL (via Supabase)
  • ORM: Supabase Client / SQLAlchemy
  • Auth: Supabase Auth + JWT
  • Validation: Pydantic
  • Deployment: Railway
  • Task Queue: Celery (optional)

Infrastructure

  • Database: Supabase (PostgreSQL + Auth + Storage)
  • Authentication: Supabase Auth
  • Payments: Stripe
  • Email: Resend
  • AI: OpenAI / Anthropic Claude
  • Monitoring: Sentry
  • Analytics: PostHog (optional)
  • CDN: Netlify Edge

Development

  • Monorepo: Turborepo
  • Package Manager: pnpm
  • Linting: ESLint + Prettier
  • Testing: Jest + Pytest + Playwright
  • CI/CD: GitHub Actions
  • Version Control: Git + GitHub

Core Components

1. Frontend Application

Purpose: User interface and client-side logic

Key Features:

  • Server-side rendering (SSR)
  • Static site generation (SSG)
  • API routes for BFF pattern
  • Optimistic updates
  • Real-time subscriptions

Technology Choices:

  • Next.js App Router: File-based routing, nested layouts, server components
  • Tailwind CSS: Utility-first styling, consistent design system
  • SWR: Client-side data fetching with caching
  • React Hook Form: Performant form handling with validation

2. Backend API

Purpose: Business logic, data processing, integrations

Key Features:

  • RESTful API endpoints
  • OpenAPI documentation
  • Background task processing
  • Webhook handling
  • External service integrations

Technology Choices:

  • FastAPI: High performance, automatic OpenAPI docs, type safety
  • Pydantic: Data validation and serialization
  • Async/Await: Non-blocking I/O for better performance
  • Dependency Injection: Clean architecture and testability

3. Database Layer

Purpose: Data persistence and real-time features

Key Features:

  • PostgreSQL database
  • Row-Level Security (RLS)
  • Real-time subscriptions
  • Full-text search
  • Automatic backups

Technology Choices:

  • Supabase: Managed PostgreSQL with built-in auth and real-time
  • RLS Policies: Database-level security for multi-tenancy
  • Migrations: Version-controlled schema changes
  • Seed Data: Consistent development environments

4. Authentication System

Purpose: User identity and access control

Key Features:

  • Email/password authentication
  • OAuth providers (Google, GitHub)
  • JWT token management
  • Session management
  • Role-based access control (RBAC)

Technology Choices:

  • Supabase Auth: Managed authentication service
  • JWT: Stateless token-based authentication
  • HTTP-only cookies: Secure token storage
  • Custom RBAC: Fine-grained permissions

5. Billing System

Purpose: Subscription and payment management

Key Features:

  • Subscription plans (Free, Pro, Enterprise)
  • Metered billing
  • Customer portal
  • Webhook processing
  • Invoice management

Technology Choices:

  • Stripe: Payment processing and subscription management
  • Webhook verification: Secure event handling
  • Customer portal: Self-service billing management

6. Email System

Purpose: Transactional email delivery

Key Features:

  • React Email templates
  • HTML and plain text variants
  • Template variables
  • Delivery tracking
  • Queue management

Technology Choices:

  • Resend: Modern email API
  • React Email: Type-safe email templates with React
  • Background processing: Async email sending

Design Principles

1. Separation of Concerns

  • Frontend: UI and user interaction
  • Backend: Business logic and data processing
  • Database: Data persistence and security
  • External Services: Specialized functionality (payments, email, AI)

2. Type Safety

  • TypeScript on frontend for compile-time checks
  • Pydantic on backend for runtime validation
  • Shared type definitions where possible
  • OpenAPI schema for API contracts

3. Security First

  • Row-Level Security (RLS) in database
  • JWT authentication with short expiry
  • API key management with scopes
  • Audit logging for sensitive operations
  • CORS and CSP headers
  • Rate limiting on API endpoints

4. Scalability

  • Stateless API design
  • Database connection pooling
  • CDN for static assets
  • Async processing for heavy tasks
  • Caching strategies (SWR, Redis)
  • Horizontal scaling capability

5. Developer Experience

  • Monorepo for code organization
  • Hot module replacement
  • Comprehensive testing
  • Automated CI/CD
  • Clear documentation
  • Type safety throughout

Data Flow

1. Read Flow (Data Fetch)

User → Frontend → API → Database → API → Frontend → User
  1. User interacts with UI
  2. Frontend makes API request
  3. API validates authentication/authorization
  4. API queries database (with RLS)
  5. Database returns filtered data
  6. API transforms and returns data
  7. Frontend updates UI

2. Write Flow (Data Mutation)

User → Frontend → API → Validation → Database → Webhook → External Services
  1. User submits form
  2. Frontend validates input
  3. Frontend sends request to API
  4. API validates again (never trust client)
  5. API writes to database
  6. Database triggers webhooks
  7. External services process events

3. Authentication Flow

User → Frontend → Supabase Auth → Database → JWT → Frontend → API
  1. User enters credentials
  2. Frontend calls Supabase Auth
  3. Supabase validates credentials
  4. Supabase returns JWT token
  5. Frontend stores token (HTTP-only cookie)
  6. Frontend uses token for API requests
  7. API validates token on each request

Deployment Architecture

Development Environment

Local Machine:
  - Next.js (localhost:3000)
  - FastAPI (localhost:8000)
  - Supabase (localhost:54321)
  - Inbucket Email (localhost:54324)

Production Environment

┌─────────────┐
│   Netlify   │  Frontend (Next.js)
└──────┬──────┘

    ┌──▼──────┐
    │ Railway │  Backend (FastAPI)
    └──┬──────┘

    ┌──▼──────┐
    │Supabase │  Database + Auth + Storage
    └─────────┘

Edge Functions (Optional)

┌──────────────┐
│ Netlify Edge │  Geographic distribution
└──────┬───────┘

    ┌──▼─────┐
    │ Origin │  Main application
    └────────┘

Communication Patterns

Synchronous (REST API)

  • User-initiated actions
  • Real-time requirements
  • Simple CRUD operations
// Frontend → Backend
const response = await fetch('/api/organizations', {
  method: 'POST',
  body: JSON.stringify(data)
})

Asynchronous (Webhooks)

  • External service events
  • Long-running processes
  • Background jobs
# Stripe → Backend
@router.post("/webhooks/stripe")
async def stripe_webhook(request: Request):
    event = stripe.Webhook.construct_event(...)
    await process_event(event)

Real-time (Subscriptions)

  • Live updates
  • Collaborative features
  • Notifications
// Database → Frontend
supabase
  .channel('organizations')
  .on('postgres_changes', {
    event: 'INSERT',
    schema: 'public',
    table: 'organizations'
  }, handleNewOrg)
  .subscribe()

Error Handling

Frontend

try {
  const data = await apiClient.get('/endpoint')
  return data
} catch (error) {
  if (error.status === 401) {
    // Redirect to login
  } else if (error.status === 403) {
    // Show permission error
  } else {
    // Show generic error
    Sentry.captureException(error)
  }
}

Backend

from fastapi import HTTPException
 
try:
    result = await service.perform_action()
    return result
except NotFoundError as e:
    raise HTTPException(status_code=404, detail=str(e))
except PermissionError as e:
    raise HTTPException(status_code=403, detail=str(e))
except Exception as e:
    logger.error(f"Unexpected error: {e}")
    raise HTTPException(status_code=500, detail="Internal server error")

Performance Optimization

Frontend

  • Code splitting and lazy loading
  • Image optimization
  • Font optimization
  • Static page generation
  • Edge caching

Backend

  • Database query optimization
  • Connection pooling
  • Response caching
  • Async processing
  • Rate limiting

Database

  • Proper indexing
  • Query optimization
  • Connection pooling
  • Read replicas (if needed)
  • Materialized views

Monitoring and Observability

Metrics Tracked

  • API response times
  • Error rates
  • Database query performance
  • User authentication events
  • Billing events
  • Email delivery rates

Tools

  • Sentry: Error tracking and performance monitoring
  • Logs: Structured logging with correlation IDs
  • Health Checks: Endpoint monitoring
  • Uptime Monitoring: External service monitoring

Next Steps