Skip to content

System Architecture

Complete overview of Lager Guru's architecture, components, and design patterns.

Overview

Lager Guru is built as a modern, scalable multi-tenant SaaS application using React, TypeScript, and Supabase. The architecture emphasizes security, performance, and maintainability.

High-Level Architecture

mermaid
graph TB
    subgraph "Client Layer"
        A[React PWA] --> B[Supabase Client]
        A --> C[React Router]
        A --> D[State Management]
    end
    
    subgraph "API Layer"
        B --> E[Supabase API]
        E --> F[PostgreSQL]
        E --> G[Row-Level Security]
        E --> H[Realtime]
        E --> I[Storage]
    end
    
    subgraph "Services"
        J[Routing Engine] --> F
        K[Slotting AI] --> F
        L[Auto Assignment] --> F
    end
    
    subgraph "External"
        M[SSO Providers] --> E
        N[Barcode Scanners] --> A
    end
    
    style A fill:#3b82f6
    style E fill:#10b981
    style F fill:#f59e0b

Technology Stack

LayerTechnologyPurpose
Frontend FrameworkReact 18UI components and state management
LanguageTypeScriptType safety and developer experience
Build ToolViteFast development and optimized builds
StylingTailwind CSSUtility-first CSS framework
UI Componentsshadcn/uiAccessible component library
BackendSupabasePostgreSQL, Auth, Realtime, Storage
DatabasePostgreSQL 15+Relational database with RLS
RoutingReact Router v6Client-side routing
StateReact Context + React QueryGlobal and server state
ChartsRechartsData visualization
PWAWorkboxService workers and offline support

Component Architecture

mermaid
graph LR
    A[Pages] --> B[Components]
    B --> C[UI Components]
    B --> D[Business Logic]
    D --> E[API Layer]
    E --> F[Supabase]
    
    style A fill:#3b82f6
    style B fill:#10b981
    style E fill:#f59e0b

Layer Responsibilities

  1. Pages: Route-level components, layout
  2. Components: Reusable business components
  3. UI Components: Base UI primitives (shadcn/ui)
  4. Business Logic: Domain-specific functions
  5. API Layer: Supabase client wrapper
  6. Supabase: Backend services

Data Flow

mermaid
sequenceDiagram
    participant User
    participant Component
    participant API
    participant RLS
    participant Database
    
    User->>Component: User Action
    Component->>API: API Call
    API->>RLS: Check Permissions
    RLS->>Database: Filter by tenant_id
    Database->>RLS: Return Data
    RLS->>API: Authorized Data
    API->>Component: Response
    Component->>User: Update UI

Security Architecture

Multi-Layer Security

mermaid
graph TB
    A[User Request] --> B[JWT Authentication]
    B --> C[Tenant Context]
    C --> D[RLS Policies]
    D --> E[Database]
    
    F[Service Role] --> E
    
    style B fill:#ef4444
    style D fill:#f59e0b
    style E fill:#10b981

Security Layers

  1. Authentication: JWT tokens via Supabase Auth
  2. Authorization: Role-based access control
  3. Tenant Isolation: Row-Level Security (RLS)
  4. Data Validation: Input validation and sanitization
  5. Service Role: Secure backend operations only

Multi-Tenant Architecture

Tenant Isolation Strategy

mermaid
graph LR
    A[Tenant A] --> B[RLS Filter]
    C[Tenant B] --> B
    D[Tenant C] --> B
    B --> E[Shared Database]
    
    style A fill:#3b82f6
    style C fill:#10b981
    style D fill:#f59e0b
    style E fill:#6366f1

Isolation Mechanisms

  1. Database Level: RLS policies filter by tenant_id
  2. Application Level: Automatic tenant context injection
  3. API Level: Tenant validation on all requests
  4. UI Level: Tenant context in React Context

Performance Optimization

Caching Strategy

mermaid
graph TB
    A[Request] --> B{Cache Hit?}
    B -->|Yes| C[Return Cached]
    B -->|No| D[Fetch from DB]
    D --> E[Store in Cache]
    E --> F[Return Data]
    
    style B fill:#3b82f6
    style C fill:#10b981

Optimization Techniques

  1. Query Optimization: Indexed queries, batch operations, materialized views
  2. Edge Function Aggregation: Supabase Edge Functions aggregate multiple queries into single responses
    • get-dashboard-snapshot-v2: Unified dashboard snapshot (zones, inventory, pick lists, shipments, drivers, safety, import jobs)
      • Supports lightweight mode (60-70% size reduction for KPI dashboards)
      • Pagination support (page, pageSize parameters)
      • Automatic gzip/deflate compression
      • 60s TTL per tenant with cache key isolation
    • admin-dashboard-summary: Aggregates dashboard data (zones, inventory, pick lists, shipments)
    • safety-kpis: Aggregates safety metrics (TSR, incidents, actions, checklists)
    • safety-engagement: Aggregates engagement metrics (scores, badges, leaderboard)
    • In-memory caching with per-tenant isolation (30-60s TTL)
    • Automatic fallback to direct Supabase queries if Edge Functions unavailable
  3. Multi-Layer Caching Strategy:
    • Server-Side: Edge Function in-memory cache (60s TTL)
    • Client-Side: React Query cache (30s staleTime, 60s gcTime)
    • Static Cache: DashboardCache for immediate UI updates
    • Persistent Cache: IndexedDB for inventory and pick lists
    • Stale-While-Revalidate: Background refresh without blocking UI
  4. Response Size Optimization:
    • Field selection optimization (removed select('*'))
    • Lightweight mode for KPI-only dashboards
    • Pagination for large datasets
    • Removed unused JSONB fields
    • Result: 30-70% reduction in response sizes
  5. Database Performance:
    • JSONB indexes (GIN) for frequently queried fields
    • Materialized views for complex aggregations
    • Optimized functions leveraging materialized views
    • Composite indexes for optimal join performance
  6. Lazy Loading: Code splitting, route-based chunks
  7. Pre-computation: Distance calculations, route optimization
  8. CDN: Static asset delivery

Dashboard Snapshot Architecture & Stability Layer

The get-dashboard-snapshot-v2 Edge Function implements a unified snapshot pattern with an explicit stability layer on the client:

Request Flow:

  1. Client requests snapshot with optional lightweight and pagination parameters
  2. Edge Function checks cache (cache key includes query parameters)
  3. On cache miss, executes parallel queries to all data sources
  4. Aggregates results into single response
  5. Caches response for 60 seconds
  6. Returns compressed response (gzip/deflate)

Client-Side Flow (Stability Rules):

  1. React Query checks client-side cache (30s staleTime, 60s gcTime)
  2. If cache is fresh, returns cached data immediately with no extra REST calls
  3. When data becomes stale, stale-while-revalidate returns cached data immediately and refreshes in the background
  4. UI updates when fresh data arrives; no polling or focus-based refetch spikes

Stability Principles:

  1. Snapshot-first: dashboards should use aggregated snapshot endpoints instead of many small REST calls
  2. Cache-first: always prefer React Query + IndexedDB cache over re-fetching the same data
  3. Realtime-over-polling: Supabase Realtime is preferred for high-frequency updates, with slow polling only as a fallback
  4. No REST on hover/animation: hover handlers, mouse move events, and animation loops must never trigger Supabase/HTTP calls
  5. Simulation is local: movement and visualization simulations operate purely on in-memory state

See: Performance Optimization Guide | Edge Functions API Documentation

Edge Functions Performance

Benefits:

  • 60-80% reduction in REST request volume for dashboard views
  • 60-90% reduction in response sizes (500KB → 200KB full / 50KB lightweight)
  • 40-60% faster dashboard load times
  • 70-85% reduction in network traffic
  • Cached responses: < 50ms (cache hit)
  • Uncached responses: 200-500ms (aggregated queries)
  • Tenant-scoped caching ensures data isolation
  • Cache hit rate: ~70% for frequently accessed dashboards

Scalability

Horizontal Scaling

  • Database: Supabase handles PostgreSQL scaling
  • API: Stateless API allows horizontal scaling
  • Frontend: CDN distribution
  • Realtime: Supabase Realtime scaling

Vertical Scaling

  • Database: PostgreSQL connection pooling
  • API: Efficient query patterns
  • Frontend: Code splitting and lazy loading

Released under Commercial License