per-tenant-database

bởi rivet-dev

Multi-tenant data isolation with one Rivet Actor per tenant: the actor key is the tenant id, so each tenant gets its own isolated dataset and migrations.

npx skills add https://github.com/rivet-dev/skills --skill per-tenant-database

Database per Tenant

IMPORTANT: Before doing anything, you MUST read BASE_SKILL.md in this skill's directory. It contains essential guidance on debugging, error handling, state management, deployment, and project setup. Those rules and patterns apply to all RivetKit work. Everything below assumes you have already read and understood it.

Working Examples

If you need a reference implementation, read the raw working example code in these templates:

Patterns for database-per-tenant architectures with RivetKit. Instead of one shared database with a tenant_id column on every table, each tenant gets its own Rivet Actor, and that actor owns the tenant's entire dataset.

Starter Code

Start with the working example on GitHub and adapt it. The example stores each tenant's dataset in JSON actor state and serves a React dashboard with live event updates.

TopicSummary
IsolationOne companyDatabase actor per tenant, keyed by company name. Switching tenants swaps the entire dataset.
StateJSON actor state holding employees and projects arrays plus timestamps. No SQLite, no queues, no scheduling.
RealtimeEvery write action mutates state, then broadcasts a typed event (employeeAdded, projectAdded) to all connected clients of that tenant.
AuthNone. The sign-in screen is cosmetic. Production guidance is in the security checklist.

The Isolation Model

The actor key is the tenant id. The client connects with useActor({ name: "companyDatabase", key: [companyName] }) and the actor reads c.key[0] in createState to seed that tenant's dataset. This gives you:

  • One actor per tenant: companyDatabase[tenantId] addresses exactly one actor instance. Two tenants can never share an actor.
  • One dataset per tenant: All reads and writes go through that actor's state, so there is no shared table with a tenant_id column to filter incorrectly. Cross-tenant leaks require constructing the wrong key, not forgetting a WHERE clause.
  • No key injection: Keys are arrays, not interpolated strings. key: [tenantId] cannot be escaped the way "tenant:" + tenantId string concatenation can. See Keys.

The example's test (tests/per-tenant-database.test.ts) proves the isolation: data written to companyDatabase["Alpha Co"] never appears in companyDatabase["Beta Co"].

Choosing a State Backend

The example uses plain JSON actor state. The same key-equals-tenant model works with any actor state backend.

BackendUse WhenDocsWorking Code
JSON actor stateSmall datasets, simple reads, whole dataset fits comfortably in memory. What the example uses.StateGitHub
Actor SQLite (rivetkit/db)Tables, indexes, SQL queries, larger-than-memory data, per-tenant relational schema.SQLiteGitHub
SQLite + DrizzleTyped schema, query builder, and generated migration files on top of actor SQLite.SQLite + DrizzleGitHub

With either SQLite option, every tenant gets its own embedded SQLite database, since the database is scoped to the actor and the actor is scoped to the tenant.

Migrations

The per-tenant example has no migrations because JSON state has no schema. When you adopt SQLite, migrations run per tenant database:

  • Raw SQL: db({ onMigrate }) runs your migration SQL inside a SQLite savepoint before the actor serves traffic. If onMigrate throws, all migration SQL rolls back atomically and the actor does not start. See SQLite.
  • Drizzle: drizzle-kit generates migration files from your typed schema, and db({ schema, migrations }) applies them when the actor wakes. See SQLite + Drizzle.

Because each tenant has its own database, migrations roll out per actor as each tenant's actor wakes, rather than as one large migration against a shared database.

Tenant Id Must Come From Auth

The example's sign-in is cosmetic: the client picks any company string and that string becomes the actor key, so any visitor can read and write any tenant's data. Do not ship this. As a required production extension (not implemented by the example):

  • Derive the tenant id from a verified credential, such as a JWT claim, never from user input.
  • Validate the credential against c.key in onBeforeConnect (pass/fail) or createConnState (store the verified user on connection state). See Authentication and Connections.
  • Add per-action permission checks on top of connection-level auth. See Access Control.

Actors

  • Key: companyDatabase[companyName] (single-element array key; c.key[0] is the company name)
  • Responsibility: One actor per tenant. Holds that company's employees and projects in persistent state, serves reads and writes via actions, and broadcasts mutations to connected clients.
  • Actions
    • addEmployee
    • listEmployees
    • addProject
    • listProjects
    • getStats
  • Queues
    • None
  • Events
    • employeeAdded
    • projectAdded
  • State
    • JSON
    • company_name
    • employees
    • projects
    • created_at
    • updated_at

Every write action follows the same mutate-then-broadcast shape: push the record into c.state, bump updated_at, broadcast the typed event, return the record. See Actions and Events.

Lifecycle

sequenceDiagram
	participant A as Tenant A client
	participant DA as companyDatabase A
	participant B as Tenant B client
	participant DB as companyDatabase B

	Note over A: authenticate and derive tenant id
	A->>DA: connect with key [tenantA]
	Note over DA: createState seeds company_name, employees, projects
	A->>DA: listEmployees() + listProjects() + getStats()
	A->>DA: addEmployee(name, role)
	DA-->>A: employeeAdded event
	B->>DB: connect with key [tenantB]
	Note over DB: separate actor, separate dataset
	B->>DB: listEmployees()
	DB-->>B: tenant B data only

In the example, the "authenticate" step is a free-text company picker. The rest of the flow matches the diagram: createState seeds the dataset on first creation, the dashboard loads with listEmployees, listProjects, and getStats, and every connected client of the same tenant receives employeeAdded and projectAdded events.

Security Checklist

The example ships with none of these. Apply all of them before production.

  • Tenant identity: Derive the tenant id from a verified JWT claim, never from a client-supplied string.
  • Connection validation: In onBeforeConnect or createConnState, verify the credential's tenant claim matches c.key and reject mismatches.
  • Per-action authorization: Check the caller's role before mutating actions (addEmployee, addProject), not just at connect time. See Access Control.
  • Input validation: Clamp name and role lengths and validate enums. The example only trims input and substitutes fallback defaults.
  • Key construction: Always pass the tenant id as an array element (key: [tenantId]). Never interpolate tenant ids into key strings, and never build keys from one tenant's input to address another tenant's actor.
  • Growth limits: As a recommended extension, cap or paginate the employees and projects arrays. The example lets them grow unboundedly in JSON state; move to SQLite when the dataset outgrows memory.

Reference Map

Actors

Cli

Clients

Cookbook

Deploy

General

Self Hosting

Thêm skills từ rivet-dev

ai-agent
rivet-dev
Xây dựng backend cho AI agent với bộ nhớ liên tục: một Rivet Actor cho mỗi cuộc hội thoại, xử lý tin nhắn theo hàng đợi, và phản hồi LLM dạng stream dưới dạng sự kiện thời gian thực.
official
ai-agent-workspace
rivet-dev
Give every AI agent its own computer: a persistent workspace with a filesystem, processes, shells, networking, and agent sessions on a lightweight in-process…
official
chat-room
rivet-dev
Build a realtime chat room backend with Rivet Actors: one actor per room, SQLite-backed message history, and WebSocket broadcast to every connected client.
official
collaborative-text-editor
rivet-dev
Xây dựng backend cho trình soạn thảo văn bản cộng tác với Yjs CRDTs và Rivet Actors: các actor theo từng tài liệu chuyển tiếp đồng bộ hóa và cập nhật nhận thức, đồng thời lưu trữ ảnh chụp nhanh.
official
cron-jobs
rivet-dev
Durable cron jobs with Rivet Actors: schedule.after and schedule.at timers survive restarts and crashes, plus re-arming recurring jobs and idempotent handlers.
official
live-cursors
rivet-dev
Live cursors and multiplayer presence with Rivet Actors: per-connection cursor state, realtime updates over events or raw WebSockets, and throttling.
official
rivetkit-client-javascript
rivet-dev
Máy khách JavaScript để kết nối với Rivet Actors qua kết nối không trạng thái hoặc có trạng thái. Hỗ trợ môi trường trình duyệt, Node.js và Bun với tính năng tự động phát hiện điểm cuối qua biến môi trường hoặc cấu hình tường minh. Cung cấp hai chế độ tương tác: gọi hành động không trạng thái cho các yêu cầu độc lập và kết nối có trạng thái với đăng ký sự kiện thời gian thực. Bao gồm truy cập HTTP và WebSocket cấp thấp cho các actor triển khai trình xử lý onRequest hoặc onWebSocket. Cung cấp mảng dựa trên hợp chất...
official
rivetkit-client-react
rivet-dev
Trình kết nối React để kết nối với Rivet Actors bằng hooks và quản lý trạng thái thời gian thực. Tạo hooks có kiểu với createRivetKit() và kết nối đến các phiên bản actor bằng useActor() với khóa và tham số tùy chọn. Đăng ký sự kiện actor với useEvent() và theo dõi vòng đời kết nối qua các trạng thái connStatus và error. Sử dụng createClient() cho các lệnh gọi một lần không trạng thái, các phương thức khám phá actor (get, getOrCreate, create, getForId), và truy cập HTTP/WebSocket cấp thấp. Hỗ trợ khóa mảng phức hợp...
official