Back to Cloudflare

Capstone B: Build a Full-Stack Application on Workers

November 5, 2026 Updated November 6, 2026 Wasil Zafar 40 min read

Combine static assets, SQL, objects, async work, and safe deployment

Table of Contents

  1. Choose a Small Product and Its Data Invariants
  2. Design Assets, API Routes, and Resource Bindings
  3. Implement Persistent Data and Background Work
  4. Release Through a Tested Preview and Production Gate
  5. Build the Application With Reproducible Configuration
  6. Submit Integration Evidence, Cost Assumptions, and Recovery Tests

Choose a Small Product and Its Data Invariants

A volunteer-run letterpress workshop sells forty seats for a Saturday session. On paper, the system is three objects: a ledger where names are written, a locked cash box where payment receipts go, and a door list the steward reads at the entrance. The ledger is the truth about who registered. The cash box holds evidence, not identity. The door list is a convenience that can be rebuilt from the ledger. That is the shape of this capstone. The product is Field Notes Workshops: a public schedule, a registration form, a payment-proof upload, a staff check-in screen, and a confirmation email. The implementation is a Worker with static assets, API routes, D1, R2, a Durable Object class, and a Queue with a dead-letter queue. The Worker is the only public entry point; no bucket or database is reachable directly.

Key terms:

  • Static assets are built files served by the Workers asset layer, usually from a dist/ directory through an ASSETS binding.
  • A binding is the typed handle a Worker uses to reach a resource: env.DB, env.PROOFS, env.BOARD, env.EMAIL_QUEUE.
  • D1 is Cloudflare's managed SQLite database. R2 is S3-compatible object storage. A Durable Object is a single-threaded, addressable instance with its own storage, used here to serialize per-session decisions and hold live check-in state. Queues delivers messages to a consumer Worker with retries and an optional dead-letter queue.
  • A migration is a numbered SQL file that changes the schema. An outbox is a row written in the same transaction as a business change, then published later, so a crash between the database commit and the queue send cannot lose the event.

The design starts from six invariants, because the UI is allowed to change and the invariants are not:

  1. A session never has more active registrations than its capacity.
  2. A given email has at most one active registration per session.
  3. A ticket number is unique within a session.
  4. A payment-proof object belongs to exactly one registration and is immutable once confirmed.
  5. A committed registration has one durable outbox event, delivered at least once.
  6. Only the registration owner may upload proof; only staff may check someone in.

Invariant 1 is enforced by the Durable Object gate; invariant 2 by the partial unique index; invariant 3 by the unique ticket constraint. Invariant 4 is enforced by the route's status check, deterministic R2 keys, and a database row that records the object's hash. Invariants 5 and 6 are enforced by the schema and by the Worker's authorization layer. Figure 1 places those responsibilities on a trust map.

Choose a Small Product and Its Data Invariants
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
    subgraph PUB["Public: no session"]
        B["Browser: SPA shell, program page, assets"]
    end
    subgraph EDGE["Worker: one deployable, one origin"]
        A["ASSETS binding: fingerprinted files"]
        R["API router: /api/v1/*"]
        AUTH{"Valid session cookie?"}
    end
    subgraph DATA["Durable data"]
        D[("D1: sessions, registrations, outbox, check-ins")]
        O[("R2: payment proofs, private bucket")]
        S["SessionBoard DO: leases and live check-ins"]
    end
    subgraph ASYNC["Asynchronous work"]
        C["Cron: publish unsent outbox rows"]
        Q["Queue: registration-events"]
        DLQ["Dead-letter queue"]
        M["Email provider"]
    end
    B -->|"GET /assets/*"| A
    B -->|"POST /api/v1/registrations"| R
    R --> AUTH
    AUTH -->|"no"| X["401 JSON: no data access"]
    AUTH -->|"yes, attendee"| D
    AUTH -->|"owner or staff"| O
    AUTH -->|"staff WebSocket"| S
    C -->|"select unsent"| D
    C -->|"send batch"| Q
    Q -->|"deliver"| M
    Q -->|"max retries"| DLQ
    R -->|"staff check-in"| S
    classDef primary fill:#132440,color:#ffffff,stroke:#0b172b;
    classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a;
    classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f;
    classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420;
    classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f;
    class B,A,R,S,C,Q,DLQ,M,X secondary;
    class AUTH ok;

The diagram has two properties worth naming. First, every write to durable storage passes through the Worker; the cron publisher only reads outbox rows. Second, the Queue is downstream of an outbox row, not of the HTTP request. That single choice removes the most common lost-event failure in small applications.

Figure 2 shows the same system as layers with owners. The public layer is untrusted. The Worker layer owns authentication, authorization, validation, and the decision to call a binding. The data layer owns facts and constraints. The asynchronous layer owns delivery attempts and retries. A team can change the public layer without touching the data layer, but a change to the data layer's meaning is a product decision, not a deployment detail.

Layered trust and ownership boundaries for Field Notes Workshops A browser reaches a Worker that serves static assets and API routes. The Worker authenticates the caller, authorizes the action, and then uses D1, R2, a Durable Object, or a Queue. Dashed lines show that the browser never reaches storage directly and that the Durable Object is rebuilt from D1. One public entry point, four owned resources The browser holds no database credential and no bucket credential. Public / untrusted Browser SPA + session cookie No direct path to D1, R2, or the DO namespace Worker / policy ASSETS + router /api/v1/* Authenticate hash cookie, load role Authorize + validate owner, staff, size, type Durable facts D1 registrations + outbox R2 proofs, private SessionBoard DO leases, live board Async / delivery Cron publisher reads unsent outbox rows Queue + DLQ retry, then quarantine Email provider external, idempotent HTTPS write proof lease session role read send deliver rebuild key Policy decisions happen in the Worker; durable facts and delivery happen behind bindings. The dashed path is a rebuild, not a write: D1 can reconstruct the Durable Object's view.

Cloudflare's own R2 architecture is a useful real-world check on that separation. R2's metadata service is built on Durable Objects to keep object metadata strongly consistent, while the object bytes live in distributed storage. The lesson is not "use a Durable Object for everything"; coordination and bulk storage are different jobs with different failure modes.

The prerequisites carry the mechanics. If bindings or secrets are new, start with Create Your First Worker and Understand Its Configuration; the request lifecycle is in Write for the Workers Runtime. For the asset and routing model, read Host Static Sites and Full-Stack Apps With Workers; for schema discipline, Build Relational Features With D1; for live state, Coordinate State With Durable Objects; for object storage, Store and Deliver Objects With R2; for delivery semantics, Choose Queues or K2 for Asynchronous Events. The release section assumes Test Workers and Release Changes Safely.

Design Assets, API Routes, and Resource Bindings

The product boundary is deliberately narrow: one Worker serves the SPA and the API; one D1 database holds relational facts; one private R2 bucket holds payment proofs; one Durable Object namespace holds per-session state; one Queue carries registration events, with one dead-letter queue. There is no second service, no public bucket, and no direct database access from the browser. This assumes Workers Paid; free-tier allocations and some limits differ, so check the plan matrix before promising a free-tier deployment.

Table 1 names requirements, not products. Public reads are the schedule and session detail; writes, proof reads, and check-ins require a session, with check-ins restricted to staff.

RequirementChosen mechanismResponsibility in this appRejected alternative and why
Serve the SPA and hashed assets without invoking application codeWorkers static assets with an ASSETS bindingServes index.html, JavaScript, CSS, and images; asset requests are free and do not consume Worker invocationsA separate Pages project works, but adds a second deployment surface and a second origin to reason about
Route authenticated JSON operationsOne Worker router under /api/v1/* with run_worker_firstAuthenticates, authorizes, validates, and returns application/problem+json on failureServing the API from the asset layer would bypass policy; a separate API Worker adds a service binding without a clear benefit at this size
Store relational facts with constraints and joinsD1Sessions, registrations, ticket numbers, check-ins, audit rows, and the outboxWorkers KV is eventually consistent and has no unique constraints, foreign keys, or multi-row transactions
Store payment proofs as immutable bytesR2, private bucket, deterministic keysHolds images and PDFs up to 5 MB; records SHA-256 and byte count in D1A D1 BLOB column hits the 2 MB row limit, bloats the database, and cannot stream range requests
Serialize capacity decisions and push live check-insOne Durable Object per sessionGrants short-lived ticket leases, enforces capacity, and broadcasts check-ins over hibernating WebSocketsPolling D1 from every dashboard is slower and turns a read-heavy screen into repeated queries; D1 alone cannot hold a WebSocket
Deliver confirmation email without blocking the requestQueue with a consumer and a DLQRetries transient provider failures, quarantines poison messages, and decouples latency from deliveryctx.waitUntil() can be dropped on eviction and has no retry policy or dead-letter path
Observe requests across all of the aboveWorkers Logs, traces, and a Tail Worker for exportCorrelates one request ID across Worker, D1, DO, R2, and Queue; feeds SLO alertsA third-party agent inside the Worker adds cold-start cost and still needs platform logs for platform failures

Asset routing is a policy boundary, not a build setting. Workers static assets serve a matching file without invoking the Worker; a path with no file falls through to application code. Two settings decide whether an API request reaches the auth layer or is answered by the SPA shell.

{
  "assets": {
    "directory": "./dist",
    "binding": "ASSETS",
    "run_worker_first": ["/api/*"],
    "not_found_handling": "single-page-application"
  }
}
// End of the /api/v1/* router: never fall through to static assets.
if (!route) {
  return problem(404, "no such route");
}

SPA fallback turns API typos into 200s

not_found_handling returns the SPA shell with status 200 for unmatched paths. That is correct for client-side routes and wrong for API routes, which must return JSON 404. The router must end with an explicit problem response and must never defer API traffic to env.ASSETS.fetch().

The same boundary applies to caching. Cache policy is part of authorization, not a performance afterthought.

PathCache policyWhy
Fingerprinted /assets/ filespublic, max-age=31536000, immutableThe hash in the filename changes when the bytes change
index.htmlno-cache, revalidateIt names the current asset graph
API responsesno-store unless explicitly publicA response carrying a session cookie must never be shared

A cached response with a session cookie is a data leak with a TTL. Treat the cache key and the cookie together; a correct Cache-Control header is the last line of defence.

The schema is small, and its constraints carry the invariants.

  • sessions: id, unique slug, positive capacity, starts_at, status.
  • registrations: id, session_id foreign key, email, ticket_no, status, proof metadata, idempotency key, timestamps.
  • checkins: registration_id as primary key, so a double scan is a no-op.
  • outbox: autoincrementing id, topic, JSON payload, and a sent_at that stays null until published.
  • audit_log: staff actions.

The constraints are the enforcement layer. A partial unique index on active (session_id, email) protects invariant 2, and unique constraints protect ticket numbers and idempotency keys. Waitlisted rows keep a null ticket number, and SQLite permits multiple nulls. The statuses are reserved, confirmed, waitlisted, cancelled, and expired.

The registration write is one D1 batch(), which Cloudflare documents as a SQL transaction: the registration insert and the outbox insert either both commit or neither does. That is the point where the database stops being a place to store strings and becomes the enforcement layer for invariant 5.

Figure 3 traces a registration through the gate and shows where each branch terminates.

Design Assets, API Routes, and Resource Bindings
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
sequenceDiagram
    autonumber
    participant C as Browser
    participant W as Worker /api/v1
    participant D as D1
    participant S as SessionBoard DO
    participant R as R2
    participant Q as Queue
    C->>W: POST /sessions/:slug/registrations
    W->>D: lookup session hash for the cookie
    alt no valid session
        D-->>W: null
        W-->>C: 401 problem+json
    else authenticated attendee
        W->>S: reserve(idempotency-key, capacity)
        alt session full
            S-->>W: full
            W->>D: insert waitlisted row, no ticket
            W-->>C: 202 waitlist position
        else lease granted
            S-->>W: ticket 17, lease 10 minutes
            W->>D: batch(insert registration, insert outbox)
            alt unique email or ticket conflict
                D-->>W: constraint error
                W->>S: release(lease)
                W-->>C: 409 duplicate or retry
            else committed
                W->>S: confirm(lease)
                W-->>C: 201 Location: /registrations/17
                Note over D,Q: cron publishes the outbox row later
            end
        end
    end
    C->>W: PUT /registrations/:id/proof
    W->>D: load registration owner and status
    D-->>W: owner, status
    alt wrong owner or wrong status
        W-->>C: 403 or 409, no upload
    else allowed
        W->>R: put private object, 5 MB cap
        R-->>W: etag and bytes
        W->>D: update proof_key, sha256, bytes
        W-->>C: 204
    end

The happy path is boring; exits are explicit. A full session produces a waitlist row with no ticket, not a 500. A duplicate email produces a 409, not a second ticket. A failed D1 insert releases the lease. A proof upload touches R2 only after owner and status checks.

The queue contract is equally explicit. The producer is the cron publisher, not the HTTP handler. Every minute it selects up to 100 rows where sent_at IS NULL, sends them as one batch, and marks them sent only after the send succeeds. The consumer computes an idempotency key from the outbox id, inserts a notifications row with a unique key, and calls the email provider. A duplicate delivery is absorbed by the unique key; a provider timeout throws, retries, and eventually lands in the DLQ. The DLQ is a normal queue with its own consumer; unconsumed messages expire on its retention schedule, which is 24 hours on the free plan and four days by default on paid, configurable up to fourteen.

Implement Persistent Data and Background Work

The first production question is which copy is allowed to be wrong. D1 is the system of record for registrations; R2 is the system of record for bytes. The Durable Object is a projection and a gate, allowed to be stale or empty because it can be rebuilt. The Queue is a delivery mechanism, allowed to duplicate because the consumer is idempotent. Once those roles are written down, failure handling stops being improvised.

Migrations are where teams quietly break that hierarchy. D1's migration runner records applied files in d1_migrations and applies them in filename order. There is no reliable down-migration story, and a destructive change cannot be undone by rolling back the Worker. The safe pattern is expand and contract: add a nullable column or a new table in migration 0002, deploy code that writes both shapes, backfill in bounded batches, switch reads, then remove the old column in a later migration. A migration that drops a column in the same release as the code change has turned a reversible deploy into a one-way door.

Before applying anything remote, the release job runs wrangler d1 migrations list DB --remote, exports a copy with wrangler d1 export, and applies the migration to a preview database. D1 Time Travel keeps a restore point for the last 30 days, but a restore is database-wide, not a per-row undo; treat it as an incident tool, not a deployment strategy. The operator also checks D1's statement limits: 100 KB per SQL statement, 100 columns per table, 2 MB per row or BLOB, and a 10 GB database ceiling on Workers Paid. Those are design constraints, not surprises to discover at 2 a.m.

The lease protocol turns a capacity check into a durable decision. The object is idempotent by key, grants a ten-minute lease, and releases it by alarm if the Worker dies before the D1 write.

// SessionBoard: one decision per idempotency key, one session per object.
type Lease = { ticketNo: number; expiresAt: number; confirmed: boolean };

async reserve(key: string, capacity: number): Promise<Lease | "full"> {
  const existing = this.leases.get(key);
  if (existing) return existing;                 // same key, same ticket
  if (this.activeCount() >= capacity) return "full";
  const lease = this.newLease(10 * 60_000);      // ten-minute hold
  this.leases.set(key, lease);
  await this.storage.setAlarm(lease.expiresAt);  // release if unconfirmed
  return lease;
}

async confirm(key: string) { /* D1 write succeeded */ }
async release(key: string) { /* cancellation or constraint error */ }

The order of writes decides the worst case. On first use, the Worker seeds a fresh or evicted object with D1's active count and highest ticket, so a rebuilt object starts from facts rather than zero. The Worker writes D1 after the lease, then confirms it; a constraint error calls release. A Worker that dies between the lease and the write is cleaned up by the alarm. A Worker that writes D1 but dies before confirming leaves a row that reconciliation counts, so the failure temporarily inflates the active count instead of selling a seat twice. A cancellation writes D1 first and then calls release; reconciliation repairs a missed call.

Reconciliation is a scheduled job, not a hope. Every fifteen minutes it runs a grouped count from D1 for recently active sessions and calls SessionBoard.reconcile(active, highWater). The object takes D1's count as authoritative and raises its high-water mark to at least the maximum ticket in D1. That repairs drift after an eviction, a failed release, or a manual database fix.

The outbox has a similar repair loop. If the publisher is down, rows accumulate with a null sent_at and the next run drains them oldest-first. If the consumer is down, the queue retains messages until its retention limit. A poison message retries and then moves to the DLQ, where an operator replays it after fixing the cause; the consumer's unique key makes replay safe.

R2 adds one more failure mode: an object can exist without a registration. The upload writes the object, then updates D1. If the D1 update fails, the Worker attempts a delete; if that also fails, an orphan remains. A weekly reconciler lists objects under the current month's prefix, reads the registration_id metadata, and deletes objects with no matching row older than 24 hours. The bucket is private, so an orphan is a cost problem. R2's strong read-after-write consistency means the reconciler will not miss a just-written object; the age threshold covers a D1 row that is mid-transaction.

Figure 4 shows ownership rather than traffic: who is allowed to be authoritative, who may be rebuilt, and where the repair loops attach. The solid lines are the normal write path; the dashed lines are reconciliation and replay.

Ownership and repair paths for the workshop application The Worker writes registrations and outbox rows to D1 in one transaction and puts proof objects in R2. D1 is the system of record. R2 stores immutable bytes. The SessionBoard Durable Object holds leases and a live check-in projection and is rebuilt from D1. A cron publisher reads the outbox and sends to a Queue, whose consumer is idempotent and whose failures go to a dead-letter queue. Observability spans every path. Authority, projections, and repair loops Solid: normal write. Dashed: rebuild, reconcile, or replay. Worker policy + routing D1: system of record registrations + outbox UNIQUE, CHECK, FK batch = one transaction R2: bytes proofs/session/reg private, immutable sha256 in D1 SessionBoard DO leases + live board projection, not truth rebuilt from D1 Cron publisher unsent rows, oldest first marks sent after send Queue + consumer at-least-once unique event id DLQ poison messages manual replay Observability: request id, trace, SLO, DLQ depth one correlation key across Worker, D1, DO, R2, and Queue batch put proof reserve + confirm key reconcile from D1 reads unsent send exhaust replay trace If D1 and the DO disagree, D1 wins. If D1 and R2 disagree, the D1 row decides whether the object is an orphan.

Monitoring starts with questions an operator can answer. Can they find one registration's request ID across the Worker log, the D1 query, the DO lease call, and the queue publish? Can they tell whether a queue message was delivered, retried, or quarantined? Can they prove every session's active count matches D1 and every R2 object has a registration row?

The platform supplies the evidence. Workers Logs includes 20 million events per month with seven-day retention on Workers Paid; a Tail Worker can forward errors to longer-lived storage. Traces sample at a configurable head rate, so a low-traffic app can trace 100% and a busy one 10%.

Write the SLOs before the alerts. 99.9% of registration requests succeed under 800 ms at p95, 99% of outbox events are delivered within 60 seconds, and DLQ depth is zero outside an acknowledged incident.

Release Through a Tested Preview and Production Gate

A release is a sequence of evidence, not a deploy command: the code builds, the tests pass, the migration applies to a copy, the preview serves the real paths, the canary stays inside the SLO, and a rollback is still possible. Figure 5 contrasts the path most small projects take with the path this application needs.

Before and after release paths for a full-stack Worker The old path deploys code and schema together to production, then discovers failures with no isolated preview and an uncertain rollback. The gated path runs tests, deploys an isolated Preview, applies an expand migration, uploads a version, sends ten percent of traffic, observes logs and SLOs, then promotes to one hundred percent. A failed gate stops the release or rolls back the Worker while a forward migration repairs schema. Two release paths, one production database The difference is not effort; it is the order of evidence and the reversibility of each step. Before: deploy and hope Edit code and schema together Deploy 100% straight to prod Watch dashboard after users are affected Rollback code schema may not match Forward fix under pressure After: a gate with a known exit Tests vitest + E2E Preview isolated D1/R2/DO Expand migration apply to copy first Upload version no traffic yet Canary 10% traces + SLO 100% promote Gate fails: stop, keep old version no partial schema, no lost traffic Breach: rollback Worker then forward-fix schema

Preview behavior is resource-specific. Worker Previews (wrangler preview) isolate code and Durable Objects, but not every bound resource.

Preview isolation is per resource, not per environment

Worker Previews create an isolated environment under the same Worker, with its own code, configuration, URL, and observability. Durable Object namespaces and storage are provisioned per Preview automatically. D1 and R2 are not: if two Previews bind the same database ID or bucket name, they share rows and objects, as the Preview resource table documents. The capstone creates fieldnotes-preview D1 and R2 resources, binds them in the previews block, and applies migrations explicitly. The preview's DO state is isolated, but its queue producer is not; a preview can send to a production queue, and a production consumer will process those messages. Point the preview at a staging queue or omit the producer until the test needs it.

A preview cannot prove the async half

Previews cannot consume Queues, and Cron Triggers do not run in a Preview. A preview can prove the HTTP path, asset routing, the auth matrix, a D1 migration, an R2 upload, and Durable Object coordination. It cannot prove the queue consumer or the scheduled publisher. Those need a staging Worker with the same consumer code and a dedicated queue, or a test-only route that calls the same function the queue() and scheduled() handlers use. Calling a preview "hosted validation" when the async half never ran is the evidence gap this capstone targets.

Migration order is the other gate. Migration 0002_add_outbox.sql is additive; it creates a table and an index. The old Worker version still runs against the new schema because nothing it reads has changed. The new version writes the outbox row inside the registration batch. Only after the canary proves the new path does a later release remove the old column or index. This is expand and contract in practice, and it is why a Worker rollback remains viable: the previous version still finds the columns it expects.

A version is inert until it receives traffic. Upload it, canary a percentage, observe the same signals the SLOs use, then promote.

# Create a version without routing traffic to it.
wrangler versions upload

# Route ten percent, observe, then promote to one hundred.
wrangler versions deploy

# Return to a recorded version if the gate fails.
wrangler rollback <version-id>

Rollback has preconditions

wrangler rollback creates a new deployment at the previous version and takes effect across routes immediately. It can reach any of the last 100 versions, but it is blocked if a Durable Object class lifecycle change occurred or a bound resource was deleted or modified between the two versions.

Durable Objects add a nuance that a stateless Worker does not have: each object is pinned to the version it started on until a new deployment is created. A gradual split is assigned per object, not per request. For a session board, that means a canary can leave some sessions on the old code and some on the new code at the same time. The state schema must therefore be readable by both versions. Add fields; do not rename or drop them in the same release. If it cannot, deploy the storage migration first, then the code, and accept a forward-fix rollback.

The release checklist fits in a pull request template: tests pass; the preview serves the changed path; the migration applied to the preview database and a restored copy; the canary stayed within the SLO for thirty minutes; one synthetic registration traces across all five hops; the DLQ is empty; the rollback version is recorded; and on-call knows which migration is irreversible.

Build the Application With Reproducible Configuration

The exercise below is design-only: no command was executed for this article, no hosted account was modified, and expected observations are acceptance criteria, not measurements. The repository state for this capstone is lab_status: not_run; the planning baseline is 2026-11-02, and product limits and prices were re-read on 2026-11-05. Treat every number as dated.

Capstone build

Build the Application With Reproducible Configuration

Label: Design-only. Not executed. Do not cite any result here as a hosted measurement.

Prerequisites and plan: A Cloudflare account on Workers Paid (the design assumes its limits and observability; free-tier allocations are smaller), Node.js 22 or later, a current Wrangler 4.x, and a Git repository. An email provider sandbox is optional; without one, the consumer writes a notifications row and skips the external call. No custom domain is required; the workers.dev hostname is enough.

Minimal setup: The build writes the SPA to dist/, and the project separates routes, database code, migrations, static files, and tests.

  • Worker entry: src/worker.ts.
  • Route and database modules: src/routes/ and src/db/.
  • Schema files: migrations/; tests: test/.
  • Static source: public/, built to dist/.
  • Assets: directory ./dist under the ASSETS binding, worker-first for API paths, SPA fallback for client routes.
  • Data: one D1 database DB and one private R2 bucket PROOFS.
  • Coordination: one Durable Object binding BOARD with a SQLite class migration.
  • Async: one queue producer EMAIL_QUEUE, a consumer with batch size 10 and five retries, and a dead-letter queue.
  • Observability: logs on, invocation logs on, and a trace sample rate.
  • Secret: the session secret is a Wrangler secret, never a vars value.
  1. Create the resources in a scratch account: wrangler d1 create fieldnotes, wrangler r2 bucket create fieldnotes-proofs, wrangler queues create registration-events, and wrangler queues create registration-events-dlq. Put the returned IDs and names into wrangler.jsonc, not into a committed secret file.
  2. Write 0001_init.sql with sessions, registrations, checkins, and audit_log. Include the partial unique index on active email, the unique ticket constraint, the status check, the positive capacity check, and the foreign keys. Write 0002_outbox.sql with outbox and a partial index on unsent rows. Run wrangler d1 migrations apply DB --local, then wrangler d1 migrations list DB --local and confirm both files are recorded.
  3. Implement the auth boundary before any business route: login writes an opaque token, stores only its SHA-256 hash with an expiry and a role, and sets __Host-session with HttpOnly, Secure, SameSite=Lax, and Path=/. Bootstrap the first staff row with a one-off wrangler d1 execute; there is no public signup. Every mutating route checks the Origin header and a same-origin request header, and every route returns application/problem+json with a stable type, title, and status.
  4. Implement the registration route in this order: authenticate, load the session by slug, validate the body, ask SessionBoard for a lease, run one batch() that inserts the registration and the outbox row, confirm or release the lease, and return 201 with a Location header. Add an Idempotency-Key column or table so a retried POST returns the first result instead of a second ticket.
  5. Implement the proof route with a 5 MB cap, an allowlist of image/jpeg, image/png, and application/pdf, a deterministic key proofs/{sessionId}/{registrationId}, and a SHA-256 computed while streaming. Reject a second upload for a confirmed registration with 409.
  6. Implement the check-in route for staff only. Insert into checkins with ON CONFLICT DO NOTHING, then call SessionBoard.markCheckedIn() and broadcast to hibernating WebSockets. If the object call fails, return success for the D1 write and log the projection failure; the board rebuilds on reconnect.
  7. Implement the outbox publisher as the scheduled() handler: select up to 100 unsent rows, send them in one batch, and mark them sent only after the send resolves. Implement the queue consumer with a unique event_id in notifications, a provider timeout, and a throw on failure so the platform retries.
  8. Write the integration tests with @cloudflare/vitest-plugin: an unauthenticated POST returns 401; an attendee cannot read another attendee's proof; a 41st registration against capacity 40 returns a waitlist or 409 and never a 41st ticket; a duplicate email returns 409; a proof over 5 MB returns 413; a failed D1 batch releases the lease. Add one browser test against wrangler dev for the SPA route and one direct /api/v1/does-not-exist test that must return JSON 404, not index.html.
  9. Create the preview resources: a separate D1 database, R2 bucket, and staging Queue producer, bound under previews. Run wrangler d1 migrations apply PREVIEW_DB --remote --config wrangler.preview-migrations.jsonc, then wrangler preview --name capstone-b. Exercise the preview URL with a seeded session and a test attendee. Confirm the preview did not write to the production D1 by checking a sentinel row.
  10. Release through versions: wrangler versions upload, then wrangler versions deploy at 10%, send a synthetic registration, inspect the trace and logs by request ID, wait thirty minutes, then promote to 100%. Record the previous version ID. Run wrangler rollback <version-id> against a staging Worker, not production, to prove the command and the timing.

Expected observations: These are acceptance criteria, not measurements.

  • The local migration list records both files.
  • The preview serves the SPA shell at /sessions/example and returns JSON 404 at /api/v1/nope.
  • The forty-first concurrent request never creates a forty-first ticket.
  • A duplicate email creates no second row.
  • The proof object is private, and its SHA-256 matches the D1 row.
  • The outbox row moves from a null to a non-null sent_at after the publisher runs.
  • A duplicate delivery leaves one notifications row.
  • One trace contains Worker, D1, Durable Object, and queue spans.
  • Rollback restores the previous version without a schema error.

Failure checks: Stop the consumer and confirm the queue backlog grows while the API still returns 201. Force a provider error and confirm retries, then DLQ placement after the configured retries are exhausted. Delete the DO storage in a scratch environment and confirm reconciliation restores counts from D1. Apply a deliberately bad migration to a copy and confirm the release job stops before production. Point a preview at the production queue by mistake and confirm the documented hazard: the production consumer receives the preview's message. These are tests of the design, not proof of a production incident.

Cost dimensions: Workers Paid has a $5 monthly minimum with 10 million requests and 30 million CPU milliseconds included; static asset requests are free. D1 includes 25 billion rows read, 50 million rows written, and 5 GB-month of storage. R2 includes 10 GB-month of Standard storage, 1 million Class A operations, and 10 million Class B operations, with no egress charge. Queues includes 1 million operations per month. Durable Objects includes 1 million requests and 400,000 GB-seconds per month, with SQLite storage billed at $0.20 per GB-month after 5 GB. Workers Logs includes 20 million events per month with seven-day retention. A test run that creates a few hundred rows and a few dozen objects should stay inside those inclusions, but only the account's bill can confirm it.

Cleanup:

  1. Delete the preview with wrangler preview delete --name capstone-b --skip-confirmation.
  2. Delete the preview D1 database and R2 bucket only after confirming they are the preview resources, not production.
  3. Empty the R2 bucket before deleting it; R2 refuses to delete a non-empty bucket.
  4. Purge the test queue and its DLQ, or delete both queues.
  5. Remove the scratch Worker with wrangler delete, then remove local .wrangler/state.
  6. Rotate the session secret and any provider key used in the exercise.

Figure 6 turns the exercise into an evidence flow. The point is not that every step is automated on day one; it is that no step is skipped silently. A failed local test stops the flow before a preview exists. A failed preview stops it before a migration touches production. A failed canary stops it before 100% of users see the change.

Build the Application With Reproducible Configuration
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
    L["Local: vitest-plugin + wrangler dev"] --> U{"Unit and integration tests pass?"}
    U -->|"no"| F["Fix locally; no preview, no deploy"]
    U -->|"yes"| P["wrangler preview: isolated DO, separate D1/R2"]
    P --> E{"Auth matrix, capacity race, upload limits pass?"}
    E -->|"no"| F
    E -->|"yes"| M{"Migration applies to preview and restored copy?"}
    M -->|"no"| F
    M -->|"yes"| V["wrangler versions upload"]
    V --> C{"Canary 10%: SLO, 5xx, DLQ, trace?"}
    C -->|"breach"| RB["wrangler rollback; forward-fix schema"]
    C -->|"pass 30 min"| G["Promote to 100%"]
    G --> O{"Post-deploy audit: duplicate tickets, orphan objects, DLQ depth"}
    O -->|"fail"| RB
    O -->|"pass"| R["Record evidence and close the release"]
    classDef primary fill:#132440,color:#ffffff,stroke:#0b172b;
    classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a;
    classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f;
    classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420;
    classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f;
    class L,U,F,P,E,M,V,RB,G,O,R secondary;
    class C warn;

Submit Integration Evidence, Cost Assumptions, and Recovery Tests

The capstone is complete when an outsider can inspect it. This matrix is pass/fail, with an artifact per line, not screenshots.

Pass/fail evidence. Each row needs an artifact, not a screenshot.

#CheckPass artifact
1Unauthenticated registrationPOST returns 401 with no row; attendee A gets 403 on attendee B's proof and the object is unchanged
2Capacity 40 under concurrencyForty reservations yield forty tickets; the forty-first yields a waitlist row or 409; no duplicate (session_id, ticket_no) and no active count above capacity; a duplicate email returns 409 with one active row
3Upload limitsA 6 MB upload returns 413 without committing an object; a valid 4 MB PDF returns 204 with a matching SHA-256
4Outbox durabilityThe outbox row commits with the registration; stopping the publisher leaves it unsent; restarting delivers it
5Consumer failure and replayA failing consumer retries, then reaches the DLQ; replay leaves one notifications row
6Rebuild and isolationDeleting DO storage in a scratch environment and reconciling restores the board from D1; a preview's D1 sentinel is absent from production
7Preview routingThe preview serves the SPA shell and a JSON 404
8Canary and rollbackA ten-percent canary is promoted only after thirty minutes inside the SLO; rollback restores the prior version
9Trace and orphan auditOne trace contains the Worker, D1, DO, and queue hops; no R2 object older than 24 hours lacks a registration row

Self-check with explained answers. Why not skip the Durable Object and rely on D1's unique constraint? The constraint prevents two rows with the same ticket number, but not two concurrent requests both deciding a seat is free and inserting different ticket numbers. The object serializes the decision; D1's constraint catches a bug in the gate. Why use an outbox instead of ctx.waitUntil(env.EMAIL_QUEUE.send(...))? The database commit and the queue send are separate systems. A crash, eviction, or transient queue error between them loses the event, and waitUntil has no durable retry or dead-letter contract. The outbox row commits with the registration, so the event survives a failed send. Why can't the preview prove the queue consumer? Previews can produce to a queue but cannot consume from one, and Cron Triggers target production. The consumer and publisher need a staging Worker or a test-only route calling the same function; otherwise an untested path becomes a release risk.

Unresolved limitations. D1 read replication is a public beta with sequential consistency through the Sessions API; writes still go to the primary, and one database remains single-threaded, so a hot session is a throughput boundary. Durable Objects have a soft limit of about 1,000 requests per second per object; a very large live audience may need sharding. Queues is at-least-once and unordered, so every consumer must be idempotent. R2 orphan cleanup is eventual and depends on a scheduled reconciler; there is no metadata-aware lifecycle rule here. Preview isolation for D1, R2, and Queues is manual, and the preview cannot exercise the consumer or cron path. The auth design is a sketch, not a penetration-tested implementation; cookie rotation, CSRF, session fixation, and email deliverability need independent review. No hosted run was performed and no tool version was tested, so every latency, error-rate, and cost statement is an assumption or a documented limit, not a measurement.

Cost assumptions. Pricing was read on 2026-11-05 and will change. Workers Paid is $5/month with 10 million requests and 30 million CPU milliseconds included. D1 includes 25 billion rows read, 50 million written, and 5 GB storage. R2 Standard is $0.015/GB-month, $4.50/million Class A, $0.36/million Class B. Queues includes 1 million operations. Durable Objects includes 1 million requests and 400,000 GB-seconds, then $0.15/million and $12.50/million GB-seconds; SQLite storage is $0.20/GB-month after 5 GB. A 1,000-registration pilot plausibly lands near the $5 minimum. At 100,000 registrations, R2 storage and Class A, D1 writes, queue operations, and CPU dominate; model them first.

References. Workers best practices; Choose a data or storage product; Workers testing; Workers observability; Workers static assets; Static asset routing; Wrangler configuration; Workers limits; Workers pricing; D1 limits; D1 migrations; D1 batch API; D1 pricing; D1 read replication; D1 Time Travel; R2 pricing; R2 consistency; R2 Workers API; Queues limits; Queues pricing; Queues batching and retries; Queues dead-letter queues; Durable Objects limits; Durable Objects pricing; Durable Objects alarms; Durable Objects WebSocket hibernation; Workers versions and deployments; Gradual deployments; Rollbacks; Worker Previews; Preview resources and isolation; Vitest integration.