IntegrationsUpdated 2026-03-18
Cloudflare Workers Integration
Deploy RetainDB on Cloudflare Workers for edge-optimized performance with queues and Durable Objects.
Applies to: Cloudflare Workers
Deploy RetainDB-powered applications on Cloudflare Workers for global low-latency performance.
Installation
bash
npm install @retaindb/sdkBasic Worker Setup
typescript
// src/index.ts
import { RetainDBClient } from "@retaindb/sdk";
export interface Env {
RETAINDB_API_KEY: string;
}
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const client = new RetainDBClient({
apiKey: env.RETAINDB_API_KEY,
});
const url = new URL(request.url);
if (url.pathname === "/search" && request.method === "POST") {
const { userId, query } = await request.json();
const results = await client.memory.search({
user_id: userId,
query,
top_k: 5,
});
return Response.json(results);
}
if (url.pathname === "/add" && request.method === "POST") {
const { userId, content, memoryType } = await request.json();
await client.memory.add({
user_id: userId,
content,
memory_type: memoryType || "event",
});
return Response.json({ success: true });
}
return new Response("Not Found", { status: 404 });
},
};Edge Queue Pattern
For high-throughput applications, use Cloudflare Queues:
typescript
// src/queue.ts
export interface QueueMessage {
action: "add" | "search";
userId: string;
content?: string;
query?: string;
memoryType?: string;
}
export default {
async queue(batch: MessageBatch<QueueMessage>, env: Env): Promise<void> {
const client = new RetainDBClient({
apiKey: env.RETAINDB_API_KEY,
});
for (const message of batch.messages) {
try {
if (message.body.action === "add") {
await client.memory.add({
user_id: message.body.userId,
content: message.body.content!,
memory_type: message.body.memoryType || "event",
});
}
// Handle other actions
message.ack();
} catch (error) {
console.error("Failed to process:", error);
message.retry();
}
}
},
};Worker Configuration
toml
# wrangler.toml
name = "retaindb-worker"
main = "src/index.ts"
compatibility_date = "2024-01-01"
[queues]
producers = [{ binding = "QUEUE", queue = "retaindb-writes" }]
consumers = [{ queue = "retaindb-writes", service = "retaindb-worker" }]Sending to Queue
typescript
// In your worker
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const { userId, content } = await request.json();
// Send to queue instead of direct call
await env.QUEUE.send({
action: "add",
userId,
content,
});
return Response.json({ queued: true });
},
};Durable Objects for Sessions
Use Durable Objects for session management:
typescript
// src/session.ts
export class SessionDO implements DurableObject {
private state: DurableObjectState;
private memory: string[] = [];
constructor(state: DurableObjectState, env: Env) {
this.state = state;
}
async fetch(request: Request): Promise<Response> {
const url = new URL(request.url);
// Add to session memory
if (url.pathname === "/memory" && request.method === "POST") {
const { content } = await request.json();
this.memory.push(content);
return Response.json({ stored: true });
}
// Get session memory
if (url.pathname === "/memory" && request.method === "GET") {
return Response.json({ memory: this.memory });
}
return new Response("Not Found", { status: 404 });
}
}Caching with Cache API
Cache search results at the edge:
typescript
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const url = new URL(request.url);
const cacheKey = new Request(url.toString(), request);
// Check cache first
const cached = await caches.default.match(cacheKey);
if (cached) return cached;
const client = new RetainDBClient({ apiKey: env.RETAINDB_API_KEY });
// ... perform search ...
const results = await client.memory.search({ ... });
// Cache the response
const response = Response.json(results);
response.headers.set("Cache-Control", "s-maxage=300");
await caches.default.put(cacheKey, response.clone());
return response;
},
};Environment Variables
bash
# wrangler.toml
[vars]
RETAINDB_API_KEY = "rdb_..."
# Or use secrets
# wrangler secret put RETAINDB_API_KEYTypeScript Configuration
typescript
// tsconfig.json
{
"compilerOptions": {
"target": "ES2022",
"module": "ES2022",
"moduleResolution": "node"
}
}Best Practices
1. Use Queue for Writes
typescript
// Don't do direct writes in request handler
// Do:
await env.QUEUE.send({ action: "add", userId, content });
// Instead of:
// await client.memory.add({ user_id: userId, content });2. Cache Responses
typescript
const cached = await caches.default.match(request);
if (cached) return cached;3. Handle Edge Limits
typescript
// Workers have CPU time limits
// Offload heavy operations to queue
if (heavyOperation) {
await env.QUEUE.send({ ... });
return Response.json({ processing: true });
}Complete Example
typescript
// src/index.ts
import { RetainDBClient } from "@retaindb/sdk";
export interface Env {
RETAINDB_API_KEY: string;
QUEUE: Queue;
}
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const client = new RetainDBClient({ apiKey: env.RETAINDB_API_KEY });
const { searchParams } = new URL(request.url);
const userId = searchParams.get("userId");
if (!userId) {
return Response.json({ error: "userId required" }, { status: 400 });
}
// Check cache
const cacheKey = new Request(request.url);
const cached = await caches.default.match(cacheKey);
if (cached) return cached;
// Search RetainDB
const results = await client.memory.search({
user_id: userId,
query: searchParams.get("query") || "",
top_k: 5,
});
// Cache for 5 minutes
const response = Response.json(results);
response.headers.set("Cache-Control", "s-maxage=300");
await caches.default.put(cacheKey, response.clone());
return response;
},
};Next step
- SDK Quickstart — Full SDK guide
- Cloudflare Workers Docs — Platform docs
- Cloudflare Queues — Queue docs
Was this page helpful?
Your feedback helps us prioritize docs improvements weekly.