Cloudflare Serverless: Workers, D1, R2 Architecture and Troubleshooting
Compare Workers Static Assets, existing Pages sites, D1 and R2, with authentication, routing, quotas and cost.
Evidence 6 cited sources
On this page
Direct answer: As of November 2026, Cloudflare recommends Workers Static Assets for new static and full-stack deployments; existing Pages sites remain supported. A Worker can run bounded APIs alongside assets, D1 stores structured SQL data, and R2 holds objects. Together they can lower the burden of operating your own servers, but they do not guarantee zero total cost, unlimited capacity, geographically local writes or always-on availability. This is a documented design and troubleshooting guide, not a claim that XBSTACK ran a new production benchmark for these components.
1. Choose the architecture from your real requirements
A static content website may need only the build, hosting, CDN, and release verification path. Add a Worker when you have a real API requirement. Add D1 for relational records and R2 for objects only if those data stores meet your privacy, consistency, cost, and retention needs.
| Component | Appropriate responsibility | Common mistaken assumption |
|---|---|---|
| Static Astro / Workers Static Assets (new projects) or Pages (existing projects) | Deliver HTML, CSS, images and browser assets | Git push proves live rollout or versioned HTML and assets can never diverge |
| Workers | Bounded API routes, policy checks, D1/R2 integrations, selected upstream calls | Unrestricted CPU, requests, and outbound subrequests |
| D1 | Structured records, indexes, SQL queries | Every read and write automatically executes near every user |
| R2 | Images, document objects, backups with appropriate access control | Free egress means free storage, operations, and retrieval |
| AI Gateway or upstream AI API | Route and observe authorized external model calls | Model usage is free or private source data can be sent without permission |
2026 deployment-path update: Cloudflare’s Workers best practices favor Workers Static Assets for new static or full-stack sites, configured through assets.directory; existing Pages installations can continue operating. For an API-backed site, route selected /api/* requests to the Worker and let static assets serve the rest. Review run_worker_first, SPA/404 fallback and version skew: a deployed HTML version can briefly reference asset hashes absent from a different Worker version’s manifest. This is an option analysis, not a declaration that XBSTACK itself moved every component to Workers/D1/R2. Its current Pages/NAS responsibilities must be verified independently.
2. A small, explicit public read API
The following illustrative TypeScript Worker assumes a Wrangler D1 binding named DB and a table public_notes. It has not been deployed or load-tested as part of this article. It intentionally covers only public records: private orders, account information, or uploads require independent server-side authentication and resource-level authorization.
interface Env {
DB: D1Database;
}
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const url = new URL(request.url);
if (request.method !== 'GET' || url.pathname !== '/api/public-notes') {
return new Response('Not found', { status: 404 });
}
try {
const result = await env.DB
.prepare('SELECT id, title FROM public_notes ORDER BY id DESC LIMIT 10')
.all();
return Response.json(result.results ?? [], {
headers: { 'Cache-Control': 'no-store' }
});
} catch {
return Response.json({ error: 'temporarily_unavailable' }, { status: 503 });
}
}
};
This sample makes the boundaries inspectable: a read-only SQL query, an explicit route and method, a meaningful HTTP failure state, and no accidental echoing of database errors. A production API additionally needs request budgets, redacted logging, schema validation, and appropriate abuse protection. Compiling TypeScript is not proof of correct operation under production data volumes or quotas.
3. D1 consistency: a replica is not a local write database
D1’s primary database handles writes. Optional global read replicas can lower read latency for some regions, but they require the D1 Sessions API. Without sessions, queries continue to execute against the primary. A read replica does not make every user’s write local.
For read-after-write requirements, keep logically related statements in a session, carry the bookmark across requests where necessary, and select the session constraint that matches the application. Authentication, transactions, idempotency, and recovery for money or other critical state remain business responsibilities. An optimistic UI update is not evidence of database consistency.
4. Account for limits and costs instead of writing “free forever”
Cloudflare’s current Workers limits specify daily requests, CPU time, subrequests, and other constraints by plan. The Free plan is useful for prototypes and some smaller websites, but it is not an unlimited compute environment. Heavy synchronous model inference may be unsuitable for a conventional Worker request.
September 2026 D1 enforcement update: Beginning September 1, 2026, Cloudflare enforces daily D1 row-read and row-write limits on the Workers Free plan. Once a limit is exceeded, subsequent affected queries fail until the UTC reset; indexes can reduce unnecessary row reads. Record row-read and row-write counts and test quota-exhaustion handling instead of assuming Free-tier D1 silently scales. See the official D1 enforcement changelog. This is an official policy verification, not an XBSTACK load-test result.
R2 pricing separates storage capacity, Class A/B operations, and retrieval fees for applicable storage classes. Internet egress bandwidth is free under R2 pricing; that does not make every R2 workload free. Free allowances differ by storage class. Check the date and plan conditions of the provider’s documentation before making a budget.
| Dimension | Measure before release | Failure risk |
|---|---|---|
| Requests | Daily and peak API calls, 429/5xx rate | Exhausted quota, upstream throttling |
| Worker CPU | CPU duration and end-to-end tail latency | 1102 errors or timeouts |
| D1 | Reads, writes, storage growth, indexes, sessions | Outdated reads, write bottlenecks |
| R2 | Stored GB-month, operation classes, storage tier | Billing surprise, exposed objects |
| AI | Input/output tokens, retries, external calls | Model bills, private-data transfer |
| Deployment | Commit SHA, public HTML, sitemap and rollback | Repo updated while CDN still serves the old version |
A fair VPS/Cloudflare comparison also measures TLS, cache hits/misses, actual database location, and data transfer. Claims such as “10–50 ms cold starts,” “infinite automatic scaling,” or “zero maintenance” need independent conditions and measurements. They are not default characteristics of every application.
5. Troubleshooting with reproducible checks
Worker 1102 or CPU limit exceeded
Inspect the exact request, runtime error, CPU metric and subrequest usage. Move CPU-intensive work to asynchronous queues or another runtime when appropriate; benchmark the same input and target load. Upgrading a plan without diagnosis is not proof that a logical loop or workload problem is fixed.
D1 read-after-write shows stale data
Separate stale application caches, unsuccessful writes and read-replica consistency. Record the query order, transaction boundary, session bookmark and version. Verify the Sessions API behavior instead of adding an arbitrary sleep or showing success before a write is acknowledged.
R2 returns 403 or an object is missing
Verify the binding name, bucket permissions, object key, public-access configuration and signed URL validity. Keep private objects private; broad public-read exposure is not a legitimate workaround for broken authorization.
The Git push succeeded, but the public page is unchanged
Examine the actual deployment trigger and commit, generated HTML, CDN response, canonical/hreflang, static assets and sitemap. A source change is not a verified live deployment. Search notifications should follow confirmed public deployment, not the moment a build or push command exits successfully.
6. Preproduction acceptance checklist
- Verify the actual Wrangler/Pages bindings, environment-specific settings and least privilege. Never embed secrets in static page assets.
- Test success, empty output, malformed input, 401/403, 429/500 and network loss in a preview environment.
- Check D1 primary/session behavior and resource-level authorization; verify R2 storage class and access policy.
- Measure p50/p95 latency and cost for real target regions and workloads. Mark unrun tests as not tested.
- Protect historical URLs, validate build and internal links, check sitemap/canonical and verify exact live deployment before submitting URLs.
- Send source material to external AI services only within the user’s applicable consent and data policies.
Conclusion: this bilingual article is worth maintaining as an independent architecture and failure-boundary guide. Without a clearly equivalent replacement it should remain at its current URLs rather than be deleted or redirected.
Related reading
Next step: continue the Agent system
Full decision path →Choose the next architecture, tool, memory, evaluation, security, or production decision instead of starting over.
DISCUSSION
Questions, verification and corrections
Sign in to comment. Every new comment is reviewed before publication; while pending, it is visible only to you and the administrator.