Objects Have Keys and Metadata Rather Than POSIX Paths
There is no folder to rename. An engineer uploads avatars/u_1042/2026/11/headshot.jpg and looks for a way to rename the 2026 folder. The slashes are ordinary characters inside one string, and the bucket can only look up that string. A bucket is a flat, lexicographically ordered map from a key to an object, not a filesystem.
The vocabulary follows from that flat map. Each distinction below changes what an operation can do (Upload objects):
| Term or operation | Meaning | Operational consequence |
|---|---|---|
| Bucket | Account-scoped namespace plus configuration | One flat keyspace; no directory objects |
| Key | UTF-8 string of up to 1,024 bytes | Slashes are bytes; prefix plus delimiter only simulates folders |
| Object | Immutable byte sequence stored under one key | Overwrite replaces the whole body; no append or in-place edit |
| Metadata | System HTTP headers plus custom x-amz-meta-* pairs, capped at 8,192 bytes | Returned on a head request, not indexed or filterable |
| ETag | Opaque validator for one upload | Not necessarily the file's MD5; a multipart ETag is derived from its parts |
| Rename | CopyObject then DeleteObject | Two charges and a window in which both keys exist |
| Overwrite | Last writer wins | Sustained writes above roughly one per second to the same key return HTTP 429 (Limits) |
| Listing | Lexicographic and paginated; strongly consistent | Prefix plus delimiter produces the folder illusion; the usual failure is pagination, not stale keys |
Think of a coat check. The ticket number is the key; the coat and its claim tags are the object and its metadata. The ticket can contain slashes, but the rack is not a tree.
Key design is retention design
Lifecycle rules match prefixes, so a tenant-and-month key lets you expire one tenant or one month at a time; a key beginning with a random identifier gives you nothing to target. Metadata is a label, not a schema: R2 returns it on a head request but does not index or filter by it. For queries such as approved assets, keep the index in D1.
%%{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
U["Upload avatars/u_1042/2026/11/headshot.jpg"] --> K["Key: one UTF-8 string, max 1024 bytes"]
K --> F["Bucket: flat keyspace, lexicographic order"]
F --> O["Object body
bytes up to 5 TiB"]
F --> S["System metadata
Content-Type, Cache-Control, ETag"]
F --> M["Custom metadata
x-amz-meta-*, max 8192 bytes"]
F --> P["List with prefix and delimiter
avatars/u_1042/ plus /"]
P --> V["Virtual folders
no inode, no atomic rename"]
K --> L["Lifecycle rule
prefix avatars/, expire after 365 days"]
L --> X["Deletion typically within 24 hours"]
M -.->|"not indexed or queryable"| D["D1 for searchable attributes"]
V -.->|"move one key"| C["CopyObject then DeleteObject"]
F -.->|"two writers, same key"| W["Last writer wins
above 1 write/s returns 429"]
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 S primary;
class U,K,F,O,M,P,V,L,X,D,C,W secondary;
Figure 1 traces the upload through the flat keyspace. The solid path is the normal write and read model; the dashed edges are filesystem assumptions that do not hold. Lifecycle attaches to the key prefix, not to a folder object, and metadata sits beside the bytes rather than inside a searchable table.
Figure 2 separates the boundaries that are easy to conflate: the request names a key, the bucket resolves it to one object envelope, and configuration such as lifecycle lives on the bucket rather than on a folder. The body is not addressable in pieces except through byte ranges, which later sections use for media delivery.
R2 APIs and S3 Compatibility Boundaries
The endpoint and region are the only changes. The same call that writes to S3 writes to R2 when it points at the account endpoint with region auto, because R2 implements a documented subset of the S3 API.
Region is auto. Some tools insist on a real region; an empty value and us-east-1 alias to it.
Compatibility is an operation-by-operation matrix. A call that exists can still reject feature-level headers inside it, so test the exact combination you ship (S3 API compatibility):
| Operation or surface | Works | Gap to plan around |
|---|---|---|
PutObject | Writes, custom metadata, conditional writes | ACL, Object Lock, tagging, website redirect, and SSE-KMS headers are unsupported |
CreateBucket | Bucket creation | Bucket ACLs and x-amz-expected-bucket-owner are unsupported |
GetObject, HeadObject, CopyObject, DeleteObject | Reads, heads, copies, deletes, range reads, conditional headers, SSE-C | Same ACL and policy gaps as the write path |
| Multipart upload | Parts, completion, abort | The ETag is derived from the parts, not from the whole file |
ListObjectsV2 | Preferred listing with prefix and delimiter | Older ListObjects exists, but V2 is preferred |
| Presigned URLs | GET, HEAD, PUT, and DELETE | Presigned POST form uploads are unsupported (Presigned URLs) |
| Bucket policy, versioning, website hosting, replication, Object Lock configuration, S3 notifications | Not implemented | Do not design around them |
| Checksums | CRC-32, CRC-32C, SHA-1, and SHA-256 as composite; CRC-64/NVME as full-object | An SDK's default mode can fail before the object is written |
| Local development | Workers binding under wrangler dev | The S3-compatible endpoint is not available against local storage |
Compatible is not portable
A successful object write says nothing about ACLs, bucket policies, versioning, or presigned form uploads. Test the exact operation and headers your application sends; the compatibility page is a per-operation matrix, not a promise that an existing S3 application runs unchanged.
| Surface | Credential and scope | Operations | Choose it when | Hard boundary |
|---|---|---|---|---|
Workers binding (env.BUCKET) | Implicit in the Worker; no public endpoint | get, put, delete, list, multipart, ranges, conditional writes | Server-side code already runs in a Worker and the bucket is in the same account | Cannot generate presigned URLs; every caller reaches it through your Worker code |
| S3 API | R2 API token access key and secret, scoped to a bucket and permission group | Broad object and bucket subset from the compatibility matrix | Existing S3 SDKs, CLI tools, rclone, browser uploads via presigned URL | No IAM policies, ACLs, versioning, Object Lock, website hosting, or S3 notification configuration |
| Cloudflare REST API | Cloudflare API token | Control plane: buckets, CORS, lifecycle, custom domains | Infrastructure automation and drift checks | 1,200 requests per five minutes per account; not the data path |
| Public custom domain | None for public reads; WAF, Access, or token auth can be layered on | GET and HEAD for objects | Public assets that need cache, WAF, and bot management | No bucket root listing; cached responses can outlive a delete or overwrite |
| Presigned URL | Signature in the query string, derived from an R2 API token | One operation on one object: GET, HEAD, PUT, or DELETE | Time-limited browser download or direct upload without proxying bytes | S3 host only, not custom domains; 1 second to 7 days; bearer token, not a session |
Choose by client and failure boundary. The Workers binding is simplest when the Worker is the only client, but it cannot mint presigned URLs, so browser uploads need an S3 client. The S3 API is broadest but carries the compatibility gaps. The REST API is for configuration, not object traffic.
R2 tokens are not IAM
R2 does not use AWS IAM. An R2 API token carries a permission group and, preferably, a bucket scope; the token yields an access key ID and secret that SigV4 clients use. An AWS profile, role, or instance profile is not portable. Rotation is a token operation, not an IAM policy change. Permission changes can take up to a minute to propagate, while object operations are strongly consistent (Consistency model).
Two traps before the write
Checksum defaults are the first trap: CRC-64/NVME is full-object only, while CRC-32, CRC-32C, SHA-1, and SHA-256 are composite only, so an SDK that defaults to the wrong mode can fail before the object is written. Local development is the second: the S3-compatible endpoint is not available against local storage, so only a Worker using the binding can be tested that way.
%%{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 B as Browser
participant W as Worker
participant R as R2 S3 endpoint
B->>W: POST /upload-url with session cookie
W->>W: verify session, build key, sign PUT
W-->>B: presigned URL, expires in 300 seconds
B->>R: OPTIONS preflight with Origin and Content-Type
alt origin is in the bucket CORS policy
R-->>B: 204 with Access-Control-Allow-Origin
else origin is missing or malformed
R-->>B: response without CORS headers
Note over B,R: Browser blocks the PUT before it is sent
end
B->>R: PUT signed URL with Content-Type
alt signature valid and not expired
R-->>B: 200 with ETag
else expired, tampered, or header mismatch
R-->>B: 403 ExpiredRequest or SignatureDoesNotMatch
end
B->>W: POST /download-url
W-->>B: presigned GET, 60 seconds
B->>R: GET with Range bytes=0-1023
R-->>B: 206 Partial Content
Each failure branch has a different owner. The Worker authenticates the user and chooses the key; R2 verifies the signature and enforces expiry; the browser enforces CORS. A missing CORS header fails before the PUT leaves the browser. A signature mismatch fails at R2 and usually means a signed header such as content type changed after signing. An expired request means the URL outlived its validity window.
The panels are two halves of one check. The TypeScript panel authenticates a caller, constrains the content type, builds a tenant-scoped key, and signs a five-minute PUT with the content type included in the signature. The bash panel creates a 12 MB fixture, writes it, reads its metadata, installs CORS, presigns a GET, requests the first 1 KB, then proves a five-second URL is rejected after six seconds. The expected status for the last command is 403.
Private Objects, Signed Requests, and Public Delivery
A new bucket is private. It has no public hostname until you enable one, and every S3 request must be signed or use a presigned URL. "Public" in R2 is a bucket-level delivery decision, not a per-object permission bit. There are three ways to get bytes to a reader, and they fail differently.
Public bucket through a custom domain. This is the production path. The domain must be a zone in the same Cloudflare account. R2 serves it through Cloudflare's cache and security layers, so you get cache rules, WAF, bot management, Access, and URL-level analytics. A bucket supports up to 100 custom domains. The bucket still does not allow listing at the root, so an object is reachable only if you know its key (Public buckets).
Public development URL. The r2.dev hostname is for testing. It is rate-limited at hundreds of requests per second, returns a 429 when exceeded, and may throttle throughput. It gives you no cache controls, WAF, or bot management. Cloudflare calls it non-production and warns against putting a CNAME in front of it (Limits).
Presigned URL or Worker proxy. These are the private paths. A presigned URL is a SigV4 signature in the query string that authorizes one operation on one object until it expires. R2 supports get, head, put, and delete on a single object, with an expiry from one second to seven days, and the URL can be reused until the deadline. Signing is server-side with no call to R2, so a Worker can mint a URL without a round trip. The URL is a bearer token: anyone holding it can perform the operation. You cannot revoke one URL before expiry; rotating the access key invalidates every URL signed with it.
A custom domain does not disable r2.dev
A team enables the development hostname for a demo and pastes object links into a shared document. Later it adds a custom domain and Access, believing the bucket is private. It is not: the development hostname is still enabled and the old links still resolve. Inventory every public surface, disable the development hostname on production buckets, and check whether a presigned URL leaked into logs; a URL in an access log is a working credential until it expires.
CORS is not authorization
CORS is a browser policy, not an access control. A presigned URL can be valid and still fail in a browser because the bucket has no rule for the page's origin. The preflight asks whether the origin may send the method and headers, and R2 answers only on a match. An origin is scheme plus host, optionally a port, with no path; one wildcard is allowed per pattern, and propagation can take 30 seconds. The same rule does not make an object private: server-side clients and attackers ignore it (Configure CORS).
Ranges are how media players seek and download managers resume. A ranged GET returns partial content with a content-range header, and a head request exposes size and type without the body. A Worker using the binding can pass a range option and stream the selected bytes; a presigned URL can carry the same header. Buffering the whole object into Worker memory loses the benefit and risks the memory limit.
Lifecycle, Uploads, Ranges, and Cost Drivers
Lifecycle rules turn object storage from an ever-growing pile into a retention policy. A rule selects a prefix and either expires objects after a number of days or on a date, or transitions them from Standard to Infrequent Access. R2 has a default rule that aborts incomplete multipart uploads after seven days, and you can tighten it per prefix. Applying a deleting configuration sets x-amz-expiration on new objects immediately, but existing objects may take longer; deletion typically happens within 24 hours of the expiration value (Object lifecycles).
Three details matter. Expiration is asynchronous, so a 90-day rule does not guarantee deletion at 90 days and one second. A transition to Infrequent Access is a Class A operation, and IA has a 30-day minimum duration plus a retrieval fee, so moving small or frequently read objects can cost more than Standard. When a transition and an expiration conflict inside 24 hours, expiration wins, so design rules with unambiguous intent.
Uploads have their own boundary. A single PUT carries up to 5 GiB. Larger objects need multipart: up to 10,000 parts, each at least 5 MiB except the last, with a maximum object size of 5 TiB. The ETag of a multipart object is derived from the parts' MD5 sums and is not the MD5 of the whole file, so never compare it to a locally computed whole-file hash. Re-uploading a part number replaces the old part; if that upload fails, the original is gone. Incomplete uploads remain until the lifecycle rule aborts them.
Range reads and conditional requests make the bucket a delivery layer. A ranged read returns partial content, and a head request exposes size and metadata without the body. The standard match and date validators let a client skip an unchanged object. A write with If-None-Match: * is atomic, so among concurrent writers to an absent key at most one succeeds and the rest receive a precondition failure (S3 API compatibility).
Cost makes the architecture visible. R2 charges for storage and two operation classes, with no egress charge for any storage class. As of 2026-11-05, Standard storage is $0.015 per GB-month, Class A is $4.50 per million, and Class B is $0.36 per million. Infrequent Access is $0.01 per GB-month, $9.00 per million Class A, $0.90 per million Class B, plus $0.01 per GB retrieved. The free tier is 10 GB-month of Standard storage, one million Class A, ten million Class B, and free egress. Billing rounds up; failed authentication is not charged (Pricing).
A calculation from list prices, not a quote, makes the tradeoff legible. Twenty terabytes of Standard storage is about 20,480 GB, roughly $307 per month after the allowance. Fifty million Class B reads is about $14 after the 10 million allowance. Serving that 20 TB once adds no egress charge. A store that bills data transfer out may charge more; use current AWS rates for your region. The inversion to watch is request-dominated workloads: 500 million Class B reads is about $176 per month, which can exceed storage cost for a small, hot object set.
Figure 4 contrasts the two retention postures. The upper lane is the default: Standard storage forever, with cost proportional to everything ever uploaded. The lower lane is a policy: Standard for the hot month, Infrequent Access for the warm months, expiration after the retention window, and automatic abort for uploads that never completed. The lower lane is not automatically cheaper, because the transition is a Class A operation and IA has a minimum duration and retrieval fee, but it is the only lane where retention is an explicit decision.
R2 fits immutable blobs read by key: uploads, media, backups, model artifacts, and logs. It is wrong for coordinated reads (KV), relational queries (D1), or transactional coordination (Durable Objects) (Choose a data or storage product).
Design an Authorized Upload and Download Flow
This exercise builds the flow from Figure 3 with a real bucket: authenticated upload URL, direct PUT, presigned download, CORS preflight, range read, expiry rejection, and a lifecycle rule. It is designed for a Free account and uses only controlled resources under a disposable prefix.
Design an Authorized Upload and Download Flow
Status: design-only — not executed for this draft. The commands follow the documentation reviewed on 2026-11-05, but no bucket was created, no URL was signed, and no request was sent. Expected observations are documented behavior and arithmetic from list prices, not measured results.
Prerequisites and plan requirements. A Cloudflare account with R2 enabled, Node.js 20 or later, npm, AWS CLI v2, curl, and grep. No paid Workers plan is required; the R2 free tier covers this volume. You need permission to create a bucket, an R2 API token with object read and write access scoped to that bucket, and your account ID. A custom domain is not required; the exercise stays on the S3 endpoint.
Inputs. A disposable bucket name such as r2-lab-initials, the account ID, the token's access key ID and secret access key, and a 12 MB fixture generated locally. Export the four values the bash panel expects and set the region to auto.
- Run the bash panel from the previous section. It creates the bucket if absent, uploads a 12 MB fixture with custom metadata, prints the head response, installs CORS for the local origin, presigns a GET, and fetches the first 1 KB.
- Confirm the object with a head request. Expect a content length of 12,582,912 bytes, the octet-stream content type, and the custom metadata key set by the panel.
- Confirm the range read. Expect partial content, a content-range header that begins at byte 0 and ends at byte 1023, and exactly 1,024 bytes in the downloaded chunk.
- Confirm CORS. Send a preflight to the object path with the local origin, the PUT method, and the content-type request header. Expect the allowed origin echoed back. Repeat with an unlisted origin; expect no allow-origin header.
- Confirm expiry. The script presigns a five-second URL, waits six seconds, then prints the status. Expect 403; a 200 means the clock or expiry setting is wrong.
- Confirm unauthorized rejection. Request the object path without a signature; expect 403 with an access-denied code. Change one character in a valid URL's signature; expect 403 with a signature-mismatch code.
- Add a lifecycle rule that expires the tmp prefix after one day, upload a probe object there, and run a head request. Expect an expiration header. Do not expect deletion on a stopwatch; it is asynchronous and typically completes within 24 hours.
- Optionally run the TypeScript panel end to end. Replace the demo user-id header check with your real session check before treating the result as an authorization test.
Expected observations. The happy path is a 200 PUT with an ETag, a 206 range GET with 1,024 bytes, a preflight that echoes the allowed origin, and 403 for the unsigned and expired requests. A listing of the lab prefix should return the fixture and no tmp key.
Failure checks. A signature mismatch on a presigned PUT usually means the client changed the content type from the signed value. A preflight with no allow-origin header means the origin is missing, includes a path, or uses more than one wildcard. A too-small entity means a multipart part under 5 MiB was not the last part. An invalid range is a 416 and means the start offset is beyond the object size. A missing upload means the multipart upload was aborted or the ID is wrong.
Cost dimensions. A 12 MB object, a few dozen operations, and minutes of storage are inside the free tier. Beyond it, storage is $0.015 per GB-month as of 2026-11-05; requests are $4.50 per million Class A and $0.36 per million Class B. No egress charge applies. Re-check pricing before repeating at scale.
Cleanup. Delete the objects, then the bucket; R2 refuses to delete a non-empty bucket. Remove the local fixture, chunk, headers, and CORS files. Revoke the R2 API token and delete any Worker or local project.
The exercise is front-loaded with rejection tests. A flow that only demonstrates the happy path has not tested authorization; the unsigned, tampered, and expired requests are the evidence that the gate works. Step 8 is optional because the Worker adds an application-specific session layer, while steps 1 through 7 test the R2 boundary common to every implementation.
Reject Unauthorized Requests and Validate CORS Behavior
Verification date: 2026-11-05. Basis: official Cloudflare documentation reviewed on that date. Execution status: design-only; no AWS, Wrangler, curl, or Node command was run. Tested versions: none recorded.
Pass evidence. A correct implementation should produce all of the following:
- An unsigned GET returns 403 with an access-denied code, and a tampered signature returns 403 with a signature-mismatch code.
- A presigned URL past its expiry window returns 403; the same URL works before the deadline.
- A preflight from an allowed origin returns an allow-origin header; a disallowed origin returns no such header.
- A
Range: bytes=0-1023request returns 206 with a content-range header and exactly 1,024 bytes; an out-of-bounds range returns 416. - A create-only write with
If-None-Match: *succeeds once for an absent key and returns 412 to the loser of a race. - A head request after a lifecycle rule shows an expiration header, while the object remains readable until asynchronous deletion.
Fail signatures. A 403 on a presigned PUT with a correct signature usually means a signed header changed. A 403 on a presigned GET from a custom domain means the URL was generated for the S3 host. A missing CORS header on an expired URL is expected, and browser JavaScript cannot read the error body. A 404 that persists after an upload on a custom domain is probably a cached 404.
Self-check. Answer before reading the explanations.
- Is a presigned URL a login session? No. It authorizes one operation on one object until it expires, and it is a bearer token. It cannot be revoked individually; rotating the signing key invalidates every URL signed with it.
- Does a CORS rule protect the bucket? No. Browsers enforce CORS; server-side clients ignore it. Bucket exposure, token scope, and signature validity are the access controls.
- Does a lifecycle rule delete exactly at the configured age? No. Deletion typically happens within 24 hours, with larger buckets taking longer. Do not use lifecycle as a synchronization primitive.
- Is "S3-compatible" a guarantee that an existing S3 application works unchanged? No. The compatibility page is an operation-level matrix with feature gaps. ACLs, bucket policies, versioning, Object Lock, website hosting, tagging, SSE-KMS, and S3 notification configuration are not implemented.
Unresolved limitations. This draft did not execute the exercise, so no latency, throughput, error rate, or bill was measured. Lifecycle timing is "typically within 24 hours," not a guaranteed deadline. Pricing and free-tier allowances are dated to 2026-11-05 and will change. The S3 compatibility matrix is a work in progress, so support can change. WAF HMAC validation requires Pro or above.
Authoritative references.
- Cloudflare R2
- S3 API compatibility
- Presigned URLs
- Public buckets
- Configure CORS
- Object lifecycles
- Upload objects
- Limits
- Pricing
- Consistency model
- Use R2 from Workers
- Workers API reference
- Choose a data or storage product
Next in the Series
In Build Relational Features With D1, we'll explore Treat schema changes and query behavior as production decisions.