Cloudflare Serverless: Workers, D1, R2 Architecture and Troubleshooting

Compare Workers Static Assets, existing Pages sites, D1 and R2, with authentication, routing, quotas and cost.

Published · 2026-01-215 min readXBSTACK
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.

ComponentAppropriate responsibilityCommon mistaken assumption
Static Astro / Workers Static Assets (new projects) or Pages (existing projects)Deliver HTML, CSS, images and browser assetsGit push proves live rollout or versioned HTML and assets can never diverge
WorkersBounded API routes, policy checks, D1/R2 integrations, selected upstream callsUnrestricted CPU, requests, and outbound subrequests
D1Structured records, indexes, SQL queriesEvery read and write automatically executes near every user
R2Images, document objects, backups with appropriate access controlFree egress means free storage, operations, and retrieval
AI Gateway or upstream AI APIRoute and observe authorized external model callsModel 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.

DimensionMeasure before releaseFailure risk
RequestsDaily and peak API calls, 429/5xx rateExhausted quota, upstream throttling
Worker CPUCPU duration and end-to-end tail latency1102 errors or timeouts
D1Reads, writes, storage growth, indexes, sessionsOutdated reads, write bottlenecks
R2Stored GB-month, operation classes, storage tierBilling surprise, exposed objects
AIInput/output tokens, retries, external callsModel bills, private-data transfer
DeploymentCommit SHA, public HTML, sitemap and rollbackRepo 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

  1. Verify the actual Wrangler/Pages bindings, environment-specific settings and least privilege. Never embed secrets in static page assets.
  2. Test success, empty output, malformed input, 401/403, 429/500 and network loss in a preview environment.
  3. Check D1 primary/session behavior and resource-level authorization; verify R2 storage class and access policy.
  4. Measure p50/p95 latency and cost for real target regions and workloads. Mark unrun tests as not tested.
  5. Protect historical URLs, validate build and internal links, check sitemap/canonical and verify exact live deployment before submitting URLs.
  6. 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.

Next step: continue the Agent system

Full decision path →

Choose the next architecture, tool, memory, evaluation, security, or production decision instead of starting over.

Next problem in the same topicWhy More Website Articles Still Bring No Traffic: A Real 592-URL AuditWhy can a personal website publish hundreds of pages without meaningful organic traffic? This XBSTACK field audit examines 592 sitemap URLs, six orphaned routes, crawl and index evidence, and a real Cloudflare release.Next problem in the same topicWhy Personal-Site 404 Traffic Spiked: External Links, Cloudflare, and Astro RoutesAn XBSTACK operations review showing how malformed external links, legacy paths, and Cloudflare route handling created rising 404 traffic, with an audit and redirect workflow.Next problem in the same topicZhuzhiliao (Zhuzhiniao) Online: Play the Bamboo Cicada GamePlay Zhuzhiliao (Zhuzhiniao) online in your browser with no download or account. Learn what the bamboo cicada toy is and how XBSTACK rebuilt it with Canvas, touch, audio and motion controls.
Comments & evidence

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.

Sign-in required Reviewed before public
Loading the discussion…