Architecture
Deployment
Deploy autonomous businesses to production
Deploy your autonomous business to production using Cloudflare Workers and the .do platform.
Deployment Architecture
Business-as-Code applications deploy as:
- Cloudflare Workers - Application logic
- Cloudflare D1 - SQL database
- Cloudflare R2 - Object storage
- Cloudflare KV - Key-value cache
- Cloudflare Durable Objects - Stateful coordination
Quick Deployment
# Install Wrangler CLI
npm install -g wrangler
# Login to Cloudflare
wrangler login
# Deploy your business
cd my-business
wrangler deployProject Structure
my-business/
├── src/
│ ├── index.ts # Main entry point
│ ├── handlers/ # Event handlers
│ ├── workflows/ # Business workflows
│ └── ai/ # AI logic
├── wrangler.jsonc # Cloudflare config
├── package.json
└── tsconfig.jsonConfiguration
wrangler.jsonc:
{
"name": "my-business",
"main": "src/index.ts",
"compatibility_date": "2025-01-01",
"node_compat": true,
// Bindings
"vars": {
"ENVIRONMENT": "production"
},
"kv_namespaces": [
{
"binding": "CACHE",
"id": "YOUR_KV_ID"
}
],
"d1_databases": [
{
"binding": "DB",
"database_name": "my-business-db",
"database_id": "YOUR_D1_ID"
}
],
"r2_buckets": [
{
"binding": "STORAGE",
"bucket_name": "my-business-assets"
}
],
"ai": {
"binding": "AI"
}
}Environment Variables
# .env.production
DATABASE_URL=your-database-url
API_KEY=your-api-key
STRIPE_SECRET_KEY=sk_live_xxx
SENDGRID_API_KEY=SG.xxxStore secrets securely:
# Add secrets
wrangler secret put DATABASE_URL
wrangler secret put STRIPE_SECRET_KEY
wrangler secret put SENDGRID_API_KEYCI/CD Pipeline
GitHub Actions
.github/workflows/deploy.yml:
name: Deploy
on:
push:
branches: [main]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: '18'
- name: Install dependencies
run: npm install
- name: Run tests
run: npm test
- name: Deploy to Cloudflare
uses: cloudflare/wrangler-action@v3
with:
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}Monitoring
Analytics
// Track metrics
analytics.track('order.created', {
orderId: order.$id,
amount: order.totalPrice,
customer: order.customer.$id,
})Error Tracking
// Sentry integration
import * as Sentry from '@sentry/cloudflare'
Sentry.init({
dsn: 'your-sentry-dsn',
environment: 'production',
})
try {
await processOrder(order)
} catch (error) {
Sentry.captureException(error)
throw error
}Logging
// Structured logging
console.log(
JSON.stringify({
level: 'info',
message: 'Order processed',
orderId: order.$id,
duration: Date.now() - start,
})
)Best Practices
1. Use Environment-Specific Config
const config = {
development: {
apiUrl: 'http://localhost:8787',
debug: true,
},
production: {
apiUrl: 'https://api.yourbusiness.com',
debug: false,
},
}
const env = process.env.ENVIRONMENT || 'development'
export default config[env]2. Health Checks
// Health check endpoint
app.get('/health', async (c) => {
const checks = {
database: await checkDatabase(),
cache: await checkCache(),
ai: await checkAI(),
}
const healthy = Object.values(checks).every((c) => c.status === 'ok')
return c.json(
{
status: healthy ? 'healthy' : 'unhealthy',
checks,
},
healthy ? 200 : 503
)
})3. Gradual Rollouts
// Feature flags
const features = {
newPricingEngine: {
enabled: true,
rolloutPercent: 10, // 10% of users
},
}
if (shouldEnableFeature('newPricingEngine', user)) {
// Use new pricing
} else {
// Use old pricing
}4. Database Migrations
# Create migration
wrangler d1 migrations create my-business-db add_new_field
# Apply migration
wrangler d1 migrations apply my-business-dbPerformance Optimization
1. Caching
// Cache expensive operations
const cached = await kv.get(`product:${id}`)
if (cached) return JSON.parse(cached)
const product = await db.get($.Product, id)
await kv.put(`product:${id}`, JSON.stringify(product), {
expirationTtl: 3600,
})
return product2. Batch Operations
// Batch database queries
const [orders, products, customers] = await Promise.all([db.list($.Order, query), db.list($.Product, query), db.list($.Person, query)])3. Edge Caching
// Cache at edge
export default {
async fetch(request, env, ctx) {
const cache = caches.default
let response = await cache.match(request)
if (!response) {
response = await handleRequest(request, env)
ctx.waitUntil(cache.put(request, response.clone()))
}
return response
},
}Summary
Deploy Business-as-Code applications with:
- Cloudflare Workers for global distribution
- CI/CD for automated deployments
- Monitoring for observability
- Feature flags for safe rollouts
- Caching for performance
Next: Scalability →