|
| 1 | +export const author = "nathan-flurry" |
| 2 | +export const published = "2025-12-03" |
| 3 | +export const category = "changelog" |
| 4 | +export const keywords = ["ai", "backend", "generation", "freestyle", "actors", "realtime", "database"] |
| 5 | + |
| 6 | +# Generating AI & User Generated Backends with Rivet |
| 7 | + |
| 8 | +**Rivet now supports programmatically deploying AI-generated and user-generated actor code to sandboxed namespaces, enabling use cases like AI code execution, user sandbox environments, preview deployments, and multi-tenant applications.** |
| 9 | + |
| 10 | +## The Problem With AI-Generated Backend Code |
| 11 | + |
| 12 | +When AI agents generate backend code, they typically need to coordinate across multiple disconnected systems: |
| 13 | + |
| 14 | +- **Database schemas** - Define tables, columns, and relationships |
| 15 | +- **API logic** - Write endpoints that query and mutate data |
| 16 | +- **Schema synchronization** - Keep database and API in sync as requirements change |
| 17 | + |
| 18 | +Each system requires separate context, increasing token usage and cognitive load for the AI. More importantly, state and behavior can drift apart when defined separately, leading to bugs and inconsistencies. |
| 19 | + |
| 20 | +## How We Solved This |
| 21 | + |
| 22 | +### Rivet Actors: AI-Friendly Code Generation With Less Context & Fragmentation |
| 23 | + |
| 24 | +Rivet Actors solve this by unifying state and logic in a single actor definition. Instead of coordinating between databases and APIs, **state and behavior live together**: |
| 25 | + |
| 26 | +<Tabs> |
| 27 | +<Tab title="With Rivet"> |
| 28 | + |
| 29 | +```typescript {{"title":"registry.ts"}} |
| 30 | +export const user = actor({ |
| 31 | + // State is defined alongside behavior |
| 32 | + createState: (c, input) => ({ |
| 33 | + name: input.name, |
| 34 | + email: input.email, |
| 35 | + createdAt: Date.now(), |
| 36 | + }), |
| 37 | + |
| 38 | + // Actions can read and mutate state |
| 39 | + actions: { |
| 40 | + updateEmail: (c, email: string) => { |
| 41 | + c.state.email = email; |
| 42 | + }, |
| 43 | + getProfile: (c) => c.state, |
| 44 | + }, |
| 45 | +}); |
| 46 | +``` |
| 47 | + |
| 48 | +</Tab> |
| 49 | +<Tab title="With HTTP + SQL"> |
| 50 | + |
| 51 | +```sql {{"title":"migrations/001_create_users.sql"}} |
| 52 | +CREATE TABLE users ( |
| 53 | + id UUID PRIMARY KEY, |
| 54 | + name TEXT NOT NULL, |
| 55 | + created_at BIGINT NOT NULL |
| 56 | +); |
| 57 | +``` |
| 58 | + |
| 59 | +```sql {{"title":"migrations/002_add_email.sql"}} |
| 60 | +ALTER TABLE users ADD COLUMN email TEXT NOT NULL DEFAULT ''; |
| 61 | +CREATE INDEX idx_users_email ON users(email); |
| 62 | +``` |
| 63 | + |
| 64 | +```typescript {{"title":"api/users.ts"}} |
| 65 | +import { Hono } from "hono"; |
| 66 | +import { db } from "./db"; |
| 67 | + |
| 68 | +const app = new Hono(); |
| 69 | + |
| 70 | +app.post("/users/:id", async (c) => { |
| 71 | + const { id } = c.req.param(); |
| 72 | + const { name, email } = await c.req.json(); |
| 73 | + |
| 74 | + await db.query( |
| 75 | + "INSERT INTO users (id, name, email, created_at) VALUES ($1, $2, $3, $4)", |
| 76 | + [id, name, email, Date.now()] |
| 77 | + ); |
| 78 | + |
| 79 | + return c.json({ success: true }); |
| 80 | +}); |
| 81 | + |
| 82 | +app.patch("/users/:id/email", async (c) => { |
| 83 | + const { id } = c.req.param(); |
| 84 | + const { email } = await c.req.json(); |
| 85 | + |
| 86 | + await db.query( |
| 87 | + "UPDATE users SET email = $1 WHERE id = $2", |
| 88 | + [email, id] |
| 89 | + ); |
| 90 | + |
| 91 | + return c.json({ success: true }); |
| 92 | +}); |
| 93 | + |
| 94 | +app.get("/users/:id", async (c) => { |
| 95 | + const { id } = c.req.param(); |
| 96 | + const result = await db.query( |
| 97 | + "SELECT name, email, created_at FROM users WHERE id = $1", |
| 98 | + [id] |
| 99 | + ); |
| 100 | + |
| 101 | + return c.json(result.rows[0]); |
| 102 | +}); |
| 103 | +``` |
| 104 | + |
| 105 | +</Tab> |
| 106 | +</Tabs> |
| 107 | + |
| 108 | +This consolidation eliminates fragmentation: |
| 109 | + |
| 110 | +- **Single source of truth**: No need to keep migrations, schemas, and APIs in sync |
| 111 | +- **Less LLM context required**: Generate one file instead of coordinating multiple systems |
| 112 | +- **Fewer errors**: State and behavior can't drift apart when they're defined together |
| 113 | +- **More powerful generation**: AI agents can focus on business logic instead of infrastructure plumbing |
| 114 | + |
| 115 | +### Rivet Namespaces: Fully Sandboxed Environments |
| 116 | + |
| 117 | +Sandboxed namespaces provide isolated environments where **each AI-generated or user-generated deployment runs independently** with its own resources, tokens, and configuration. This enables safe multi-tenant deployments and user-generated code execution. |
| 118 | + |
| 119 | +## Use Cases |
| 120 | + |
| 121 | +Sandboxed namespaces enable a variety of isolated deployment scenarios: |
| 122 | + |
| 123 | +- **AI-generated code**: Deploy LLM-generated backends safely in isolated environments |
| 124 | +- **User sandbox environments**: Give users their own sandboxed Rivet namespace to experiment |
| 125 | +- **Preview deployments**: Create ephemeral environments for testing pull requests |
| 126 | +- **Multi-tenant applications**: Isolate each customer in their own sandboxed namespace |
| 127 | + |
| 128 | +## How It Works |
| 129 | + |
| 130 | +The deployment process involves four key steps: |
| 131 | + |
| 132 | +1. **Create sandboxed namespace**: Programmatically create an isolated Rivet namespace using the Cloud API or self-hosted Rivet API |
| 133 | + |
| 134 | +2. **Generate tokens**: Create the necessary authentication tokens: |
| 135 | + - **Runner token**: Authenticates the serverless runner to execute actors |
| 136 | + - **Publishable token**: Used by frontend clients to connect to actors |
| 137 | + - **Access token**: Provides API access for configuring the namespace |
| 138 | + |
| 139 | +3. **Deploy code**: Deploy the actor code and frontend programmatically to your serverless platform of choice (Vercel, Netlify, AWS Lambda, Freestyle, etc.) |
| 140 | + |
| 141 | +4. **Connect Rivet**: Configure Rivet to run actors on your deployment in your sandboxed namespace |
| 142 | + |
| 143 | +## Show Me The Code |
| 144 | + |
| 145 | +Here's a simplified example of the deployment flow using [Freestyle](https://freestyle.sh) (built specifically for this use case): |
| 146 | + |
| 147 | +```typescript |
| 148 | +import { RivetClient } from "@rivetkit/engine-api-full"; |
| 149 | +import { FreestyleSandboxes } from "freestyle-sandboxes"; |
| 150 | + |
| 151 | +async function deploy(projectDir: string) { |
| 152 | + // Step 1: Create sandboxed namespace |
| 153 | + const { project, organization } = await cloudRequest("GET", "/tokens/api/inspect"); |
| 154 | + const { namespace } = await cloudRequest( |
| 155 | + "POST", |
| 156 | + `/projects/${project}/namespaces?org=${organization}`, |
| 157 | + { displayName: `ns-${Date.now()}` } |
| 158 | + ); |
| 159 | + |
| 160 | + // Step 2: Generate tokens |
| 161 | + // ...omitted... |
| 162 | + |
| 163 | + // Step 3: Deploy to Freestyle |
| 164 | + const freestyle = new FreestyleSandboxes({ apiKey: FREESTYLE_API_KEY }); |
| 165 | + const deploymentSource = prepareDirForDeploymentSync(projectDir); |
| 166 | + await freestyle.deployWeb(deploymentSource, { |
| 167 | + envVars: { |
| 168 | + RIVET_ENDPOINT: "https://api.rivet.dev", |
| 169 | + RIVET_NAMESPACE: namespace.access.engineNamespaceName, |
| 170 | + RIVET_TOKEN: runnerToken, |
| 171 | + }, |
| 172 | + entrypoint: "src/backend/server.ts", |
| 173 | + domains: [FREESTYLE_DOMAIN], |
| 174 | + }); |
| 175 | + |
| 176 | + // Step 4: Configure Rivet to run actors on the deployment |
| 177 | + const rivet = new RivetClient({ |
| 178 | + environment: "https://api.rivet.dev", |
| 179 | + token: accessToken, |
| 180 | + }); |
| 181 | + await rivet.runnerConfigsUpsert("default", { |
| 182 | + datacenters: { |
| 183 | + "us-west-1": { |
| 184 | + serverless: { |
| 185 | + url: `https://${FREESTYLE_DOMAIN}/api/rivet`, |
| 186 | + headers: {}, |
| 187 | + maxRunners: 1000, |
| 188 | + }, |
| 189 | + }, |
| 190 | + }, |
| 191 | + namespace: namespace.access.engineNamespaceName, |
| 192 | + }); |
| 193 | +} |
| 194 | +``` |
| 195 | + |
| 196 | +Call this deployment function whenever your AI agent generates new actor code or a user requests their own sandbox environment. The entire process takes seconds and creates a fully isolated, production-ready deployment. |
| 197 | + |
| 198 | +## Getting Started |
| 199 | + |
| 200 | +To try deploying AI-generated or user-generated Rivet Actors: |
| 201 | + |
| 202 | +- Check out the [complete example on GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/ai-and-user-generated-actors-freestyle) |
| 203 | +- Read the [full documentation guide](/docs/actors/ai-and-user-generated-actors) |
| 204 | +- Sign up for [Rivet Cloud](https://dashboard.rivet.dev) or [self-host Rivet](/docs/self-hosting) |
| 205 | + |
| 206 | + |
0 commit comments