Skip to main content

Introduction

RestAI is a modern, multi-tenant restaurant management system built with performance, scalability, and real-time capabilities at its core. The system supports multiple organizations (restaurants), each with multiple branches, staff, and customers.

Technology Stack

  • Runtime: Bun v1.3+ - Fast all-in-one JavaScript runtime
  • Monorepo: Turborepo + Bun workspaces for efficient multi-package development
  • Language: TypeScript 5.8 for type safety across the entire stack

System Architecture

┌─────────────────────────────────────────────────────────────┐
│                        Client Layer                         │
├──────────────────────┬──────────────────────────────────────┤
│   Admin Dashboard    │        Customer Web App             │
│   (Next.js - :3000)  │     (QR Code Access)                │
└──────────┬───────────┴──────────────────┬──────────────────┘
           │                              │
           │         HTTP/WebSocket       │
           ▼                              ▼
┌─────────────────────────────────────────────────────────────┐
│                    API Server (Hono - :3001)                │
├─────────────────────────────────────────────────────────────┤
│  • REST Endpoints      • JWT Auth       • File Uploads      │
│  • WebSocket Server    • Role-based ACL • Business Logic    │
└──────────┬───────────────────────────┬──────────────────────┘
           │                           │
           ▼                           ▼
┌──────────────────────┐    ┌─────────────────────┐
│   PostgreSQL 17      │    │      Redis 7        │
├──────────────────────┤    ├─────────────────────┤
│ • Primary Database   │    │ • Pub/Sub for WS    │
│ • All Business Data  │    │ • Session Cache     │
│ • Multi-tenant       │    │ • Real-time Events  │
└──────────────────────┘    └─────────────────────┘

Multi-Tenancy Model

RestAI implements a shared database, schema-level multi-tenancy approach:
// Organization (Tenant Root)
organizations
  ├── id: uuid (primary key)
  ├── name: string
  ├── slug: string (unique)
  ├── plan: "free" | "starter" | "pro" | "enterprise"
  └── branches[]
        ├── id: uuid
        ├── organization_id: uuid (FK)
        ├── name: string
        ├── timezone: string (default: "America/Lima")
        ├── currency: string (default: "PEN")
        └── tax_rate: integer (stored as 1800 = 18.00%)
All database queries are automatically scoped to the authenticated user’s organization and branch(es) to ensure complete data isolation between tenants.

Core Features

1. Order Management

  • Order Types: Dine-in, Takeout, Delivery
  • Real-time Status: Pending → Confirmed → Preparing → Ready → Served → Completed
  • Multi-item Orders: Support for modifiers, special instructions, and quantity adjustments
  • Price Snapshots: Historical price data preserved in order items

2. Table Management

  • QR Code Access: Each table has a unique QR code for customer self-service
  • Table Sessions: Track customer sessions from start to completion
  • Status Tracking: Available, Occupied, Reserved, Maintenance
  • Space Organization: Group tables by floor/space for better organization

3. Menu & Inventory

  • Category Management: Hierarchical menu categories
  • Modifier Groups: Customizable options (size, extras, substitutions)
  • Inventory Tracking: Recipe ingredients linked to inventory items
  • Automatic Deduction: Stock consumed when orders are confirmed

4. Real-time Communication

  • WebSocket Channels: Branch-level, table-level, and session-level rooms
  • Event Broadcasting: Order updates, table status changes, kitchen notifications
  • Redis Pub/Sub: Horizontal scaling support for WebSocket events

5. Staff & Permissions

  • Role Hierarchy: Super Admin → Org Admin → Branch Manager → Cashier/Waiter/Kitchen
  • Branch Assignment: Staff can be assigned to multiple branches
  • Table Assignment: Waiters assigned to specific tables

6. Loyalty & Rewards

  • Points System: Earn points on purchases, redeem for rewards
  • Loyalty Tiers: Bronze, Silver, Gold with multipliers
  • Coupon System: Percentage, fixed, buy-x-get-y discounts

7. Payment Processing

  • Multiple Methods: Cash, Card, Yape (Peru), Plin, Bank Transfer
  • Invoice Generation: Boleta and Factura (Peru tax system)
  • SUNAT Integration: Electronic invoice submission tracking

Data Flow: Customer Order Journey

1. Customer scans QR code → Creates table session

2. Customer browses menu → Adds items to cart

3. Customer places order → Order created (status: pending)

4. WebSocket broadcasts to kitchen → Order appears on KDS

5. Kitchen confirms order → Status: confirmed → preparing

6. Inventory auto-deducted → Stock levels updated

7. Kitchen marks ready → Status: ready

8. Waiter serves → Status: served

9. Payment processed → Order completed

10. Loyalty points awarded → Customer record updated

Security & Authentication

JWT Token Strategy

// Short-lived (15 minutes)
interface AccessTokenPayload {
  sub: string;           // user_id
  role: UserRole;
  organization: string;  // organization_id
  branches: string[];    // branch_ids user has access to
  iat: number;
  exp: number;
}

Role-Based Access Control

  • super_admin: Full system access, manage all organizations
  • org_admin: Manage organization settings, all branches
  • branch_manager: Manage single branch, view reports
  • cashier: Process orders and payments
  • waiter: Take orders, update table status
  • kitchen: View and update order preparation status

Performance Optimizations

  1. Database Indexing:
    • Composite indexes on (organization_id, branch_id, status)
    • Indexes on foreign keys and frequently queried fields
    • Timestamp indexes for date range queries
  2. Caching Strategy:
    • Redis for session data and WebSocket room management
    • Menu data caching with TTL
    • Branch settings cached at application level
  3. Query Optimization:
    • Use of Drizzle’s prepared statements
    • Selective field retrieval (no SELECT *)
    • Eager loading for related entities
  4. Real-time Events:
    • Redis Pub/Sub for horizontal scaling
    • WebSocket connection pooling
    • Automatic reconnection handling

Deployment Architecture

Production Environment:

├── Load Balancer (Cloudflare)

├── API Servers (multiple instances)
│   ├── Bun server with WebSocket support
│   └── Horizontal scaling via Redis Pub/Sub

├── Next.js Frontend (Vercel/Cloud)
│   ├── Static generation for public pages
│   └── SSR for authenticated routes

├── PostgreSQL (Managed)
│   ├── Primary instance
│   └── Read replicas for reporting

├── Redis Cluster (Managed)
│   └── Pub/Sub + Cache

└── Cloudflare R2
    └── Static assets and uploads

Design Principles

  1. Type Safety First: TypeScript everywhere, Zod for runtime validation
  2. Multi-tenant by Default: Every table includes organization_id
  3. Real-time Communication: WebSockets for instant updates
  4. Immutable Pricing: Snapshot prices at order time for accurate records
  5. Graceful Degradation: System continues working if Redis is unavailable
  6. Audit Trail: Timestamps and creator tracking on all mutations

Next Steps

Monorepo Structure

Explore the Turborepo workspace organization and packages

Database Schema

Deep dive into the PostgreSQL schema and relationships

Real-time WebSockets

Learn how WebSocket communication powers real-time features

API Documentation

Browse the complete REST API reference

Build docs developers (and LLMs) love