| | |

Cloudflare 20 ☁️ Cheatsheet

⏱️ Estimated read: 10 min | |

A dense reference for the whole platform: CLI, config, bindings, storage, AI, security, observability, and the limits that decide the architecture. Limits and prices change — verify before capacity planning.


CLI

CommandDoes
wrangler initScaffold a project
wrangler devLocal runtime with bindings
wrangler dev --remoteRun on the edge, real bindings
wrangler deployPublish to production
wrangler versions uploadUpload without deploying
wrangler deployments listRollback points
wrangler rollback [id]Revert to a version
wrangler tail [name]Live log stream
wrangler secret put KEYEncrypted env var
wrangler typesGenerate Env from config
wrangler whoamiAccount and token check
# Local first, always; --remote only when a binding cannot be simulated
wrangler dev

# Real bindings, real data — use a staging namespace
wrangler dev --remote

# Failures only, piped through jq
wrangler tail api --format json | jq 'select(.outcome != "ok")'

Config Anatomy

// wrangler.jsonc — the modern form; toml still works
{
  "name": "api",
  "main": "src/index.ts",
  "compatibility_date": "2025-04-01",   // pins runtime behaviour
  "compatibility_flags": ["nodejs_compat"],  // Node builtins
  "observability": { "enabled": true, "head_sampling_rate": 1 },

  "vars": { "ENV": "production" },       // plaintext, in the bundle
  // secrets go through `wrangler secret put`, never here

  "kv_namespaces": [{ "binding": "CACHE", "id": "abc123" }],
  "r2_buckets":    [{ "binding": "BUCKET", "bucket_name": "uploads" }],
  "d1_databases":  [{ "binding": "DB", "database_name": "app", "database_id": "uuid" }],
  "ai":            { "binding": "AI" },
  "vectorize":     [{ "binding": "VECTORIZE", "index_name": "docs" }],

  "durable_objects": { "bindings": [{ "name": "ROOM", "class_name": "Room" }] },
  "migrations": [{ "tag": "v1", "new_sqlite_classes": ["Room"] }],

  "queues": {
    "producers": [{ "binding": "JOBS", "queue": "jobs" }],
    "consumers": [{ "queue": "jobs", "max_batch_size": 10, "max_retries": 3 }]
  },

  "triggers": { "crons": ["0 * * * *"] },   // hourly
  "tail_consumers": [{ "service": "log-sink" }]
}

Bindings

BindingAccessGuarantee
KVenv.CACHEEventually consistent, global
D1env.DBSQLite, strongly consistent per DB
R2env.BUCKETS3-compatible, zero egress
Durable Objectenv.ROOMSingle instance, serialized
Queue producerenv.JOBSAt-least-once delivery
Hyperdriveenv.HYPERDRIVEPooled Postgres/MySQL
Workers AIenv.AINo API key, metered in Neurons
Vectorizeenv.VECTORIZENearest-neighbour over vectors
Analytics Engineenv.METRICSWrite-only, SQL-queryable
Service bindingenv.OTHERWorker-to-Worker, no egress
Dispatcherenv.DISPATCHERTenant Worker by name
// Service binding: a fetch to another Worker with no public hostname
const res = await env.OTHER.fetch("https://internal/users", {
  method: "POST",
  body: JSON.stringify({ id }),
});

Storage Matrix

StoreModelConsistencyBest For
KVKey-valueEventual (~60 s)Config, sessions, flags
D1RelationalStrong per DBSmall relational data
R2ObjectStrong per objectFiles, backups, media
DOObject + SQLiteSerializableRooms, carts, counters
QueuesLogAt-least-onceAsync work, fan-out
VectorizeANN indexEventual on writeRAG retrieval
HyperdrivePoolDepends on DBExisting Postgres
┌──────────────────────────────────────────────────────────┐
│  PICKING A STORE                                         │
│                                                          │
│  read-heavy, tolerate staleness      ──► KV              │
│  need JOIN or a WHERE clause         ──► D1 / Hyperdrive │
│  bytes with a key, any size          ──► R2              │
│  one writer must serialize           ──► Durable Object  │
│  work that outlives the request      ──► Queues          │
│  similarity search                   ──► Vectorize       │
│                                                          │
│  Wrong pick is a correctness bug, not a performance one. │
└──────────────────────────────────────────────────────────┘

KV

// Read: cacheTtl is seconds of edge caching, minimum 60
const v = await env.CACHE.get("user:42", { type: "json", cacheTtl: 300 });

// Write: expirationTtl in seconds; metadata is searchable on list()
await env.CACHE.put("user:42", JSON.stringify(user), {
  expirationTtl: 3600,
  metadata: { plan: "pro" },
});

// List: cursor-paginated; never assume one page
let cursor: string | undefined;
do {
  const page = await env.CACHE.list({ prefix: "user:", cursor, limit: 1000 });
  cursor = page.cursor;
} while (cursor);
LimitValue
Value size25 MiB
Key size512 bytes
Metadata1024 bytes
Writes per key1 per second
PropagationUp to 60 s globally

D1

// Prepared statement with bound params; never interpolate user input
const row = await env.DB
  .prepare("SELECT id, email FROM users WHERE id = ?")
  .bind(id)
  .first();

// All rows, with metadata
const { results, meta } = await env.DB
  .prepare("SELECT * FROM posts WHERE author = ? LIMIT ?")
  .bind(authorId, 20)
  .all();

// Batch: one round trip, implicitly transactional
await env.DB.batch([
  env.DB.prepare("INSERT INTO posts (id, title) VALUES (?, ?)").bind(id, title),
  env.DB.prepare("UPDATE counts SET posts = posts + 1 WHERE id = ?").bind(authorId),
]);
# Migrations live in a directory; track each one in a table
wrangler d1 migrations create app add_posts
wrangler d1 migrations apply app --local
wrangler d1 migrations apply app --remote

R2

// Write with content type and custom metadata
await env.BUCKET.put(`avatars/${userId}.webp`, bytes, {
  httpMetadata: { contentType: "image/webp", cacheControl: "public, max-age=31536000" },
  customMetadata: { uploader: userId },
});

// Conditional read: send the ETag, get a 304 for free
const obj = await env.BUCKET.get(key, {
  onlyIf: req.headers,
  range: req.headers,
});
if (!obj) return new Response("not found", { status: 404 });
return new Response(obj.body, { headers: { etag: obj.httpEtag } });
ItemValue
Zero egressYes, on every plan
Storage$0.015 / GB-month
Class A (writes)$4.50 / million
Class B (reads)$0.36 / million
Single PUT5 GiB (multipart beyond)

Queues

// Producer: send one message, or a batch
await env.JOBS.send({ type: "resize", id }, { delaySeconds: 10 });
await env.JOBS.sendBatch(items.map(body => ({ body })));

// Consumer: the batch is delivered together; ack is implicit on return
export default {
  async queue(batch: MessageBatch<Job>, env: Env) {
    for (const msg of batch.messages) {
      try {
        await handle(msg.body, env);
      } catch (err) {
        msg.retry({ delaySeconds: 30 });   // explicit, not automatic
      }
    }
  },
};
SettingEffect
max_batch_sizeUp to 100 messages
max_batch_timeoutSeconds to wait for a full batch
max_retriesAttempts before the DLQ
dead_letter_queueWhere exhausted messages land

Durable Objects

export class Room extends DurableObject<Env> {
  // Input gate: every request to this instance is serialized
  async fetch(req: Request) {
    const count = (await this.ctx.storage.get<number>("count")) ?? 0;
    await this.ctx.storage.put("count", count + 1);
    return Response.json({ count: count + 1 });
  }

  // Alarms: a persisted timer, one per object
  async alarm() {
    await this.ctx.storage.deleteAll();
  }
}

// Address an instance: name it, or generate an id
const id = env.ROOM.idFromName(`room:${roomId}`);
const stub = env.ROOM.get(id);
await stub.fetch(req);
LimitValue
Address byidFromName (deterministic) or newUniqueId
Storage per object10 GB (SQLite-backed)
HibernationWebSocket objects sleep, no duration bill
ConcurrencyOne instance, serialized by design

Workers AI, Vectorize, AI Gateway

// Chat: cap output, control temperature
const { response } = await env.AI.run("@cf/meta/llama-3.1-8b-instruct", {
  messages: [{ role: "user", content: q }],
  max_tokens: 400,
  temperature: 0.2,
});

// Embeddings: batch the whole array in one call
const { data } = await env.AI.run("@cf/baai/bge-base-en-v1.5", { text: chunks });

// Streaming: hand the stream straight to the response
return new Response(await env.AI.run(model, { messages, stream: true }), {
  headers: { "content-type": "text/event-stream" },
});
// Vectorize: filter on an indexed property, before the comparison
const hits = await env.VECTORIZE.query(vec, {
  topK: 8,
  returnMetadata: "all",
  namespace: "prod",
  filter: { lang: { $eq: "en" } },
});
// Gateway: same call, one different base URL, plus cache and log metadata
fetch(`https://gateway.ai.cloudflare.com/v1/${acct}/${gw}/workers-ai/${model}`, {
  method: "POST",
  headers: {
    "content-type": "application/json",
    "cf-aig-cache-ttl": "300",                      // seconds
    "cf-aig-metadata": JSON.stringify({ feature }),  // filterable in the log
  },
  body: JSON.stringify({ messages }),
});
ModelDimensions
@cf/baai/bge-small-en-v1.5384
@cf/baai/bge-base-en-v1.5768
@cf/baai/bge-large-en-v1.51024
@cf/baai/bge-m31024
ItemValue
Workers AI free tier10,000 Neurons/day
Paid rate$0.011 / 1,000 Neurons
Vectorize topK20 with metadata, 100 ids-only
Index immutablesDimensions, metric

Agents and MCP

// One Durable Object per conversation, addressed by name
export class Support extends Agent<Env, State> {
  initialState: State = { turns: 0 };

  async onMessage(conn: Connection, raw: string) {
    this.setState({ turns: this.state.turns + 1 });   // persists + broadcasts
    conn.send(await answer(raw, this.env));
  }

  async onConnect(conn: Connection) {
    conn.send(JSON.stringify(this.state));            // replay on attach
  }
}

export default {
  fetch: (req, env, ctx) => routeAgentRequest(req, env) ?? new Response("404", { status: 404 }),
};
// MCP: the tool schema is the contract the calling model reads
this.server.tool("search_docs",
  { query: z.string(), limit: z.number().int().max(20).default(5) },
  async ({ query, limit }) => {
    const hits = await this.env.VECTORIZE.query(await embed(query), {
      topK: limit,
      filter: { tenantId: { $eq: this.props.userId } },   // scoped per caller
    });
    return { content: hits.matches.map(m => ({ type: "text" as const, text: m.metadata.text })) };
  });
TransportPathClient
SSE/sseOlder MCP clients
Streamable HTTP/mcpCurrent clients

Images and Turnstile

// Transformations: the option string is a bill — use a preset map
const PRESETS = {
  thumb: "width=200,height=200,fit=cover,quality=70,format=auto",
  hero: "width=1600,quality=80,format=auto",
};

// Turnstile: siteverify is the only place the verdict is trusted
const body = new URLSearchParams({
  secret: env.TURNSTILE_SECRET,
  response: token,
  remoteip: ip,
});
const out = await (await fetch("https://challenges.cloudflare.com/turnstile/v0/siteverify",
  { method: "POST", body })).json();

// Bind the token to the form and the session, not just to "success"
if (!out.success || out.action !== "login" || out.cdata !== session) reject();
ItemValue
Delivery URLimagedelivery.net/<hash>/<id>/<variant>
Transform path/cdn-cgi/image/<options>/<source>
Billed onUnique transformations, not requests
Turnstile token300 s, single use
Retryable errortimeout-or-duplicate

Security

# Custom rule: expression + action, first match wins
(http.request.uri.path contains "../") or (http.user_agent contains "sqlmap")

# Rate limit: key on something rotation-proof
characteristics: ["http.request.headers[\"x-api-key\"]"]
period: 60, threshold: 300, mitigation: managed_challenge
PhaseRunsUnit
L3/L4 DDoSBefore TLSAutomatic
ddos_l7HTTP layerSensitivity dial
http_request_firewall_customYour expressionsRule
http_request_firewall_managedCloudflare + OWASPRuleset id
http_ratelimitCounted historyRequest per window
Access ItemValue
Assertion headerCf-Access-Jwt-Assertion
Browser cookieCF_Authorization
JWKShttps://<team>.cloudflareaccess.com/cdn-cgi/access/certs
Service tokenCF-Access-Client-Id + -Secret
Wildcard app*.preview.example.com
Origin must notHave a public IP — use a Tunnel
# cloudflared: the catch-all is mandatory, not optional
ingress:
  - hostname: preview.example.com
    service: http://localhost:3000
  - service: http_status:404

Observability

// Tail consumer: one event per request; batch the sink write
export default {
  async tail(events: TraceItem[], env: Env, ctx: ExecutionContext) {
    const body = events.map(ev => JSON.stringify({
      script: ev.scriptName,
      outcome: ev.outcome,          // ok | exception | exceededCpu | ...
      ray: ev.event?.request?.cf?.rayId,
      errors: ev.exceptions.map(e => `${e.name}: ${e.message}`),
    })).join("\n");
    ctx.waitUntil(env.BUCKET.put(`trace/${Date.now()}.ndjson`, body));
  },
};
// Analytics Engine: tenant in indexes, because WHERE pushes down on it
env.METRICS.writeDataPoint({
  indexes: [tenantId],
  blobs: [path, method, tenantId, outcome],
  doubles: [durationMs, isError, bytes],
});
-- Billing-grade count: the sample interval is not optional
SELECT blob3 AS tenant, sum(_sample_interval) AS requests,
       quantile(0.99)(double1) AS p99
FROM request_metrics
WHERE timestamp > NOW() - INTERVAL '1' DAY
GROUP BY tenant
SurfaceRetentionLatency
wrangler tailSessionLive
Workers Logs3 daysSeconds
Tail WorkerYou choosePer request
LogpushYour bucketMinutes
Analytics Engine90 daysBatched

Workers for Platforms

// Router: hostname → tenant stub. The stub is a Fetcher.
const stub = env.DISPATCHER.get(tenant.scriptName);
return stub.fetch(req, { headers: { "x-tenant-id": tenant.id } });
# Upload a tenant script with its own limits and tags
curl -X PUT "https://api.cloudflare.com/client/v4/accounts/$ACCT/workers/dispatch/namespaces/$NS/scripts/$NAME" \
  -H "Authorization: Bearer $CF_TOKEN" \
  -F 'metadata={"main_module":"index.mjs","compatibility_date":"2025-04-01","limits":{"cpu_ms":50,"subrequests":20},"tags":["plan:pro"]};type=application/json' \
  -F 'index.mjs=@./index.mjs;type=application/javascript+module'
ConceptMeaning
Dispatch namespaceContainer for tenant Workers
limits.cpu_msPer-tenant CPU ceiling
limits.subrequestsPer-tenant fetch ceiling
tagsEchoed on every trace item
Outbound WorkerGates every tenant subrequest

Limits

ItemFreePaid
CPU time10 ms30 s default, up to 5 min
Memory128 MB128 MB
Script size3 MB10 MB
Subrequests501,000
Workers100500
Request body100 MB500 MB
Simultaneous connections66

Error Codes

CodeMeaning
1101Uncaught exception in the Worker
1102CPU limit exceeded
1015Rate limited
1020Blocked by a firewall rule
1033Tunnel error
520Origin returned an unknown response
522Origin connection timed out
523Origin unreachable
524Origin took longer than 100 s
526Invalid origin certificate

Gotchas

SymptomCauseFix
Env var undefinedSet in vars but not deployedwrangler secret put or redeploy
Bindings missing in devwrangler.toml not jsonc, or no --remoteRegenerate Env with wrangler types
Stale KV readEventual consistencycacheTtl minimum is 60 s
DO resets stateNot in migrationsAdd new_sqlite_classes
Queue redeliversHandler threw or did not ackmsg.ack() or return normally
Subrequest limit hitLoops calling fetchBatch, or use a service binding
Cache never hitsSet-Cookie or Authorization presentCache-Control: public and no cookie
Local time in cronCron is UTCConvert explicitly
Secret leaked in logsconsole.log(env)Log field names, never the object
CPU exceeded silentlyNothing runs after the killAlert on outcome, not logs

Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!