All skills
openai avatar

/cloudflare-deploy

@bf9e226 official
by openaiopenai/skills28k stars
1,891

Deploy applications and infrastructure to Cloudflare using Workers, Pages, and related platform services. Use when the user asks to deploy, host, publish, or set up a project on Cloudflare.

Use this Skill: https://skilld.dev/gh/openai/skills/cloudflare-deploy

This session only. Nothing lands on disk.

referencesdurable-objectspatterns.md

≈1.7k tokens on demand. Your agent reads this file only when SKILL.md points to it.

Durable Objects Patterns

When to Use Which Pattern

Need Pattern ID Strategy
Rate limit per user/IP Rate Limiting idFromName(identifier)
Mutual exclusion Distributed Lock idFromName(resource)
>1K req/s throughput Sharding newUniqueId() or hash
Real-time updates WebSocket Collab idFromName(room)
User sessions Session Management idFromName(sessionId)
Background cleanup Alarm-based Any

RPC vs fetch()

RPC (compat ≥2024-04-03): Type-safe, simpler, default for new projects
fetch(): Legacy compat, HTTP semantics, proxying

const count = await stub.increment();  // RPC
const count = await (await stub.fetch(req)).json();  // fetch()

Sharding (High Throughput)

Single DO ~1K req/s max. Shard for higher throughput:

export default {
  async fetch(req: Request, env: Env): Promise<Response> {
    const userId = new URL(req.url).searchParams.get("user");
    const hash = hashCode(userId) % 100;  // 100 shards
    const id = env.COUNTER.idFromName(`shard:${hash}`);
    return env.COUNTER.get(id).fetch(req);
  }
};

function hashCode(str: string): number {
  let hash = 0;
  for (let i = 0; i < str.length; i++) hash = ((hash << 5) - hash) + str.charCodeAt(i);
  return Math.abs(hash);
}

Decisions:

  • Shard count: 10-1000 typical (start with 100, measure, adjust)
  • Shard key: User ID, IP, session - must distribute evenly (use hash)
  • Aggregation: Coordinator DO or external system (D1, R2)

Rate Limiting

async checkLimit(key: string, limit: number, windowMs: number): Promise<boolean> {
  const req = this.ctx.storage.sql.exec("SELECT COUNT(*) as count FROM requests WHERE key = ? AND timestamp > ?", key, Date.now() - windowMs).one();
  if (req.count >= limit) return false;
  this.ctx.storage.sql.exec("INSERT INTO requests (key, timestamp) VALUES (?, ?)", key, Date.now());
  return true;
}

Distributed Lock

private held = false;
async acquire(timeoutMs = 5000): Promise<boolean> {
  if (this.held) return false;
  this.held = true;
  await this.ctx.storage.setAlarm(Date.now() + timeoutMs);
  return true;
}
async release() { this.held = false; await this.ctx.storage.deleteAlarm(); }
async alarm() { this.held = false; }  // Auto-release on timeout

Hibernation-Aware Pattern

Preserve state across hibernation:

async fetch(req: Request): Promise<Response> {
  const [client, server] = Object.values(new WebSocketPair());
  const userId = new URL(req.url).searchParams.get("user");
  server.serializeAttachment({ userId });  // Survives hibernation
  this.ctx.acceptWebSocket(server, ["room:lobby"]);
  server.send(JSON.stringify({ type: "init", state: this.ctx.storage.kv.get("state") }));
  return new Response(null, { status: 101, webSocket: client });
}

async webSocketMessage(ws: WebSocket, msg: string) {
  const { userId } = ws.deserializeAttachment();  // Retrieve after wake
  const state = this.ctx.storage.kv.get("state") || {};
  state[userId] = JSON.parse(msg);
  this.ctx.storage.kv.put("state", state);
  for (const c of this.ctx.getWebSockets("room:lobby")) c.send(msg);
}

Real-time Collaboration

Broadcast updates to all connected clients:

async webSocketMessage(ws: WebSocket, msg: string) {
  const data = JSON.parse(msg);
  this.ctx.storage.kv.put("doc", data.content);  // Persist
  for (const c of this.ctx.getWebSockets()) if (c !== ws) c.send(msg);  // Broadcast
}

WebSocket Reconnection

Client-side (exponential backoff):

class ResilientWS {
  private delay = 1000;
  connect(url: string) {
    const ws = new WebSocket(url);
    ws.onclose = () => setTimeout(() => {
      this.connect(url);
      this.delay = Math.min(this.delay * 2, 30000);
    }, this.delay);
  }
}

Server-side (cleanup on close):

async webSocketClose(ws: WebSocket, code: number, reason: string, wasClean: boolean) {
  const { userId } = ws.deserializeAttachment();
  this.ctx.storage.sql.exec("UPDATE users SET online = false WHERE id = ?", userId);
  for (const c of this.ctx.getWebSockets()) c.send(JSON.stringify({ type: "user_left", userId }));
}

Session Management

async createSession(userId: string, data: object): Promise<string> {
  const id = crypto.randomUUID(), exp = Date.now() + 86400000;
  this.ctx.storage.sql.exec("INSERT INTO sessions VALUES (?, ?, ?, ?)", id, userId, JSON.stringify(data), exp);
  await this.ctx.storage.setAlarm(exp);
  return id;
}

async getSession(id: string): Promise<object | null> {
  const row = this.ctx.storage.sql.exec("SELECT data FROM sessions WHERE id = ? AND expires_at > ?", id, Date.now()).one();
  return row ? JSON.parse(row.data) : null;
}

async alarm() { this.ctx.storage.sql.exec("DELETE FROM sessions WHERE expires_at <= ?", Date.now()); }

Multiple Events (Single Alarm)

Queue pattern to schedule multiple events:

async scheduleEvent(id: string, runAt: number) {
  await this.ctx.storage.put(`event:${id}`, { id, runAt });
  const curr = await this.ctx.storage.getAlarm();
  if (!curr || runAt < curr) await this.ctx.storage.setAlarm(runAt);
}

async alarm() {
  const events = await this.ctx.storage.list({ prefix: "event:" }), now = Date.now();
  let next = null;
  for (const [key, ev] of events) {
    if (ev.runAt <= now) {
      await this.processEvent(ev);
      await this.ctx.storage.delete(key);
    } else if (!next || ev.runAt < next) next = ev.runAt;
  }
  if (next) await this.ctx.storage.setAlarm(next);
}

Graceful Cleanup

Use ctx.waitUntil() to complete work after response:

async myMethod() {
  const response = { success: true };
  this.ctx.waitUntil(this.ctx.storage.sql.exec("DELETE FROM old_data WHERE timestamp < ?", cutoff));
  return response;
}

Best Practices

  • Design: Use idFromName() for coordination, newUniqueId() for sharding, minimize constructor work
  • Storage: Prefer SQLite, batch with transactions, set alarms for cleanup, use PITR before risky ops
  • Performance: ~1K req/s per DO max - shard for more, cache in memory, use alarms for deferred work
  • Reliability: Handle 503 with retry+backoff, design for cold starts, test migrations with --dry-run
  • Security: Validate inputs in Workers, rate limit DO creation, use jurisdiction for compliance

See Also

  • API - ctx methods, WebSocket handlers
  • Gotchas - Hibernation caveats, common errors
  • DO Storage - Storage patterns and transactions

Source: SKILL.md on GitHub

2 warnings17d5 checks · Risk SAFE
  • Gen Agent Trust Hub17d

    This skill provides comprehensive guidance for deploying and managing infrastructure on the Cloudflare platform. It includes extensive educational material on secure development practices, such as preventing SQL injection and managing secrets effectively. No malicious patterns or security risks were identified.

  • Socket17d

    2 alerts: gptAnomaly

  • Snyk17d

    Risk: LOW · No issues

  • Runlayer7mo

    310/310 files flagged

  • ZeroLeaks5mo

    Score: 93/100 · 2 sections analyzed

Signed by skilld at bf9e226. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub 2 months ago.

Activeupdated 8 months ago

README badge

README badge for openai/skills/cloudflare-deploy

Deploys applications and infrastructure to Cloudflare's platform, including Workers, Pages, D1, R2, Durable Objects, KV, and other services. Use decision trees to route to the right Cloudflare product based on compute, storage, AI, networking, security, or media needs.

Generated from the current SKILL.md.

Does this skill cover all Cloudflare products?
The skill is a consolidated index covering compute, storage, AI, networking, security, media, and developer tools on Cloudflare. It uses decision trees to route you to the right product reference, then loads detailed guidance for that product.
What authentication is required before deploying?
Run `npx wrangler whoami` to check if authenticated. For local deployment, use `wrangler login` (one-time OAuth). For CI/CD, set the `CLOUDFLARE_API_TOKEN` environment variable.
What should I do if deployment fails due to network issues?
Rerun the deploy with `sandbox_permissions=require_escalated` to grant elevated network access, which is required for outbound requests to Cloudflare during deployment.
How long does a Cloudflare deployment typically take?
Deployments may take several minutes. Use appropriate timeout values in your configuration or CI/CD environment.

Generated from the current SKILL.md. These answers refresh after source changes.