Draw the Resource Graph and the Application State Graph
Terraform's graph is a diagram of API objects. Your application's state graph is a history of facts. Both are real, both change on release day, and only the first one lives in your state file. Confusing them produces the classic outcome: a clean plan, a successful deploy, and a database that no longer matches the code that queries it.
Provider 5.28.1 can own more of this chain than older Cloudflare examples suggest. A Worker is now a Worker, a version and a deployment rather than a single upload, so the code, its bindings and the traffic split are all plannable. The provider documentation still carries the older single-resource upload path for simpler setups, and recommends the three-resource path when you want version control over what is serving traffic. Either way, D1 databases, queues, consumer attachments and Workflow definitions are resources too.
The state graph is not in that plan at all. D1 holds rows plus the migration ledger. A queue holds messages, retry counts and dead-letter contents. A Durable Object holds a SQLite database per instance. A Workflow instance holds a step history that survives restarts. No amount of state inspection tells you what is inside any of them, because Terraform records the container and never the contents.
| Surface | Terraform resource | What it versions | Runtime data it does not own |
|---|---|---|---|
| Database | cloudflare_d1_database | name, jurisdiction, replication mode | rows, indexes, d1_migrations |
| Queue | cloudflare_queue | retention, delivery delay, pause | in-flight and retained messages |
| Consumer | cloudflare_queue_consumer | batch size, retries, DLQ link | leases and retry counters |
| Worker code | cloudflare_worker_version | source, bindings, class migrations | nothing, because it is stateless |
| Traffic | cloudflare_workers_deployment | version percentages | nothing |
| Workflow | cloudflare_workflow | class name, concurrency, retention | instance history and sleeps |
| Durable Object class | none of its own | declared in migrations or exports | every instance's SQLite storage |
The first three rows are infrastructure; the last four rows are the application. That split is not a comment on importance. It is a comment on recovery: the left column can be rebuilt from configuration in minutes, and the right column cannot be rebuilt at all unless something else kept a copy.
A Durable Object class has no resource of its own, and that is deliberate. In this provider release the class lifecycle rides on the Worker version, as a migration entry or as a declarative export. There is no namespace resource in the 5.28.1 schema; the namespace is provisioned by the upload. So a class rename is a code change with a data consequence, reviewed like a schema migration rather than like a new bucket.
Instance identity is state too, and it is the part teams forget to design. A Durable Object is addressed by a name you choose, and a Workflow instance carries an identifier chosen at creation. If the identifier is random per request, no later process can find the instance that needs repair, and the recovery route becomes a search across logs. Choose an identifier derived from the business key, store it where the operator can read it, and the recovery route becomes a lookup.
Every edge between the two graphs is an attribute, and attributes do not type-check across tools. The binding array carries a type and one identifying attribute per type. Terraform can resolve the database and the queue from its own resources, because those attributes are computed outputs of objects in the same state. It cannot resolve a class name or a workflow name, because those are strings that also appear in source code, and the provider never reads your source.
| Binding type | Attribute that crosses | Where Terraform gets it |
|---|---|---|
d1 | id | the database resource's computed uuid |
queue | queue_name | the queue resource's queue_name |
durable_object_namespace | class_name | a literal that must match the exported class |
workflow | workflow_name | a literal that must match the definition's name |
The computed handoffs are safe. The literal ones are the ones to test. A database UUID that changes because someone recreated the database will produce a plan diff, which is visible. A class name that no longer matches the exported class produces no diff at all; the upload succeeds and the binding fails at runtime. That asymmetry is the reason the last two rows deserve a deploy-time assertion rather than a code review.
There is exactly one cycle in the graph, and it is the Workflow binding. A Worker version that declares a workflow binding needs the definition to exist. The definition needs a script and a class name, which only exist after a version carrying that class is deployed. Terraform reports a dependency cycle, and adding an explicit dependency will not break it, because that only adds another edge.
The cycle has three legitimate shapes, and none of them is clever. The first is two-phase Terraform: version one deploys the class, the definition is created against that deployment, and version two adds the binding. The second is to let the deployment tool own the binding while Terraform owns the definition, which removes the edge at the cost of one handoff string living outside the plan. The third is to skip the binding entirely and call the Workflows API from the Worker, which trades a graph edge for a token and a network hop.
Pick the two-phase route when the same root owns the Worker, and write it down. The temptation is to add the binding to version one and let Terraform work it out, which produces a cycle error that looks like a provider bug and is actually a modelling mistake. The second apply is not a workaround. It is the graph telling you that a definition cannot be bound before it exists.
%%{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 TF["Terraform graph — API objects and their edges"]
DB["D1 database
name, jurisdiction, replication"]
Q["Queue
retention, delivery delay"]
DLQ["Dead-letter queue
its own retention"]
QC["Consumer
batch, retries, DLQ name"]
WV["Worker version
code, bindings, migrations"]
DEP["Deployment
100% or split percentages"]
WF["Workflow definition
class, concurrency, retention"]
end
subgraph APP["Application state graph — what the runtime accumulates"]
ROWS["D1 rows
and d1_migrations ledger"]
MSG["Messages
retries and DLQ contents"]
DOS["Durable Object SQLite
one database per instance"]
HIST["Workflow instance history
completed steps and sleeps"]
end
DB -.->|"uuid into the d1 binding"| WV
Q -.->|"queue_name into the queue binding"| WV
Q --> QC
DLQ --> QC
WV --> DEP
WV -.->|"class name must match"| WF
DEP -.->|"code writes at runtime"| ROWS
Q --> MSG
WV --> DOS
WF --> HIST
DEP --> HIST
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 DB,Q,DLQ,QC primary;
class WV,DEP,WF secondary;
class ROWS,MSG,DOS,HIST ok;
Read the diagram from the dotted edges inward. Solid lines are references Terraform resolves and orders for you. Dotted lines are strings that cross a boundary: a UUID written into a binding, a queue name repeated in a consumer, a class name repeated in a definition. When one of those strings is wrong, the plan is still green and the failure appears at runtime, in a request that binds nothing or a consumer that never fires.
Destroy is the edge that deserves a rehearsal, not a diagram. Removing the database resource deletes the database and its rows. A class tombstone deletes every instance's storage. Removing the queue deletes undelivered messages. The state graph has no rollback, only a backup, and only if you took one before the apply.
The figure below places the two graphs side by side and marks where each handoff occurs.
Provision D1 and Version SQL Migrations Separately
Terraform creates an empty database. It does not create a schema. The resource decides the name, the jurisdiction, the primary location hint and the read-replication mode. It returns a UUID. That is the whole contract, and it is deliberately small.
Two attributes decide where the data lives, and both are creation choices. Jurisdiction restricts the database to a region set; the location hint asks for a primary region when the jurisdiction does not override it. Read the plan for a replacement marker before you change either, because a database that is replaced is a database whose rows are gone.
The computed table count is not a health check. The provider's own description says the value is no longer accurate and should not be relied on. A pipeline that waits for a non-zero table count, or an alarm that fires when it stops changing, is measuring a number that has already been disclaimed.
| Attribute | What it decides | Treat a change as |
|---|---|---|
name | the handle every migration command uses | fixed; renaming changes every command |
jurisdiction | which region set may store the data | a new database until the plan says otherwise |
primary_location_hint | where the primary is created | a creation choice, not an operational knob |
read_replication | whether replicas are placed automatically | an operational toggle |
uuid | the value the Worker binding needs | computed, never written by hand |
The UUID is the first cross-tool handoff, and it does not exist until the database does. If the Worker version is in the same root, the binding reads the computed attribute and Terraform orders the apply for you. That is the good case, and it is the reason to keep the database and the Worker in one configuration rather than two repositories with a copy of the value pasted between them.
SQL is versioned by files, not by resources. A migration is a numbered SQL file under a migrations directory, and the applied set is recorded in a table inside the database itself. Three commands cover the lifecycle: create a new file, list what is unapplied, apply what remains. The ledger is the authority, which means the schema's version is part of the data rather than part of the plan.
Prefer the database name over the binding name when you run migrations. The binding name can be changed by a refactor; the database name cannot. A pipeline that targets the binding can be pointed at the wrong database by an edit that looks like a rename.
Nested layouts are a glob, not a special case. ORMs that write one directory per migration are supported by setting a pattern, which must start with the configured directory. The recorded migration name becomes the path relative to that directory, so the ledger stays portable across machines. If your ORM generates the files, let the ORM generate them; the platform's own create command only writes top-level files.
A provisioner is not a migration system. Running SQL from a local-exec hook hides an imperative step inside a declarative plan: it has no ledger, it re-runs when the resource is replaced, and its success is recorded as an attribute rather than as an applied version. Worse, it sits inside the apply, so a failure leaves the graph half-applied and the schema half-changed at the same time. The only honest place for schema change is a job whose output is the database's own ledger.
Apply the schema before the code that needs it, and make both directions tolerate the other. Add a nullable column, deploy code that writes both shapes, backfill, then drop the old column in a later release. A rename is two releases, never one, because the old code keeps running while the new version rolls out. The same rule applies to a queue consumer: the message shape written by the producer must be readable by the consumer that is still on the previous version.
Record the bookmark before the migration, not after the incident. The time-travel command prints the current bookmark, which is the value you will restore to if the migration is wrong. Time Travel is always on and keeps thirty days on paid plans, seven on free. A bookmark older than that window is invalid, so an export to object storage is the only way to keep a copy beyond it.
Restoring is in place, destructive and reversible only by another restore. In-flight queries are cancelled, the database is overwritten, and the command returns the previous bookmark so you can undo the undo. That is a good safety property and a bad habit: take the bookmark first, and write it somewhere that survives the terminal session.
A migration record needs three values to be auditable. The file's checksum identifies exactly what ran, the ledger tail identifies how far the schema got, and the bookmark identifies the data state that preceded it. With those three, a second engineer can prove which schema is live without re-running anything. With only a ticket that says "migration applied", they can prove nothing and will re-run it.
%%{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
A["New file in the migrations directory"] --> B["Read the current bookmark
and write it into the release record"]
B --> C["Apply unapplied migrations
against the database name"]
C --> D{"Every statement committed?"}
D -->|"yes"| E["Ledger row present in d1_migrations"]
D -->|"no"| F["Stop the deploy pipeline,
do not retry blindly"]
F --> G{"Did the failure leave
partial DDL behind?"}
G -->|"no"| H["Fix forward with a new file"]
G -->|"yes"| I["Restore the recorded bookmark"]
E --> J["Verify schema and row counts"]
J --> K{"Verification passes?"}
K -->|"yes"| L["Deploy code that expects the schema"]
K -->|"no"| I
I --> M["Re-apply from the restored state"]
M --> J
H --> C
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 A,B,C,K primary;
class D,E,J secondary;
class I danger;
class F,G,H,M warn;
class L ok;
One pipeline owns migrations, and the lock is a concurrency group. Two runners applying the same directory is the most common way to get a half-applied schema. The ledger makes a second run skip applied files, but it cannot make two simultaneous runners polite, and an interleaved schema change is exactly as unpleasant as it sounds.
A failed migration may leave no ledger row and a half-changed schema. The next run then re-executes the same file and fails on a column that already exists. Write each file so it is either a single statement or guarded, and check the ledger before retrying rather than after the second failure.
| Symptom | Likely cause | First check |
|---|---|---|
| Duplicate column on re-run | partial apply, no ledger row | the ledger's contents |
| Foreign key violation during a rebuild | constraints checked mid-migration | the defer pragma at the top of the file |
| Migration targeted the wrong database | binding name used instead of database name | the command's target |
| Schema newer than the running code | code deploy skipped or rolled back | deployed version against ledger tail |
| Restore succeeded but queries fail | data rewound under newer code | code and schema compatibility |
The pipeline orders the steps that Terraform cannot. Terraform can order the database before the Worker version; it cannot place your SQL between them, because the migration is not an object in its graph. A release is therefore database, then migrations, then apply, then deployment verification, with the same commit identifier written into each record. If two of those records disagree about which commit they belong to, the release is already suspect.
Create Queue Topology Without Assuming Delivery Is Exactly Once
Queues promise delivery, not one delivery. The documented model is at least once, which means a consumer can see the same message twice, and a batch can fail after some of its messages were already handled. A design that treats a queue as a function call will double-charge someone eventually, and the second charge will look like a queue bug rather than a missing constraint.
Topology is four objects, and only three of them are automatic. A producer binding writes to a queue. The queue holds messages for its retention period. A consumer attachment invokes a Worker with batches. A dead-letter queue receives what the consumer could not finish. The producer binding lives in the Worker's binding array; the other three have resources or names you own.
A consumer is an attachment, not a binding. Attaching a Worker as a consumer is a property of the queue side, which is why the resource takes a script name and a queue identifier rather than appearing in the binding list. That also means the attachment can exist before the code that exports the handler does, and that gap is not visible in a plan. Order the attachment after the deployment, not after the Worker object.
| Setting | Terraform attribute | Default | Change it when |
|---|---|---|---|
| Batch size | batch_size | 10 messages, maximum 100 | the downstream API has a per-request limit |
| Batch wait | max_wait_time_ms | 5000 ms, maximum 60000 | latency matters more than batch efficiency |
| Retries | max_retries | 3 | a poison message should reach the dead letter faster |
| Retry delay | retry_delay | set it explicitly | the downstream needs time to recover |
| Concurrency | max_concurrency | unset, platform maximum | the database is the bottleneck, not the queue |
| Visibility | visibility_timeout_ms | 30000 ms | pull consumers need a longer lease |
| Dead letters | dead_letter_queue | none, failures are discarded | you want to replay instead of lose |
Duplicates have five ordinary sources, and only one of them is a retry. They are worth listing because each one suggests a different test.
| Source | What the consumer observes | What makes it safe |
|---|---|---|
| Delivery retry after a timeout | the same message again, later | a unique constraint on a message key |
| Partial batch failure | some messages already written | per-message acknowledgement |
| Visibility timeout expiry | the message reappears mid-work | an idempotency check before the write |
| Dead-letter replay | old messages re-enter the queue | the same key as the original attempt |
| Producer retry | two identical sends, no consumer error | a deterministic key chosen by the producer |
Idempotency belongs in the database, not in the consumer's memory. A unique index on the business key, an insert that ignores conflicts, and a read of the affected-row count is the whole pattern. It survives restarts, deploys and concurrency, which an in-process set does not. When the work must be serialized per key rather than merely deduplicated, a Durable Object is the better home, because one instance handles one key at a time.
Message shape is an interface, so version it with the payload. A consumer deployed after the producer ships may still receive messages written by the previous release, and a consumer that rolls back will receive messages written by the new one. Putting a schema version in the payload, and tolerating the previous version for one release, costs a field and removes an entire class of deploy-order argument.
Create the dead-letter queue as its own resource. A deployment tool that finds a missing dead-letter queue will create it for you, which is convenient and leaves an unmanaged queue in the account that no plan will ever mention. Referencing the queue's name from the consumer keeps the ownership visible and makes the retention setting reviewable.
Do not let two tools own the consumer settings. The same retry and batch values can be declared in the deployment configuration and in Terraform. The last deploy wins, so a release through the other tool can silently revert a reviewed retry policy, and the next apply can revert it back. The symptom is a settings diff that appears and disappears without anyone changing code, which is usually diagnosed as provider flakiness rather than as split ownership.
Pause before you purge. Pausing delivery stops consumers while messages keep accumulating, which is the correct move when the handler is wrong. Purging deletes every message in the queue and cannot be undone. One is a pause with a resume; the other is a data-loss event that happens to have a confirmation prompt.
Three incidents cover most of the operational surface. When the handler writes bad rows, pause delivery, fix the handler, and replay from the dead letters rather than purging, because the queue is now the evidence. When the database is saturated, lower consumer concurrency before raising retries, or the retries simply push the same load back into the same wall. When a deploy removes the handler, pause first; otherwise every message retries until it is discarded or lands in the dead letter with no consumer able to explain it.
Batch settings are a latency decision as much as a throughput decision. A large batch waits for the batch to fill or the timeout to expire, whichever comes first. Raising the size to reduce invocations can add seconds to every message, and lowering the timeout can produce many tiny batches that stress the database more than the larger ones would have.
Concurrency is the only setting that protects the database. The platform will scale consumers to its own maximum unless you cap them, and the maximum is chosen for the platform's throughput rather than for your query cost. A D1 database with a write-heavy consumer is the usual place where an uncapped consumer turns a backlog into a timeout storm; the cap is the backpressure valve, and it belongs in the same review as the query it protects.
Handle Durable Object and Workflow Evolution Explicitly
The class lifecycle is a deploy-time migration, not a resource attribute. Provider 5.28.1 exposes it on the Worker version as either a migration entry with a tag or an export entry with a state. Both are supported, and a single Worker must use one or the other. Choosing is a real decision: the tag form is ordered and auditable, the export form is declarative and reconciles namespaces against the code.
| Intent | exports entry | Legacy migration field | Data effect |
|---|---|---|---|
| Create a class | live entry with storage = "sqlite" | new_sqlite_classes | new empty namespace |
| Rename a class | state = "renamed" plus renamed_to | renamed_classes | storage follows the new name |
| Delete a class | state = "deleted" | deleted_classes | namespace and data destroyed |
| Keep serving | live entry, no state | no entry | no change |
Tags exist to make ordering checkable. The legacy form carries a new tag and an old tag, and the upload is rejected when the current tag does not match the expected one. That is an optimistic concurrency check on schema history: it catches a migration applied from a stale branch, which is precisely the failure a code review cannot see. The export form does not have that check, so it relies on reconciliation output instead, which is richer but arrives after the upload.
Read the reconciliation output, because the plan cannot predict it. The version resource reports which namespaces were created, renamed or deleted, and lists warnings and stale tombstones that are safe to remove. Those fields are populated only after the upload, so they are apply-time evidence rather than plan-time promises. A deploy that reports a class renamed when you expected no change is a deploy that needs a rollback decision, not a second apply.
A rename is two updates that are not atomic. The namespace's class pointer changes, and the Worker code that exports the class changes, in the same rollout but not at the same instant. During that window a request can resolve to a name with no class behind it. The documented remedy is three deploys: alias the new class under the old name, apply the rename while the alias is live, then remove the alias.
Code updates outlive the deploy, so storage changes must be backward compatible. The default strategy lets an active object keep its current code until it hibernates or five minutes pass, whichever comes first. A second deploy starts a second timer, and the first timer to expire makes the object adopt the latest version, not the version that started that timer. A gradual deployment extends the window further, because more than one version is serving at once.
That window is a schema-compatibility requirement, not a scheduling detail. If the new code adds a column that the old code cannot read, the old code is still writing rows during the window. Make the change additive for one release, or force an immediate update and accept that in-flight work is interrupted. The same trade-off appears in the migration section, which is not a coincidence: a Durable Object's storage is a database, and it deserves the same expand-then-contract discipline.
| Change | Risk during rollout | Mitigation |
|---|---|---|
| Rename a class | pointer moves before code exports the name | three deploys with an alias |
| Delete a class | data destroyed at deploy, no trash | export and verify first |
| Change storage shape | old code reads a new schema | additive fields, or immediate update |
| Add a class | none, namespace is new | declare it in the same apply |
| Move a class to another Worker | both sides must agree on the handoff | staged transfer, not a rename |
A Workflow definition is a Terraform object; its instances are not. The resource names a workflow, a script and a class, and sets concurrency, step limit and retention. Creating it does not create work. Instances are created at runtime, and their history is what makes a multi-step process resumable.
Concurrency is a policy, not a performance setting. The limit caps how many instances run at once and queues the rest, which makes it the right place to protect a downstream system that cannot absorb a burst. The step ceiling bounds a runaway loop before it exhausts the account. Retention decides how long a finished or failed instance can be inspected, and it is the difference between debugging a failure and reconstructing it from logs.
Step names are the durable identity, so treat them as an interface. A completed step is recorded by name, and a later version of the code that renames or reorders steps can leave a running instance unable to resume where it left off. Add a new step; do not rewrite an old one that instances may still need.
Every step can retry, so every step must be safe to repeat. A charge, an email or a row insert inside a step will run again after a transient failure. Check for the effect before causing it, or make the effect idempotent in the database, exactly as the queue consumer does. The documented rules for Workflows say the same thing in more detail, and they are worth reading before the first production instance rather than after the first double charge.
Deleting a class is the one operation with no undo. The tombstone requires the class to be gone from the code and no other Worker to bind it, and then it removes the namespace and its data permanently. Export first, confirm the export, remove the bindings, and only then deploy the tombstone. A tombstone that fails because another Worker still binds the class is the safe outcome; a tombstone that succeeds is irreversible.
A Workflow definition is cheaper to recreate than the instances it ran. Destroying the definition removes the handle, not the business outcome, but it also removes the record you would use to explain the outcome. Drain and inspect before you delete, and treat retention as part of the release contract rather than as a storage setting.
Test a Persistent State Change and Its Recovery Route
A stateful release needs a test that fails when the data is wrong, not when the plan is wrong. The scenario below is deliberately small: an orders table, a queue message per order, a consumer that records fulfilment, and a Durable Object that serializes work per customer. The change adds a coupon column and a new Workflow step. Every layer in the earlier diagrams is present exactly once, which is what makes the trace readable.
The test is a trace, not a unit test. Place one order, let the consumer run, confirm the row and the message outcome, then break the release on purpose and follow the recovery route. What you are recording is which actions restore which layer, and which actions only appear to.
| Action | Infrastructure | Code | Persistent data |
|---|---|---|---|
terraform destroy | deleted | unchanged | deleted with the database and namespaces |
| Deployment rollback | unchanged | previous version | untouched, and possibly incompatible |
| D1 restore to a bookmark | unchanged | unchanged | rewound, in place, destructive |
| Class tombstone | namespace deleted | changed | every instance's storage destroyed |
| Dead-letter replay | unchanged | unchanged | rows written again, deduplicated by key |
Destroy is not a rollback and a rollback is not a restore. A destroy removes the objects and the data behind them. A deployment rollback returns code and nothing else, so it can point old code at a newer schema. A data restore rewinds rows and leaves the code where it was, so it can point new code at an older schema. Only one of the three is reversible without a copy, and it is not the one people reach for first.
The recovery order is pause, identify, restore, verify, resume. Pause delivery so no new work lands during the repair. Identify the bookmark or export that precedes the bad change. Restore data, or roll the code back to a schema-compatible version, but decide which one first, because doing both blindly produces two changes to audit. Verify with a query rather than a dashboard chart. Then resume delivery and replay the dead letters at a rate the database can absorb.
The order exists because the two halves fail differently. Restoring data while newer code is live produces a schema mismatch that looks like a code bug. Rolling code back while newer data is live produces a missing-column error that looks like a data bug. Pausing first turns both into a single, explainable mismatch that you chose, which is the only kind of mismatch a review can approve.
Verification is two queries and one comparison. The row count for the affected key proves the write happened or was undone. The highest applied migration proves which schema the database believes it has. Comparing both against the release record is what turns "it looks fine" into a statement someone else can check.
When there is no usable bookmark, the recovery route gets longer but not impossible. Time travel has a window, and a database restored once already has a new history. The fallback is the last export plus a replay of the writes that followed it, with the ledger telling you which migration files to reapply and in what order. That path is slower and lossier, which is the argument for an export that outlives the platform's window rather than one taken only when someone remembers.
The trace is only useful if it survives the incident. Write the bookmark, the row counts, the deployed version and the dead-letter depth into the release record while the terminal is still open. A recovery that works once and cannot be described is a recovery that will be reinvented, badly, at three in the morning.
Review the stateful release
Execution status: design-only. The trace below was written against Terraform 1.17.1 and cloudflare/cloudflare 5.28.1, checked on 6 November 2026. It was not executed against a live account, so every expected result is documented behavior rather than a measurement.
Prerequisites. A disposable Cloudflare account, an API token with Workers, D1, Queues and Workflows write access, a scratch repository, a built Worker bundle, and a migration directory with one file. Use the smallest plan that supports the products you are testing, and never point the restore step at a database holding anything you want to keep.
The change under test. Add a nullable coupon column, write the coupon in the consumer, and add one step to the Workflow. Apply it as three separate records: the migration, the Terraform apply, and the deployment.
- Baseline the graph. Apply the configuration and confirm the plan is empty on a second run. Record the database UUID, queue name, workflow name and deployed version identifier in one line of the release record.
- Place one order. Submit a request with a known order key. Confirm one row exists and one message was produced; a second identical request is the duplicate test, not a repeat of the first.
- Read the ledger and the bookmark. Query the migration ledger and the time-travel bookmark before the new file is applied. Write both values down; the bookmark is the only restore point that will exist.
- Apply the migration. Run the migration job against the database name. Expect the ledger to gain one row and the column to be nullable, so the old code still writes successfully.
- Deploy, then verify. Apply Terraform, confirm the consumer attachment still targets the deployed script, then place a second order and check that the coupon is stored and the Workflow instance reaches its final step.
- Break it deliberately. Send a message whose payload violates the new constraint. Expect retries, then a dead letter once the retry ceiling is reached, and no partial row.
- Restore and observe the mismatch. Restore to the recorded bookmark while the new code is still deployed. Expect queries that reference the new column to fail. This is the lesson: the restore fixed the data and broke the code contract.
- Recover in order. Pause delivery, roll the code back to the previous version, confirm the row state, then resume and replay the dead letter. Record how long each phase took.
| Observation | Passing result | Failing result means |
|---|---|---|
| Second identical order | one row, one effect | the idempotency key is missing |
| Poison message | dead letter after the ceiling | retries are unbounded or the DLQ is unset |
| Restore with new code | mismatch is visible and explained | the test did not actually restore |
| Ledger after restore | tail moves back with the data | the migration was applied outside the backup window |
| Consumer after rollback | attachment still points at the live script | the attachment was created before the deploy |
Cost dimensions. A D1 database, two queues and a handful of messages sit in the lowest tiers; the real cost is the account and the time to tear it down. Workflow step charges apply per step, so keep the instance to a few steps and delete it after the run.
Cleanup. Destroy the root, then confirm in the dashboard that the database, both queues and the Workflow definition are gone. Export or delete the release record according to your retention policy, and keep the trace, not the credentials.
Sources. The provider schema for 5.28.1 was read directly with the schema command, and the behavior claims above follow Cloudflare's documentation for D1 migrations, D1 Time Travel, queue batching and retries, Durable Object class exports, Durable Object code updates, and Workers infrastructure as code.
Next in the Series
In Static Applications: Pages, Worker Assets and Custom Domains, we'll explore Manage hosting configuration while separating builds, content deployment and domain activation.