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:#f59e0bTechnology Stack
| Layer | Technology | Purpose |
|---|---|---|
| Frontend Framework | React 18 | UI components and state management |
| Language | TypeScript | Type safety and developer experience |
| Build Tool | Vite | Fast development and optimized builds |
| Styling | Tailwind CSS | Utility-first CSS framework |
| UI Components | shadcn/ui | Accessible component library |
| Backend | Supabase | PostgreSQL, Auth, Realtime, Storage |
| Database | PostgreSQL 15+ | Relational database with RLS |
| Routing | React Router v6 | Client-side routing |
| State | React Context + React Query | Global and server state |
| Charts | Recharts | Data visualization |
| PWA | Workbox | Service 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:#f59e0bLayer Responsibilities
- Pages: Route-level components, layout
- Components: Reusable business components
- UI Components: Base UI primitives (shadcn/ui)
- Business Logic: Domain-specific functions
- API Layer: Supabase client wrapper
- 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 UISecurity 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:#10b981Security Layers
- Authentication: JWT tokens via Supabase Auth
- Authorization: Role-based access control
- Tenant Isolation: Row-Level Security (RLS)
- Data Validation: Input validation and sanitization
- 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:#6366f1Isolation Mechanisms
- Database Level: RLS policies filter by
tenant_id - Application Level: Automatic tenant context injection
- API Level: Tenant validation on all requests
- 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:#10b981Optimization Techniques
- Query Optimization: Indexed queries, batch operations, materialized views
- 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
- Multi-Layer Caching Strategy:
- Server-Side: Edge Function in-memory cache (60s TTL)
- Client-Side: React Query cache (30s staleTime, 60s gcTime)
- Static Cache:
DashboardCachefor immediate UI updates - Persistent Cache: IndexedDB for inventory and pick lists
- Stale-While-Revalidate: Background refresh without blocking UI
- 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
- Field selection optimization (removed
- 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
- Lazy Loading: Code splitting, route-based chunks
- Pre-computation: Distance calculations, route optimization
- 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:
- Client requests snapshot with optional
lightweightand pagination parameters - Edge Function checks cache (cache key includes query parameters)
- On cache miss, executes parallel queries to all data sources
- Aggregates results into single response
- Caches response for 60 seconds
- Returns compressed response (gzip/deflate)
Client-Side Flow (Stability Rules):
- React Query checks client-side cache (30s
staleTime, 60sgcTime) - If cache is fresh, returns cached data immediately with no extra REST calls
- When data becomes stale, stale-while-revalidate returns cached data immediately and refreshes in the background
- UI updates when fresh data arrives; no polling or focus-based refetch spikes
Stability Principles:
- Snapshot-first: dashboards should use aggregated snapshot endpoints instead of many small REST calls
- Cache-first: always prefer React Query + IndexedDB cache over re-fetching the same data
- Realtime-over-polling: Supabase Realtime is preferred for high-frequency updates, with slow polling only as a fallback
- No REST on hover/animation: hover handlers, mouse move events, and animation loops must never trigger Supabase/HTTP calls
- 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
Related Documentation
- Multi-Tenant Architecture - Tenant isolation details
- Database Schema - Database structure
- RLS Policies - Security policies
- Developer Guide - Development practices