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 anASSETSbinding. - 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:
- A session never has more active registrations than its capacity.
- A given email has at most one active registration per session.
- A ticket number is unique within a session.
- A payment-proof object belongs to exactly one registration and is immutable once confirmed.
- A committed registration has one durable outbox event, delivered at least once.
- 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.
%%{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.
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.
| Requirement | Chosen mechanism | Responsibility in this app | Rejected alternative and why |
|---|---|---|---|
| Serve the SPA and hashed assets without invoking application code | Workers static assets with an ASSETS binding | Serves index.html, JavaScript, CSS, and images; asset requests are free and do not consume Worker invocations | A separate Pages project works, but adds a second deployment surface and a second origin to reason about |
| Route authenticated JSON operations | One Worker router under /api/v1/* with run_worker_first | Authenticates, authorizes, validates, and returns application/problem+json on failure | Serving 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 joins | D1 | Sessions, registrations, ticket numbers, check-ins, audit rows, and the outbox | Workers KV is eventually consistent and has no unique constraints, foreign keys, or multi-row transactions |
| Store payment proofs as immutable bytes | R2, private bucket, deterministic keys | Holds images and PDFs up to 5 MB; records SHA-256 and byte count in D1 | A D1 BLOB column hits the 2 MB row limit, bloats the database, and cannot stream range requests |
| Serialize capacity decisions and push live check-ins | One Durable Object per session | Grants short-lived ticket leases, enforces capacity, and broadcasts check-ins over hibernating WebSockets | Polling 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 request | Queue with a consumer and a DLQ | Retries transient provider failures, quarantines poison messages, and decouples latency from delivery | ctx.waitUntil() can be dropped on eviction and has no retry policy or dead-letter path |
| Observe requests across all of the above | Workers Logs, traces, and a Tail Worker for export | Correlates one request ID across Worker, D1, DO, R2, and Queue; feeds SLO alerts | A 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.
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.
| Path | Cache policy | Why |
|---|---|---|
Fingerprinted /assets/ files | public, max-age=31536000, immutable | The hash in the filename changes when the bytes change |
index.html | no-cache, revalidate | It names the current asset graph |
| API responses | no-store unless explicitly public | A 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, uniqueslug, positivecapacity,starts_at, status.registrations:id,session_idforeign key,email,ticket_no, status, proof metadata, idempotency key, timestamps.checkins:registration_idas primary key, so a double scan is a no-op.outbox: autoincrementing id, topic, JSON payload, and asent_atthat 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.
The Durable Object is a projection, not a second database
SessionBoard owns two things: a short-lived lease table for capacity decisions and a live check-in projection for the staff screen.
Its SQLite storage holds leases(lease_id, ticket_no, expires_at, confirmed) plus a small board_state. The authoritative registration remains in D1. If the object is evicted, the live board is rebuilt from D1 on the next connection; if its storage is lost, reconciliation repairs it. That hierarchy is what makes the failure section tractable.
Figure 3 traces a registration through the gate and shows where each branch terminates.
%%{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
Fail closed, never bypass the gate
The most dangerous failure in this design is a fallback that keeps registration working by writing directly to D1 when the Durable Object is unavailable. That converts a partial outage into an invariant violation: the object is the only component that serializes capacity for a session, and D1's unique ticket constraint prevents duplicates, not oversubscription. Fail closed with a 503 and a retry hint; never bypass the gate.
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.
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.
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.
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.
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.
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/andsrc/db/. - Schema files:
migrations/; tests:test/. - Static source:
public/, built todist/. - Assets: directory
./distunder theASSETSbinding, worker-first for API paths, SPA fallback for client routes. - Data: one D1 database
DBand one private R2 bucketPROOFS. - Coordination: one Durable Object binding
BOARDwith 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
varsvalue.
- Create the resources in a scratch account:
wrangler d1 create fieldnotes,wrangler r2 bucket create fieldnotes-proofs,wrangler queues create registration-events, andwrangler queues create registration-events-dlq. Put the returned IDs and names intowrangler.jsonc, not into a committed secret file. - Write
0001_init.sqlwithsessions,registrations,checkins, andaudit_log. Include the partial unique index on active email, the unique ticket constraint, the status check, the positive capacity check, and the foreign keys. Write0002_outbox.sqlwithoutboxand a partial index on unsent rows. Runwrangler d1 migrations apply DB --local, thenwrangler d1 migrations list DB --localand confirm both files are recorded. - 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-sessionwithHttpOnly,Secure,SameSite=Lax, andPath=/. Bootstrap the first staff row with a one-offwrangler d1 execute; there is no public signup. Every mutating route checks theOriginheader and a same-origin request header, and every route returnsapplication/problem+jsonwith a stabletype,title, andstatus. - Implement the registration route in this order: authenticate, load the session by slug, validate the body, ask
SessionBoardfor a lease, run onebatch()that inserts the registration and the outbox row, confirm or release the lease, and return201with aLocationheader. Add anIdempotency-Keycolumn or table so a retried POST returns the first result instead of a second ticket. - Implement the proof route with a 5 MB cap, an allowlist of
image/jpeg,image/png, andapplication/pdf, a deterministic keyproofs/{sessionId}/{registrationId}, and a SHA-256 computed while streaming. Reject a second upload for a confirmed registration with409. - Implement the check-in route for staff only. Insert into
checkinswithON CONFLICT DO NOTHING, then callSessionBoard.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. - 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 uniqueevent_idinnotifications, a provider timeout, and a throw on failure so the platform retries. - 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 againstwrangler devfor the SPA route and one direct/api/v1/does-not-existtest that must return JSON 404, notindex.html. - Create the preview resources: a separate D1 database, R2 bucket, and staging Queue producer, bound under
previews. Runwrangler d1 migrations apply PREVIEW_DB --remote --config wrangler.preview-migrations.jsonc, thenwrangler 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. - Release through versions:
wrangler versions upload, thenwrangler versions deployat 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. Runwrangler 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/exampleand 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_atafter 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:
- Delete the preview with
wrangler preview delete --name capstone-b --skip-confirmation. - Delete the preview D1 database and R2 bucket only after confirming they are the preview resources, not production.
- Empty the R2 bucket before deleting it; R2 refuses to delete a non-empty bucket.
- Purge the test queue and its DLQ, or delete both queues.
- Remove the scratch Worker with
wrangler delete, then remove local.wrangler/state. - 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.
%%{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.
| # | Check | Pass artifact |
|---|---|---|
| 1 | Unauthenticated registration | POST returns 401 with no row; attendee A gets 403 on attendee B's proof and the object is unchanged |
| 2 | Capacity 40 under concurrency | Forty 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 |
| 3 | Upload limits | A 6 MB upload returns 413 without committing an object; a valid 4 MB PDF returns 204 with a matching SHA-256 |
| 4 | Outbox durability | The outbox row commits with the registration; stopping the publisher leaves it unsent; restarting delivers it |
| 5 | Consumer failure and replay | A failing consumer retries, then reaches the DLQ; replay leaves one notifications row |
| 6 | Rebuild and isolation | Deleting DO storage in a scratch environment and reconciling restores the board from D1; a preview's D1 sentinel is absent from production |
| 7 | Preview routing | The preview serves the SPA shell and a JSON 404 |
| 8 | Canary and rollback | A ten-percent canary is promoted only after thirty minutes inside the SLO; rollback restores the prior version |
| 9 | Trace and orphan audit | One 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.