Skip to content

Architecture

Technical architecture — stack, multi-tenancy, data model, and infrastructure.

7 min read

Overview

Kagami is a single-instance, multi-tenant SaaS application built on Next.js (App Router), Supabase (Postgres), and deployed on Oracle Cloud Infrastructure (OCI) VMs behind nginx + PM2. All tenants share one database; isolation is enforced by Row-Level Security (RLS) policies at the database layer — not by separate databases or schemas per tenant.

Kagami multi-tenant platform architecture separating control plane, tenant operations, and client booking

Technology Stack

Layer Technology Why
Web framework Next.js 16 (App Router) Server components, streaming, routing
UI library React 19 + TypeScript Component model, type safety
Styling Tailwind CSS 4 + shadcn/ui Design system, composable components
Database Supabase Postgres SQL, RLS, Auth, Storage, Realtime
Auth Supabase Auth JWT, RLS integration, email/OTP
Realtime Supabase Realtime Calendar and queue live sync
AI OpenRouter (default model deepseek/deepseek-v4-flash-0731) with Groq and optional Anthropic failover WhatsApp/web AI agent and other capabilities; see AI Architecture
Voice Plivo + Dograh Inbound call handling
Payments Razorpay (adapter) UPI, cards; India-first
Messaging WhatsApp Business API (adapter) Primary client channel in India
Accounting Zoho Books (adapter) Accounting sync
Email Resend Transactional and campaign emails (web/src/lib/email)
Mobile Capacitor 8 (Android WebView shells, no iOS build) apps/mobile-app and apps/mobile-capacitor; see Mobile App
Testing Vitest (unit), Playwright (E2E) Test pyramid
CI/CD GitHub Actions (deploy workflow only) ci.yml is disabled; deploy is a manual workflow; see Development and Deployment
Hosting OCI VMs / nginx + PM2 (web), Supabase Cloud (data) salonos-prod plus kagami-prod-1, kept on the same build

Three-Plane Structure

Control Plane (/super-admin, /(control))

Platform operators manage tenants, subscriptions, and support here. This plane is not accessible to tenant users.

Tenant Plane (/(tenant))

The operator dashboard. All features from scheduling through analytics live here. The tenant plane is the bulk of the codebase (170+ page.tsx routes under src/app/(tenant)).

Client Plane (/(client), /(embed))

Client-facing surfaces: booking widget, portal, check-in, intake, consent, feedback. These are lightly authenticated (client session or magic link) and white-labelled per brand.

Multi-Tenancy

Hierarchy

org → brand → location → staff

Every data entity carries a combination of org_id, brand_id, and/or location_id. The appropriate foreign keys are set at the boundary of what that entity belongs to:

  • Clients are brand-scoped (brand_id)
  • Appointments are location-scoped (location_id)
  • Services are brand-scoped (brand_id), with optional location overrides

Row-Level Security (RLS)

Every table has RLS enabled. Policies enforce:

  • A user can only read rows for orgs they belong to, checked through membership helpers such as public.is_org_member(org_id) and public.is_org_admin(org_id) (security-definer functions over the memberships table, keyed on auth.uid(); see 0001_tenant_core.sql). This is not a JWT org_id claim.
  • Brand-scoped data: also checks brand_id
  • Location-scoped data: also checks location_id

For requests made with the user's own session, the database enforces isolation. Some later migrations add brand/location scoping on top (for example 0142_clients_rls_brand_location_scope.sql).

Server Actions

Mutations in the tenant plane run as Server Actions. Many of them use the user's authenticated Supabase client, so RLS applies to the write; many server helpers (for example lib/billing/actions.ts) use the service-role client instead, which bypasses RLS, so for those the server-side role check in lib/auth is the real gate. See Roles & Permissions.

Service Role Usage

The Supabase service_role key bypasses RLS. It is used through getSupabaseAdmin() in:

  • Background cron jobs (reminders, journeys, birthday sends)
  • Data imports
  • Platform-level admin operations in the control plane
  • Many tenant-plane server helpers and Server Actions (billing, scheduling, AI and others)

Because the database does not enforce isolation for these paths, each one must check the caller's role and scope in code before reading or writing. The key is read only on the server and is never sent to the browser.

White-Label Theming

Brand resolution happens at request time:

  1. The request URL (custom domain or brand slug) is matched to a brand record
  2. The brand's theme tokens (primary colour, secondary colour, accent, logo URL) are loaded
  3. CSS custom properties are set on the response: --brand-primary, --brand-secondary, etc.
  4. All components use these variables — no component hard-codes a colour

This means the same codebase serves every brand with its own visual identity with zero per-brand code.

Realtime Architecture

Supabase Realtime is used selectively for surfaces where live updates genuinely matter:

  • Calendar: appointment changes from any connected device appear within 1 second
  • Queue board: walk-in additions and assignment updates are live

Realtime subscriptions are scoped to location_id — a user never receives another location's events.

Background Jobs

Jobs that run asynchronously (reminders, journeys, review requests, birthdays):

  • Each job is an idempotent POST /api/cron/* route in web/src/app/api/cron/. Most recurring jobs are scheduled by Supabase pg_cron + pg_net (migration 0176_pg_cron_recurring_jobs.sql and later *_cron.sql migrations), authenticated with a secret kept in Supabase Vault. A few jobs and the ECG health watchdog still run from the prod VM crontab (scripts-vm/crontab; see scripts-vm/README.md). Do not schedule the same job in both places.
  • Run as service-role operations with explicit scope
  • Idempotent: running the same job twice produces the same outcome
  • Logged: every job run, batch size, and outcome is recorded

AI Architecture

The WhatsApp/web AI agent (web/src/lib/ai/gateway.ts, runAgentTurn) talks to models through a provider layer, web/src/lib/ai/llm.ts. It speaks the OpenAI-compatible /chat/completions format, translates to and from Anthropic's block format, and fails over down an ordered list of providers that have a key configured:

Agent turn (gateway.ts, tools.ts)
         ↓
  chatWithFailover()  (llm.ts)
         ↓
  1. OpenRouter   (default model deepseek/deepseek-v4-flash-0731; OPENROUTER_MODEL overrides)
  2. OpenRouter -> Groq (only when OPENROUTER_GROQ_BYOK=1)
  3. Groq direct  (default openai/gpt-oss-20b)
  4. Anthropic    (only when ANTHROPIC_API_KEY is set)
  • A brand's configured model is honored only when AI_HONOR_BRAND_MODEL=1; otherwise the OpenRouter default is used. A Claude model request can move Anthropic to the front of the list.
  • Cost per call is logged from per-provider token prices (computeCostUsd).
  • An optional reply jury (reply-jury.ts, enabled with AI_REPLY_JURY=on) has several models score a drafted reply and holds low-confidence replies for staff.
  • The older capability gateway in web/src/lib/ai-gateway/index.ts still maps capabilities to Claude models. When ANTHROPIC_API_KEY is absent (prod runs on OPENROUTER_API_KEY) it routes text-only calls through the same failover chain.
  • Voice calls use Plivo plus the Dograh chat-completions endpoint (web/src/app/api/voice/dograh/v1/chat/completions).

For features and guardrails see AI Features.

Data Model — Key Entities

Domain Core entities
Tenancy Org, Brand, Location, User, Role membership (memberships: a user's role and scope)
Catalog ServiceCategory, Service, ServiceVariant, AddOn, Resource
People StaffProfile, Skill, Shift, TimeOff, Client, ClientNote
Scheduling Appointment, AppointmentService, QueueEntry, CalendarBlock
Commerce Invoice, InvoiceLineItem, Payment, Deposit, Refund
Cash CashDrawer, CashMovement, ShiftClose
Retention Membership, Package, LoyaltyAccount, GiftCard, WalletEntry
Inventory Product, StockItem, StockMovement, PurchaseOrder
Staff Ops CommissionRule, AttendanceRecord (commissions are computed per period, not stored in a ledger)
Finance Expense, VendorBill, BankSettlement, ReconciliationMatch
Marketing Segment, Campaign, Journey, JourneyRun, Offer
Platform Plan, Subscription, AuditLog, ImportJob

Security Posture

  • RLS: every table, every read and write
  • HTTPS only: enforced by nginx (Let's Encrypt) and Supabase
  • Secrets: environment variables only; never in code or logs
  • Input validation: Zod schemas on all Server Action inputs
  • Webhook verification: HMAC signature checks on all inbound webhooks (payment, WhatsApp)
  • Audit log: every state-changing action records who, what, and when
  • PII handling: personal data in analytics views is anonymised; AI prompts redact sensitive fields

Development and Deployment

Environments

Environment Purpose
Local Developer machine: localhost:3000 against the local Supabase stack (Docker), loaded from a prod clone by web/scripts/sync-prod-to-local.sh. Never point the local app at the prod Supabase project
Production Live: OCI VM salonos-prod (nginx + PM2) plus kagami-prod-1, with Supabase Cloud

There is no staging environment and no per-PR preview deploy. The old Vercel staging deploy was removed (SALO-698) and Vercel is no longer running. apps/ai-services/ is dormant code with no deploy target.

CI and Deploy (GitHub Actions)

  • .github/workflows/ci.yml.disabled: lint, type check, tests and build are not run automatically right now. Run npm run verify (or the individual lint/typecheck/test scripts) locally before opening a PR.
  • .github/workflows/deploy.yml: triggered manually (workflow_dispatch) only; nothing deploys on merge to master. It builds in an isolated staging clone on the VM, applies migrations, swaps directories atomically, restarts PM2, health-checks /api/health with automatic rollback, then syncs kagami-prod-1 to the same build.
  • If Actions is unavailable, ops/deploy-salonos-prod.sh runs the same build-then-swap deploy from a developer machine over SSH.

Database Migrations

Migrations live in web/supabase/migrations/ (over 300 .sql files, numbered from 0001; several numeric prefixes are used more than once).

  • web/scripts/migrate.mjs applies pending files in filename order against the prod Supabase project (via the Management API) and records them in public.schema_migrations. The deploy runs it; production migrations are applied by deploys, not by developers' local apps.
  • Do not replay migrations into the local database or run supabase db reset: the duplicate prefixes make replay abort. The local schema comes from the prod dump (sync-prod-to-local.sh).