Back to Terraform

R2 and KV: Provision Storage Without Turning State into a Data Store

November 6, 2026 Wasil Zafar 31 min read

Manage buckets, namespaces and storage policy while keeping bulk content and runtime mutation in their proper workflows

Table of Contents

  1. Choose Object and Key-Value Storage by the Application Contract
  2. Provision Buckets, Namespaces and Bindings Separately
  3. Verify CORS, Lifecycle, Custom Domains and Jurisdiction
  4. Keep Bulk Content Uploads and Runtime Data Outside Ordinary State
  5. Prove Access and Cleanup Without Destroying Shared Data

Choose Object and Key-Value Storage by the Application Contract

The product names suggest a storage decision; the application contract makes it. A bucket and a namespace both accept writes and return reads, so either can be made to work for a small demo. They diverge on the questions that decide production behaviour: whether a read sees the last write, how large a single value may be, whether the client can enumerate keys, and whether data expires on a clock.

R2 is object storage with whole-object semantics. Each object is a byte sequence addressed by a key, and the API is S3-compatible: put, get, range read, copy, and list by prefix. Reads, writes, deletes and listings are strongly consistent globally, so a Worker that writes an object and immediately reads it sees its own write.

KV is a globally cached map, optimized for reads. Writes land in central stores and then propagate to caches; a change is usually visible immediately where it was made, but other locations may serve the old value for 60 seconds or more. Negative lookups are cached too, so a newly created key can appear missing for the same window.

The consistency question is a product requirement, not a tuning knob. If a workflow does write-then-read, or two clients must agree on a value, KV is the wrong primitive by design. R2 supplies that guarantee, and a Durable Object supplies it with atomic operations, which is the right answer for counters and coordination.

A concrete test separates the two behaviours. A Worker that accepts an upload, writes a status object, and redirects to a results page needs the next request to see that object; R2 passes and KV may not. A Worker that reads a feature flag on every request and tolerates a minute of staleness is the inverse case, where KV's cache is an advantage.

Size ceilings decide the shape of the payload. R2 holds objects up to 5 TiB, with a single-request ceiling just under 5 GiB and multipart above that; KV holds values up to 25 MiB, with 512-byte keys and 1 KiB of metadata. A payload measured in gigabytes is an object; a payload measured in kilobytes is a candidate for KV.

Enumeration is a first-class difference. R2 lists by prefix and delimiter, which supports a directory-like browse, a release manifest, or a cleanup job that walks one prefix. KV lists keys with a prefix and cursor, but it is not a query engine and has no delimiters; if the application needs to discover structure, that structure belongs in the key name or in a database.

Pagination is part of the contract too. Both services return keys in pages, so an inventory or cleanup job must loop until the cursor is exhausted instead of assuming one response is complete. A job that stops after the first page leaves objects behind and still reports success.

Cost follows the access pattern, not the brand. R2 bills storage and operations but not egress, which rewards large downloads; KV bills reads and writes and stores little, which rewards fan-out reads. Model the monthly operations before choosing, not after the first invoice.

Expiry means different things in each service. KV applies a per-key TTL at write time, with a minimum of 60 seconds, and the key disappears when it elapses. R2 has no per-object TTL; lifecycle rules delete by prefix and age or date, and evaluation is asynchronous, typically within 24 hours.

Write rate is the quiet constraint. KV allows one write per second to the same key, and R2 allows one concurrent write per second to the same object name; both return errors rather than queueing when exceeded. A hit counter, a leaderboard, or a lock is neither product's job, no matter how small the value is.

The state boundary is identical for both. Terraform provisions the container and its policy: the bucket, the namespace, CORS, lifecycle, a custom domain, and the binding name. It does not own the objects or the key-value pairs, and putting them in state turns a content pipeline into an infrastructure plan.

Figure 1 turns the contract into a short decision path, with the "neither" branch kept visible.

Choose Object and Key-Value Storage by the Application Contract
%%{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','signalColor':'#5a6e82','noteBkgColor':'#c4873b','noteTextColor':'#132440','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
    A["Access pattern"] --> B{"Must a read see
the previous write?"} B -->|"yes"| C["Durable Object or D1
atomic state"] B -->|"no"| D{"Whole object, range read
or prefix listing?"} D -->|"yes"| E["R2 bucket
strong and global"] D -->|"no"| F{"Small value with
a useful expiry?"} F -->|"yes"| G["KV namespace
eventual and cached"] F -->|"no"| H["Reassess the contract
before provisioning"] 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,D,F primary; class E secondary; class G ok; class C warn; class H danger;

The branch that exits to a Durable Object is not a failure. It is the correct answer when the contract requires atomicity or a per-key write rate above one per second. Choosing it early avoids building a cache-shaped workaround around a database-shaped problem.

Figure 2 shows the boundary the rest of the article depends on: a control plane that records names and policy, and a data plane that holds bytes the state file should never see.

Terraform owns the container and its policy, not the objects or key-value pairs Terraform configuration and state record bucket names, namespace identifiers, CORS, lifecycle and binding names. The R2 bucket holds objects and the KV namespace holds keys and values. A Worker reads and writes that data at request time through bindings, and the data never crosses back into state. One boundary, two planes Terraform control plane: names and policy bucket name and jurisdiction, namespace title and ID, CORS and lifecycle custom domain, binding names, and the account boundary No object bytes and no key-value pairs: state records identity, not content. state boundary: content never crosses upward R2 bucket Objects and metadata whole-object reads, range requests, prefix listing strong read-after-write consistency 5 TiB per object, 8 KiB metadata KV namespace Keys and values small cached values with a per-key TTL eventual, up to 60 seconds or more 25 MiB per value, 512-byte keys provisions provisions Worker runtime: bindings CONTENT and CONFIG request-time reads and writes, outside Terraform the data plane never writes back into the state ledger reads and writes reads and writes

Read the table as a set of tests, not a feature list. Each row is a question to ask before provisioning; a "no" on consistency or size usually settles the choice without further debate.

TestR2 objectsKV valuesWhat it decides
ConsistencyStrong read-after-write, list and deleteEventual, up to 60 seconds or moreWhether a read may return stale data
Unit and ceiling5 TiB per object, 1,024-byte key, 8 KiB metadata25 MiB per value, 512-byte key, 1 KiB metadataWhether the payload is a file or a field
EnumerationPrefix and delimiter listingPrefix and cursor listingWhether the app browses a hierarchy
ExpiryLifecycle by prefix and age or datePer-key TTL, minimum 60 secondsWhether data must vanish on a clock
Write rateOne concurrent write per second per keyOne write per second per keyWhether this is a counter or a session
Access pathS3 API, Worker binding, custom domainWorker binding, REST APIWhich client owns the read

The contract also decides the failure story. An R2 bucket that collects orphaned multipart uploads costs storage; a KV namespace that serves stale configuration costs correctness. The next section provisions both containers without pretending they are the same kind of resource.

Provision Buckets, Namespaces and Bindings Separately

Three objects, three identities, three lifecycles. A bucket is named and account-scoped; a namespace has an opaque ID and a human title; a binding is a name inside a Worker script that points at one of them. Treating the trio as one unit is how a rename becomes an outage.

The bucket's Terraform ID is its name. Import uses account, bucket name and jurisdiction, which is a hint that jurisdiction is part of identity rather than a cosmetic setting. The namespace is the opposite: the title is editable and the ID is generated, so never hard-code the ID in a variable or a Worker config.

A bucket cannot be renamed in place. Changing the name plans a create and a destroy, and the destroy is blocked while objects exist, so a "rename" becomes a migration. Derive the name from the environment and keep human labels in tags or documentation instead.

A bucket name is identity

Renaming a bucket plans a create and a destroy, and the destroy blocks while objects exist, so the change becomes a migration. Put environment and purpose in the name from the start; keep human labels in documentation where they can change for free.

Pin the versions before writing a resource. The example fixes Terraform 1.17.1 and provider 5.28.1, takes the account from a variable, and derives names from an environment string so the same root can build staging and production without copy-paste. The jurisdiction is explicit because it cannot be repaired later.

terraform {
  required_version = "1.17.1"

  required_providers {
    cloudflare = {
      source  = "cloudflare/cloudflare"
      version = "= 5.28.1"
    }
  }
}

variable "account_id" {
  type = string
}

variable "environment" {
  type = string
}

locals {
  bucket_name    = "site-content-${var.environment}"
  namespace_name = "site-config-${var.environment}"
}

resource "cloudflare_r2_bucket" "content" {
  account_id    = var.account_id
  name          = local.bucket_name
  jurisdiction  = "eu"
  storage_class = "Standard"
}

resource "cloudflare_workers_kv_namespace" "config" {
  account_id   = var.account_id
  title        = local.namespace_name
  jurisdiction = "eu"
}

Jurisdiction belongs at creation. For R2 the accepted values are default, eu, fedramp and us; for KV they are eu, fedramp and us. Neither service lets you move an existing container between jurisdictions, so a change in that field is a replacement, not an update.

Bindings are declared where the Worker lives. A bucket or namespace does not know which Worker uses it; the script's binding list does. Reference the resource attributes instead of repeating strings, so Terraform orders creation and a rename cannot leave a dangling name.

resource "cloudflare_workers_script" "app" {
  account_id  = var.account_id
  script_name = "site-${var.environment}"

  # Existing script content arguments omitted for clarity.
  bindings = [
    {
      name         = "CONTENT"
      type         = "r2_bucket"
      bucket_name  = cloudflare_r2_bucket.content.name
      jurisdiction = "eu"
    },
    {
      name         = "CONFIG"
      type         = "kv_namespace"
      namespace_id = cloudflare_workers_kv_namespace.config.id
    },
  ]
}

The reference is also the dependency edge. Because the binding reads the bucket name and namespace ID, Terraform creates the containers first and updates the script afterwards. A literal string erases that edge and produces an apply that fails only when the Worker is invoked.

Binding names are code, not infrastructure. Renaming CONTENT in the script block without changing the Worker source produces a runtime error that no plan can catch. Treat the binding name as part of the application's interface and review it with the code that reads it.

Use one root per environment, or one root with environment-scoped keys. Two roots that both declare the same bucket will fight over it; a single root with for_each over environment names keeps addresses stable. The key is the environment, never the generated ID.

Failure branches are predictable. A duplicate bucket name in the account fails at create; a jurisdiction edit plans a replacement; deleting a non-empty bucket fails at the API; a binding that names the wrong environment succeeds and serves the wrong data. Only the last one is quiet, which is why the binding deserves a review separate from the bucket.

Import is the repair path for a container created elsewhere. The bucket imports by account, name and jurisdiction; the namespace imports by account and ID. Import binds identity without changing data, and the first plan then shows whether the configuration matches the container that already exists.

Figure 3 follows the create order and puts the quiet failure beside the loud ones.

Provision Buckets, Namespaces and Bindings Separately
%%{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','signalColor':'#5a6e82','noteBkgColor':'#c4873b','noteTextColor':'#132440','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
    V["account_id and environment"] --> B["cloudflare_r2_bucket"]
    V --> K["cloudflare_workers_kv_namespace"]
    B --> C["cloudflare_r2_bucket_cors"]
    B --> L["cloudflare_r2_bucket_lifecycle"]
    B --> D["cloudflare_r2_custom_domain"]
    B --> RB["binding type r2_bucket"]
    K --> KB["binding type kv_namespace"]
    RB --> W["cloudflare_workers_script"]
    KB --> W
    B -.-> F1["Failure: name already used
in the account"] K -.-> F2["Failure: jurisdiction changed
means replacement"] W -.-> F3["Failure: binding names
another environment"] B -.-> F4["Failure: destroy with
objects still present"] 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 V,B,K,W primary; class C,L,D,RB,KB secondary; class F1,F4 danger; class F2,F3 warn;

A binding is not a permission grant. It exposes the bucket or namespace to the script, but the account token still needs the R2 and KV permission groups, and a public custom domain is a separate access path. Keeping those three ideas apart prevents "the binding exists, so access should work" debugging.

Two roots are better than one when ownership differs. If a platform team owns the bucket and an application team owns the Worker, publish the bucket name and namespace ID as outputs and consume them across the boundary. The ownership split is explicit, and neither team can delete the other's container by accident.

Verify CORS, Lifecycle, Custom Domains and Jurisdiction

Provider 5.x manages bucket policy, not just the bucket. CORS, lifecycle and custom domains are separate resources in 5.28.1, which means they can be reviewed, planned and destroyed independently. That is a change from older guides that reached for the AWS provider or the dashboard because the Cloudflare provider "did not support" the setting.

CORS is a browser contract, and it only applies when the request carries an Origin header. A command-line GET without that header will look as if the policy is missing. The provider resource takes a list of rules, each with allowed methods and origins, optional headers, exposed response headers and a preflight cache lifetime.

resource "cloudflare_r2_bucket_cors" "content" {
  account_id   = var.account_id
  bucket_name  = cloudflare_r2_bucket.content.name
  jurisdiction = "eu"

  rules = [{
    id = "public-assets"
    allowed = {
      methods = ["GET", "HEAD"]
      origins = ["https://www.example.com"]
      headers = ["if-none-match"]
    }
    expose_headers  = ["etag", "content-length"]
    max_age_seconds = 3600
  }]
}

Origins are matched as scheme, host and optional port, never as a path. A value with a trailing slash or a file path is invalid, a wildcard may appear once and can span periods, and ports cannot be wildcarded. If the browser sends an origin that is not in the list, the object still downloads for a direct request and fails for the page's JavaScript.

A permissive wildcard is a decision, not a shortcut. * allows any origin and is appropriate only for content that is already public and has no credentialed access. For anything behind a login, list the exact origins and keep the policy in review with the application's route table.

CORS changes are eventually visible and can be masked by cache. Propagation is usually quick but can take up to 30 seconds, and a custom domain that already cached an object will keep serving it without the new headers until the cache is purged. Purge the hostname after the apply, then repeat the preflight with the exact origin.

Lifecycle is a bucket-wide policy made of prefix-scoped rules. Each rule has an ID, an enabled flag and a prefix condition; actions can delete objects by age or date, abort incomplete multipart uploads, or move objects to Infrequent Access. An empty prefix means the whole bucket, which is the most common way a "temporary" rule deletes shared content.

resource "cloudflare_r2_bucket_lifecycle" "content" {
  account_id   = var.account_id
  bucket_name  = cloudflare_r2_bucket.content.name
  jurisdiction = "eu"

  rules = [{
    id      = "expire-build-artifacts"
    enabled = true
    conditions = {
      prefix = "artifacts/"
    }
    delete_objects_transition = {
      condition = {
        type    = "Age"
        max_age = 2592000
      }
    }
    abort_multipart_uploads_transition = {
      condition = {
        type    = "Age"
        max_age = 86400
      }
    }
  }]
}

Deletion is asynchronous, and the clock starts at the object's age. R2 typically removes an object within 24 hours of the expiration value it reports, and a newly applied rule may take time to reach existing objects. A test that uploads an object and waits a minute proves nothing; read the rule back and verify the configuration instead.

Give each retention class its own prefix. Artifacts, exports and user uploads rarely share a lifetime, and separate prefixes make each rule auditable. A single empty-prefix rule is easy to write and almost impossible to reason about six months later.

Two rules on the same prefix do not merge. When a delete and a storage-class transition fall within the same 24-hour window, delete wins. The default bucket lifecycle already aborts multipart uploads after seven days, so an explicit rule that also aborts them is a deliberate override, not a new safety net.

A custom domain is the production access path; r2.dev is a development URL. The custom domain resource requires a zone in the same account, creates the DNS record, and exposes ownership and certificate status as computed fields. The managed r2.dev domain is rate-limited and bypasses WAF and Access, so leaving it enabled after adding a custom domain leaves a second, weaker door open.

Caching on a custom domain deliberately relaxes R2's consistency. Once Cloudflare caches an object, an overwrite or delete can remain invisible until the TTL expires or the cache is purged. If the application depends on immediate visibility, read through the binding or the S3 API, not through the public hostname.

resource "cloudflare_r2_custom_domain" "assets" {
  account_id  = var.account_id
  bucket_name = cloudflare_r2_bucket.content.name
  domain      = "assets.example.com"
  zone_id     = var.zone_id
  enabled     = true
  min_tls     = "1.2"
}

Jurisdiction is a data-residency promise, not a latency hint. A location hint is best-effort and honored only on first creation; jurisdiction guarantees storage within a region and cannot be changed. Set it deliberately, record it next to the bucket name, and remember that a jurisdiction-specific S3 endpoint is required for object operations.

Jurisdiction constrains durable storage, not every cache. KV can cache values outside the jurisdiction on Cloudflare's network even when the namespace is jurisdiction-restricted; the guarantee covers where the data is durably stored. Read the data-location page for the exact promise before writing it into a compliance statement.

The binding enum is not identical to the bucket enum. In this release the bucket resource accepts default, eu, fedramp and us, while the Worker binding lists eu, fedramp and fedramp-high. Read both schemas before copying a value; a mismatch fails at plan time, which is the cheap place to find it.

Adoption is limited by import support. In 5.28.1, CORS, lifecycle and custom-domain resources do not support import. If the policy already exists in the dashboard, the first apply will overwrite it, so export the current JSON, put it in review, and treat the apply as a migration rather than an adoption.

Verification is two-sided: the API's view and the browser's view. Read the policy back through Wrangler or the S3 API, then make a real preflight and a real GET with an Origin header. A policy that exists but never reaches the response is a cache or origin-matching problem, not a Terraform problem.

# Read the policy back from Cloudflare.
npx wrangler r2 bucket cors list site-content-prod
npx wrangler r2 bucket lifecycle list site-content-prod

# Preflight and GET must both carry the request Origin header.
curl -si -X OPTIONS -H "Origin: https://www.example.com" \
  -H "Access-Control-Request-Method: GET" \
  https://assets.example.com/app.js

curl -sI -H "Origin: https://www.example.com" \
  https://assets.example.com/app.js

Keep Bulk Content Uploads and Runtime Data Outside Ordinary State

State is a control-plane ledger, not a content store. Every attribute of every managed resource is serialized into the state file, including values you might expect to remain remote. A bucket's name and policy belong there; a million object keys or a session token do not.

State is a ledger, not a drive

Terraform state should describe the bucket and its policy, never the objects inside it. Bulk data belongs in a sync pipeline, runtime values belong in the service, and a managed KV key is acceptable only as a small reviewed seed.

The provider has a resource for individual KV keys, and it is a trap for runtime data. cloudflare_workers_kv writes a key and its value through Terraform, so the value is stored in state and every rotation becomes a plan. Use it for a small, reviewed seed only, and never for values that change per request or per user.

Bulk objects move through a data pipeline. Wrangler can put a single object, the S3 API can sync a directory, and the Workers API can write at request time; all three bypass Terraform and none of them touch state. Choose the path by volume and cadence, then give it credentials scoped to object write on one bucket.

# One object, useful for a smoke test or a single asset.
npx wrangler r2 object put "site-content-prod/assets/app.js" \
  --file dist/app.js --content-type application/javascript --remote

# A release prefix avoids mirror deletes against shared content.
aws s3 sync ./dist "s3://site-content-prod/releases/2026-11-06" \
  --endpoint-url "https://<ACCOUNT_ID>.r2.cloudflarestorage.com" --region auto

# KV seeds are reviewed JSON, not per-request writes.
npx wrangler kv bulk put config-seed.json \
  --namespace-id "$KV_NAMESPACE_ID" --remote

Content sync is a release step, not an apply step. A sync should be idempotent, write to a versioned or content-addressed prefix, and verify checksums before it flips a pointer. Deleting from the destination is a separate, reviewed operation; a sync that mirrors deletions will happily remove objects another system still serves.

Content-addressed keys make the pipeline reversible. Writing assets/<hash>/app.js means a new release never overwrites the object a previous release serves, and rollback is a pointer change rather than a re-upload. The cost is a cleanup policy for old hashes, which belongs in the lifecycle rules.

KV seeds are configuration releases. Store the seed as a reviewed JSON file, write it with a namespace ID resolved from Terraform output, and give each key a TTL only when expiry is part of the contract. A seed that runs on every deploy and overwrites runtime state is a rollback generator.

A seed needs its own version marker. Write the schema version beside the values, so a Worker can detect an old seed instead of silently reading a shape it no longer understands. The marker is small, stable and worth more than any amount of deployment documentation.

Runtime writes belong to the Worker. A Worker binding can put an object or a key without any Terraform involvement, which is exactly what a session, a preference or an uploaded file needs. The binding name is the contract; the data is not.

Three cadences, three credential scopes. Infrastructure changes on merge, content on release, runtime continuously. A single admin token that can do all three makes every pipeline a potential destroyer of the others' data; split the tokens and the blast radius follows.

Figure 4 puts the three pipelines beside the one ledger they must not write into.

Infrastructure, content and runtime pipelines with one state ledger A merge runs Terraform and updates state. A release syncs objects into R2 and seeds reviewed values into KV. Runtime requests read and write through Worker bindings. Only the infrastructure pipeline writes state, and no content path crosses that boundary. Three cadences, one ledger Terraform state: names, identifiers and policy only bucket name and jurisdiction, namespace title and ID CORS, lifecycle, custom domain, binding names Infrastructure apply on merge plan, review, apply writes state creates containers Content sync on release versioned prefix checksums first never writes state KV seed on reviewed change JSON file in the repo explicit TTL per key never writes state Worker runtime: reads and writes through bindings per request, continuous, no Terraform in the path, no state mutation reads and writes state content paths never cross into state serves

Retention needs one owner per rule. Lifecycle rules, bucket locks and application TTLs can all remove data; overlapping rules produce surprises that look like data loss. Decide whether the bucket policy, the object's key prefix, or the application owns expiry, and document the answer where the next operator will find it.

Deletion is not the same as cleanup. Removing a Terraform resource deletes the container, while removing it from state only stops management. For a bucket with content, the first is an outage; for a namespace with keys, it is an outage plus data loss. Mark the containers that must survive a plan with prevent_destroy, and keep content deletion in the data pipeline.

The state file should be boring. If a plan ever shows object keys or KV values, the boundary has already been crossed; fix the configuration before the state grows and the secret spreads to every backend copy.

Use a remote backend with encryption and locking before the first shared apply. State will contain resource identifiers and binding names, and a local file on a laptop is a single point of failure. The backend is part of the storage boundary even though it lives outside Cloudflare.

Prove Access and Cleanup Without Destroying Shared Data

A storage boundary is proven by four separate checks. The binding resolves, the public path serves the object with the right headers, the lifecycle or retention rule is actually configured, and destroy refuses to remove data that still exists. Passing one check says nothing about the other three.

Four checks, four failure modes

Binding, public path, retention configuration and destroy protection each fail differently. Run all four on a run-specific container and record the results in the change ticket, or a green deploy will hide whichever check nobody performed.

Write the checks into the change ticket, not into memory. Each one has a different failure mode, and a reviewer who sees all four results can tell whether the boundary was tested or merely deployed. The ticket is also the place to record which container was disposable.

Use disposable containers with a run-specific suffix. Create a bucket and namespace for the exercise, never reuse a production name, and record the suffix in the change ticket. A test that writes into the real content bucket is not a test; it is an unannounced deployment.

Start with the private path. Invoke the Worker route that reads through the binding and confirm it returns the object you uploaded, then write a new key and read it back immediately. On R2 the second read must see the write; on KV the same check proves only local visibility, not global consistency.

Then prove the public path with an Origin header. A preflight OPTIONS request should return the allowed methods and headers, and a GET should return the matching allow-origin value plus any exposed headers. Without the Origin header, R2 returns the object but no CORS headers, which is the most common false negative.

Lifecycle proof reads the configuration, not the clock. R2 deletes asynchronously and typically removes objects within 24 hours of their expiration value, so an exercise cannot wait for the object to vanish. Read the rule back, confirm its prefix and age, and use a dedicated prefix so the rule's scope is visible in the response.

Cleanup starts by emptying the disposable bucket. R2 refuses to delete a non-empty bucket and the provider has no force-destroy switch, so list and delete the objects, abort incomplete multipart uploads, then destroy. For KV, deleting the namespace removes every key in it, which is why the exercise uses a namespace created for the run.

Guard the shared containers before the exercise, not after. A prevent_destroy lifecycle on the production bucket and namespace turns an accidental destroy into a plan error, and a comment that names the owner makes the intent visible. The disposable containers should not carry the guard, so cleanup remains possible.

Order matters when the Worker is shared. Remove or update the binding before destroying a container the production Worker still references; Terraform's graph will destroy the script if it owns it, but a script managed elsewhere will simply start failing at runtime. Check who references the bucket and namespace before approving the destroy.

Capture evidence that a reviewer can check. Save the plan output, the CORS response headers, the lifecycle rule as returned by the API, and the object count before and after cleanup. Screenshots of a dashboard are weaker evidence than four small text files with timestamps.

Lab

Verify the storage boundary

Execution status: design-only. The commands below were not run against a live account for this article. You perform the exercise with your own disposable names and keep the output; the evidence is yours, not a transcript.

Prerequisites. An account where you can create R2 buckets and KV namespaces, a token with the R2 and KV write permission groups, Terraform 1.17.1 with provider 5.28.1, Wrangler, and a Worker route that reads a bucket and a namespace through bindings. Use a bucket name and namespace title that include a run suffix you can identify later.

  1. Apply the containers only: the bucket, the namespace, and their bindings. Confirm the namespace ID in the output and that the bucket reports the jurisdiction you requested.
  2. Upload one small object under a dedicated test prefix, using the same path the content pipeline would use. Record its key and checksum.
  3. Read the object through the Worker binding, then write a second object and read it back in the same request. On R2 the second read must see the new bytes.
  4. Submit a preflight OPTIONS request with the real Origin header, followed by a GET with the same header. Record the status, the allow-origin value and every exposed header.
  5. Apply one lifecycle rule scoped to the test prefix, then read the policy back through Wrangler. Confirm the rule ID, prefix, age and action; do not wait for deletion.
  6. Attempt the destroy plan while one test object remains and confirm the API refuses the non-empty bucket. Then delete the test objects, abort any incomplete multipart upload, and apply the destroy.
  7. Delete the test namespace only after confirming no Worker binding still references it. A namespace delete removes every key, including keys written by the runtime.
  8. Run a final plan with detailed exit codes and confirm it is empty, then remove the disposable names from the review record.
CheckCommand shapePass looks like
BindingWorker route through CONTENT and CONFIGObject bytes and the seeded value are returned
ConsistencyWrite then read through the bindingR2 returns the new object immediately
CORSOPTIONS and GET with OriginMatching allow-origin and exposed headers
Lifecyclewrangler r2 bucket lifecycle listRule ID, prefix and age match the HCL
GuardrailDestroy with one object presentAPI refuses the non-empty bucket
CleanupEmpty, then destroy, then planDestroy succeeds and the plan is empty

Expected observation. The bucket and namespace appear in state with stable addresses, the Worker resolves both bindings, and the public object returns the configured CORS headers only when the request carries a matching Origin. The lifecycle rule is visible in the API response, but the test object is still present because its age has not elapsed and deletion is asynchronous. The destroy attempt fails while the object exists and succeeds after the prefix is emptied.

Failure checks. A binding that returns undefined usually points at a different environment's bucket or namespace. A GET without CORS headers but a successful body usually means the request lacked an Origin header or the cached response predates the policy. A lifecycle rule that disappears after apply usually means another root manages the same bucket. A destroy that removes objects without complaint means the container was empty or the test used the wrong bucket.

Cost dimensions. The exercise creates a few small objects and a handful of operations, which costs cents at most; KV's free allowance covers a short test. Storage and operations are the billable dimensions, and egress from R2 is not charged. Destroy the disposable containers to stop storage charges, and remove any test token when the exercise ends.

Cleanup. Empty the bucket, delete the test prefix, then destroy the bucket and namespace. Keep the production bucket's prevent_destroy guard in place, and verify that removing a test binding did not leave the production Worker pointing at a deleted namespace. If the exercise changed a shared CORS policy, restore the reviewed JSON and purge the custom-domain cache.

References (checked 6 November 2026): R2 bucket resource, R2 CORS resource, R2 lifecycle resource, R2 custom domain resource, KV namespace resource, R2 consistency, R2 object lifecycles, R2 CORS, KV consistency, KV limits, public buckets, and data location.

Next in the Series

In Stateful Workers: D1, Queues, Durable Objects and Workflows, we'll explore Coordinate infrastructure dependencies with separately versioned application schemas and state transitions.