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.
Quick How-To Guides & Fast FixesNeed a quick fix or step-by-step solution? Browse our fast answers on HowTo.KandZ.me:
# 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")'
// 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
Store
Model
Consistency
Best For
KV
Key-value
Eventual (~60 s)
Config, sessions, flags
D1
Relational
Strong per DB
Small relational data
R2
Object
Strong per object
Files, backups, media
DO
Object + SQLite
Serializable
Rooms, carts, counters
Queues
Log
At-least-once
Async work, fan-out
Vectorize
ANN index
Eventual on write
RAG retrieval
Hyperdrive
Pool
Depends on DB
Existing 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);
Limit
Value
Value size
25 MiB
Key size
512 bytes
Metadata
1024 bytes
Writes per key
1 per second
Propagation
Up 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 } });
Item
Value
Zero egress
Yes, on every plan
Storage
$0.015 / GB-month
Class A (writes)
$4.50 / million
Class B (reads)
$0.36 / million
Single PUT
5 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
}
}
},
};
Setting
Effect
max_batch_size
Up to 100 messages
max_batch_timeout
Seconds to wait for a full batch
max_retries
Attempts before the DLQ
dead_letter_queue
Where 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);
Limit
Value
Address by
idFromName (deterministic) or newUniqueId
Storage per object
10 GB (SQLite-backed)
Hibernation
WebSocket objects sleep, no duration bill
Concurrency
One 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 }),
});
Model
Dimensions
@cf/baai/bge-small-en-v1.5
384
@cf/baai/bge-base-en-v1.5
768
@cf/baai/bge-large-en-v1.5
1024
@cf/baai/bge-m3
1024
Item
Value
Workers AI free tier
10,000 Neurons/day
Paid rate
$0.011 / 1,000 Neurons
Vectorize topK
20 with metadata, 100 ids-only
Index immutables
Dimensions, 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 })) };
});
Transport
Path
Client
SSE
/sse
Older MCP clients
Streamable HTTP
/mcp
Current 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();
Item
Value
Delivery URL
imagedelivery.net/<hash>/<id>/<variant>
Transform path
/cdn-cgi/image/<options>/<source>
Billed on
Unique transformations, not requests
Turnstile token
300 s, single use
Retryable error
timeout-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
// 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
Surface
Retention
Latency
wrangler tail
Session
Live
Workers Logs
3 days
Seconds
Tail Worker
You choose
Per request
Logpush
Your bucket
Minutes
Analytics Engine
90 days
Batched
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'
Concept
Meaning
Dispatch namespace
Container for tenant Workers
limits.cpu_ms
Per-tenant CPU ceiling
limits.subrequests
Per-tenant fetch ceiling
tags
Echoed on every trace item
Outbound Worker
Gates every tenant subrequest
Limits
Item
Free
Paid
CPU time
10 ms
30 s default, up to 5 min
Memory
128 MB
128 MB
Script size
3 MB
10 MB
Subrequests
50
1,000
Workers
100
500
Request body
100 MB
500 MB
Simultaneous connections
6
6
Error Codes
Code
Meaning
1101
Uncaught exception in the Worker
1102
CPU limit exceeded
1015
Rate limited
1020
Blocked by a firewall rule
1033
Tunnel error
520
Origin returned an unknown response
522
Origin connection timed out
523
Origin unreachable
524
Origin took longer than 100 s
526
Invalid origin certificate
Gotchas
Symptom
Cause
Fix
Env var undefined
Set in vars but not deployed
wrangler secret put or redeploy
Bindings missing in dev
wrangler.toml not jsonc, or no --remote
Regenerate Env with wrangler types
Stale KV read
Eventual consistency
cacheTtl minimum is 60 s
DO resets state
Not in migrations
Add new_sqlite_classes
Queue redelivers
Handler threw or did not ack
msg.ack() or return normally
Subrequest limit hit
Loops calling fetch
Batch, or use a service binding
Cache never hits
Set-Cookie or Authorization present
Cache-Control: public and no cookie
Local time in cron
Cron is UTC
Convert explicitly
Secret leaked in logs
console.log(env)
Log field names, never the object
CPU exceeded silently
Nothing runs after the kill
Alert 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