Images Need Sizes, Formats, and Access Policy
Imagine a museum publishes 12,000 archival photographs and a few recorded tours. The first version points every page at the original scan. On a phone, a 6,000-pixel photograph is downloaded into a 390-pixel card, and the page's largest image arrives late.
The fix is not one product. It is three separate decisions:
- Geometry: which pixels are needed for this slot and screen?
- Encoding: which format and quality should carry them?
- Authorization: who may fetch this rendition, and for how long?
A print shop keeps one high-resolution negative and fills orders for different print sizes. Media delivery works the same way: store once, derive many, authorize each delivery.
The source image or master is the original you keep for durability. A variant is a named output recipe, such as thumbnail at 320 pixels. A transformation is a request to produce an output using parameters such as width, fit, format, and quality. Format negotiation chooses an encoding the browser can decode, usually from its Accept header. A signed URL is a capability URL: possession, plus a valid signature and usually an expiry, is permission to fetch.
Three independent layers
Geometry, encoding, and authorization fail separately. A cache policy does not fix an image that is four times too large. A correct size does not protect a private original. A signed URL does not make a slow video start faster.
Figure 1 separates the request paths so failures land on the right layer.
%%{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
B[Browser: viewport, DPR, Accept] --> Q{Which URL?}
Q -->|original object| R[(R2 or origin master)]
Q -->|variant request| E[Edge: parse variant and params]
E --> A{Signed URL required?}
A -->|no| C{Cache hit for source + params?}
A -->|yes| V{exp and signature valid?}
V -->|no| D[Refuse delivery]
V -->|yes| C
C -->|yes| S[Serve encoded variant]
C -->|no| O[Fetch source image]
O -->|missing or 4xx| X[9404 or 9408 error]
O -->|ok| T[Resize, encode, store derived object]
T --> S
S --> B
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 E primary;
class B,Q,A,D,S,O,T secondary;
class C,V ok;
class X danger;
Figure 1 also shows why "put a CDN in front" is incomplete. A CDN caches an object; it cannot invent a missing size unless something performs the derivation. Cloudflare offers four related tools: raw R2 objects, transformations for images stored elsewhere, hosted Images with variants, and Stream for video.
Figure 2 turns the flow into boundaries. The browser owns viewport, pixel density, and Accept. The edge owns derivation, cache lookup, and authorization. Storage owns the master bytes.
Cloudflare Images and Transformation Workflows
Suppose the museum keeps its masters in R2. It has four plausible designs, and they differ in who derives the rendition and what the bill counts (Images pricing, transformations overview, Stream pricing).
| Option | What you store | Derivation | Access control | Billing unit | Best fit |
|---|---|---|---|---|---|
| Raw R2 object | Original bytes, any size | None; your app or Worker builds it | Public custom domain or presigned R2 request | Storage and operations; egress free | Masters, downloads, non-image assets |
| Image Transformations | Original in R2 or another allowed origin | On-demand resize and format conversion via /cdn-cgi/image/ | Zone rules, origin allowlist, WAF | Unique source-plus-parameter transformations per month | Large libraries you already host |
| Hosted Images | Image uploaded to Images, 10 MB per file | Named variants, up to 100, or custom options | Per-image signed URLs; variants can be forced public | Images stored plus images delivered | Managed upload and private delivery |
| Stream | Video original uploaded or fetched by link | Transcoding and packaging into HLS and DASH | Signed playback tokens and allowed embed origins | Minutes stored plus minutes delivered | On-demand and live video |
The first row is the control case. R2 stores durable objects and charges no egress, but a public custom domain serves the object you uploaded, not a resized version. Cache rules make repeat delivery cheaper; they cannot change the pixels (R2 pricing, public buckets).
The second row derives renditions at request time. A transformation URL names its options before its source, so the edge can parse width, fit, and format from the path. On a hit it serves the stored rendition without touching the origin; on a miss it fetches, encodes, caches, and serves (transformations overview).
Hosted Images trades control for management. The third row moves the bytes into Images storage and gives you named variants. Hosted images default to format=auto, support up to 100 predefined variants, and can require signed URLs per image or variant (create variants). Upload once, then request https://imagedelivery.net/<ACCOUNT_HASH>/<IMAGE_ID>/<VARIANT>. The tradeoff is a 10 MB per-file upload limit for hosted images, versus 100 MB for remote transformation sources (limits).
Quota stops new work, not cached work
After the documented free-plan allowance of 5,000 unique transformations in a month, cached transformations keep serving, new ones are rejected with 9422, and the original is the fallback. Parameter validation fails earlier with 9401, while a missing source fails later in the same flow, so triage the three as separate classes (Images pricing, troubleshooting).
Figure 3 traces the workflow and its failure branches.
%%{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
participant B as Browser
participant E as Edge
participant C as Cache
participant O as Source origin
B->>E: GET variant with width and format
E->>E: Validate parameters and quota
alt Invalid or over quota
E-->>B: 9401 or 9422 error
else Valid request
E->>C: Look up source plus parameters
alt Cache hit
C-->>E: Cached derived object
E-->>B: 200 with Cf-Resized header
else Cache miss
E->>O: Conditional GET for source
alt Source missing or denied
O-->>E: 404 or 403
E-->>B: 9404 or 9408 error
else Source available
O-->>E: 200 original bytes
E->>E: Resize, encode, store
E-->>B: 200 derived object
end
end
end
Note over B,E: New width or new source URL
means a new unique transformation
Responsive markup lets the browser choose. List candidates in srcset with width descriptors and describe the slot with sizes; the server does not guess the device. Cloudflare also supports width=auto, which selects from client hints or a user-agent fallback using default breakpoints of 320, 768, 960, and 1200 pixels, and dpr up to 2 for high-density screens (make responsive images, features).
Format negotiation follows the client. format=auto serves the most efficient format the browser advertises, falling back when AVIF encoding would be too slow or the image too large. A custom Worker that negotiates itself must read Accept; the edge will not infer it (features).
The product boundary matters. Transformations are enabled per zone, and the default source policy accepts only images from that zone. Hosted storage is a paid-plan capability; the free plan includes transformations with the 5,000-unique allowance. AVIF input is Enterprise-only, and private hosted images do not support custom paths. Confirm the current plan matrix before designing around these (pricing, limits, private images).
A cost sketch makes the tradeoff concrete. If 12,000 images are requested at six widths, that is 72,000 unique transformations. The first 5,000 are included, and 67,000 at $0.50 per 1,000 is about $33.50. The same library in R2 at 4 MB per file is 48 GB; 38 billable GB at $0.015 per GB-month is about $0.57. These are list-price estimates, not quotes. Transformation count, not stored bytes, often dominates an image bill.
Stream Handles Video Ingestion and Playback
Video is not a large image. A two-hour MP4 forces the player to fetch a container with interleaved metadata and seek within a growing file; changing quality means starting another file. Adaptive streaming replaces that with a manifest of renditions and short segments the player can switch between as throughput and buffer health change.
| Behavior | Progressive MP4 | Segmented HLS or DASH |
|---|---|---|
| What the player fetches | One file, read with range requests | A manifest, then short segments |
| Quality switching | Restart from a different file | Switch at the next segment boundary |
| Startup | Waits on container metadata and a growing buffer | Starts once the first segments are buffered |
| Seeking | Jumps inside one large object | Fetches the segment that covers the target |
| Caching | One large object, partially cached | Each segment is its own cache entry |
| Best fit | Short clips, downloads, archival | Long or live playback on mixed networks |
Adaptive streaming is what lets a phone on a train keep playing while a desktop receives a sharper stream.
Cloudflare Stream owns that pipeline. Upload a file, provide a URL, or issue a one-time direct-creator link. Stream accepts MP4, MKV, MOV, AVI, WebM, MPEG-TS, and other common containers, with a 30 GB maximum, and re-encodes into HLS and DASH renditions (upload videos). Ingestion and encoding are not billed separately. Storage is prepaid at $5 per 1,000 minutes; delivery is post-paid at $1 per 1,000 minutes (Stream pricing).
Direct creator upload keeps bytes off your server. Your backend mints a one-time URL, the browser uploads straight to Stream, and the reservation is released when the upload completes or expires (direct creator uploads).
A simple POST is capped at 200 MB, so larger or unreliable connections should use resumable tus instead.
Playback uses the Stream Player or your own HLS or DASH player. The manifest lists the renditions; the player chooses. clientBandwidthHint returns the rendition closest to a requested bitrate, but it is a diagnostic override, not a production default (use your own player).
A token is not a playback pipeline
A signed URL is not a substitute for a playback pipeline. A long-lived token in front of a single 2 GB MP4 still gives viewers a progressive download with no adaptive renditions; the token controls who may fetch the file, not whether playback starts quickly. Conversely, HLS does not make a video private unless requests are actually authorized.
Video failures split into two classes. Packaging problems appear as slow startup, buffering, or an undecodable stream. Authorization problems appear as a manifest that loads but segments that fail, or an embed that works on one domain and not another. Stream's allowed-origin setting controls which domains may embed a video; signed tokens control which viewers may request manifests and segments (securing your Stream).
A realistic scenario: 300 recorded tours, eight minutes each, are 2,400 minutes of storage, rounded into three $5 blocks, or $15 per month. At 20,000 complete views, 160,000 minutes delivered costs $160. A single 1080p MP4 at roughly 5 Mbps is about 300 MB per view, or 6 TB for the same traffic. R2 would not charge egress for those bytes, but it would still serve a progressive file. Stream's price buys transcoding, adaptive renditions, and a player, not cheaper bandwidth.
Media Authorization and Cost Drivers
Authorization is a capability decision. A public gallery image can be fetched by anyone who knows the URL. A private image or video needs a check on every request that returns bytes, not just on the page that contains the embed.
Hosted Images signs each delivery URL. The URL carries an exp timestamp and an HMAC-SHA256 sig query parameter. Your backend holds the signing key, builds the exact path and query string, and returns a short-lived URL. The browser fetches the image directly, without proxying bytes through your Worker. If an image requires signed URLs and the token is missing or invalid, it cannot be accessed unless a variant is explicitly configured to always allow public access (serve private images, Images binding).
Stream swaps the video ID for a signed token. The token appears in player, manifest, and thumbnail URLs, and can carry expiry, not-before, download permission, and IP or country rules. Expiry cannot exceed 24 hours beyond signing time. For low volume, the /token endpoint returns a one-hour token; at scale, sign with a key or use the Workers binding so the key never enters your application (securing your Stream).
Figure 4 contrasts the shapes. A public URL is a permanent capability: anyone who copies it can fetch the object until the object or URL changes. A signed URL adds a verification step; when you set an expiry, the edge checks signature and expiry, and the URL stops working after the window closes. Set that expiry deliberately: the Images binding can generate a signed URL without one if expiresIn is omitted.
Cost follows the dimensions you vary. Each product meters something different, and the exemption list is where budgets leak (Images pricing, Stream pricing).
| Meter | Billed per | What counts | What does not |
|---|---|---|---|
| Image transformation | Unique source plus parameters, per calendar month | Width, height, fit, and DPR changes | Repeated identical requests; format and quality changes do not add uniqueness |
| Hosted Images storage | Image stored per month | Every image held in Images | — |
| Hosted Images delivery | Successful response larger than 1,024 bytes | Delivered image bytes | Failed or tiny responses |
| Stream storage | Minute stored | Total duration held | — |
| Stream delivery | Minute delivered | Client buffering | Browser-cached playback |
Three failure modes deserve design attention.
Cache-busting variants pay twice
Adding ?v=2026-11-04 to every source URL is a common deploy habit. For a transformation, the query string is part of the source identity, so the new URL is a new unique transformation and a cold cache entry. A site that does this on every deploy can pay for the same 72,000 renditions again each month. Version the source object itself, or purge deliberately.
Signing is byte-exact
If you sign one path and serve another, add a parameter after signing, reorder parameters, or use the wrong key, the edge rejects the request. An expiry shorter than the page's cache lifetime produces intermittent failures that look like a CDN problem, and an always-public variant bypasses the signature entirely. Test the exact URL the browser will use.
Format negotiation fails quietly. A Worker or proxy that strips or rewrites the Accept header can make every viewer receive JPEG, or a format the client cannot decode. If you negotiate yourself, send Vary: Accept so shared caches do not serve one client's encoding to another, and test with real browser headers rather than curl defaults.
Design a Responsive Gallery and Video Playback Page
Design a Responsive Gallery and Video Playback Page
Design-only. This is a reproducible plan, not a hosted validation. No account was provisioned and no measurements were taken for this article. Run it in your own test account and record your own observations.
| Requirement | Detail |
|---|---|
| Account and zone | A test zone you control, HTTPS enabled, dashboard access |
| Transformations | Enabled on the zone |
| Hosted Images | A paid Images plan for storage and signed URLs |
| Stream | A subscription sold as prepaid storage |
| Fixture-only route | Without the paid products, use a local static page and local images, and mark hosted steps not run |
Inputs. Six images of different aspect ratios, each at least 1600 pixels wide, plus one 30-second video, a static gallery page, and a test bucket or origin for masters. Optionally, a small Worker for signing with the key stored as a secret.
- Put the masters in R2 behind a custom domain, or use an existing origin. Keep originals out of the public gallery path if delivery should be private.
- Enable transformations on the zone and restrict source origins to your zone. Confirm that a source from an unlisted domain is rejected.
- Write the gallery markup with
srcsetcandidates at 400, 800, and 1600 pixels, a matchingsizesvalue, and explicit width and height attributes. - Request each candidate with
curl -sIand record status, content type, length, derived-image header, andcf-cache-status. Repeat one request and compare cache status. - Send AVIF, WebP, and JPEG-only
Acceptheaders to the sameformat=autoURL, and record the returned content types. - If hosted Images is available, upload one private image, create a variant, generate a signed URL with a 60-second expiry, fetch immediately, wait for expiry, and fetch again.
- If Stream is available, upload the 30-second video, wait for encoding, create a signed token with a five-minute expiry, and load the embed. Request the manifest with an expired token and record the response.
- Add
?v=test1to one transformation source URL, request it, and compare cache status and any transformation count in the dashboard. Remove it and request the original again.
Expected observations.
| Check | Expected result |
|---|---|
| 400-pixel versus 1600-pixel candidate | The smaller candidate returns fewer bytes |
| Repeated transformation | A cache hit; derivation does not re-run |
Different Accept headers | Different content types, with a fallback |
| Expired signed URL | No bytes returned |
| Versioned source URL | Behaves as a new object |
Failure checks.
- An unsigned request for a private image should fail.
- A signature with one changed character should fail.
- A variant marked always-public should still succeed without a token: intended override, design warning.
- A missing source should produce a
9404-class error. - Exceeding the free allowance should produce
9422for new variants while cached variants serve.
Approximate cost dimensions. Transformations equal source images multiplied by distinct widths; format and quality do not add unique transformations. Hosted storage is $5 per 100,000 images per month, hosted delivery $1 per 100,000 successful responses, Stream storage $5 per 1,000 minutes, and Stream delivery $1 per 1,000 minutes. These are list-price formulas as of 2026-11-04, not a quote.
Cleanup. Delete test images and video, remove R2 objects and the custom domain, disable transformations if unused, purge test URLs, revoke test keys and tokens, and delete the Worker and its secret. Confirm the old URLs no longer serve content.
Check Access, Image Dimensions, and Playback Behavior
Use pass/fail checks another operator can repeat. The verification date is 2026-11-04; the planning baseline is 2026-11-02. No hosted exercise was executed, and no browser, CLI, or product version was tested. These checks become evidence only after you run them.
Pass/fail evidence.
- Dimensions. Inspect a variant with
identifyorsips -g pixelWidth -g pixelHeight. Pass if delivered dimensions match the requested width and fit behavior, including DPR. Fail if the original dimensions or an unexpected crop is returned. - Format. Request one URL with AVIF, WebP, and JPEG
Acceptheaders. Pass if the content type matches what the client advertised and is decodable. Fail if every client receives one encoding, or an unsupported format. - Cache. Request the same variant twice and inspect
cf-cache-status. Pass if the second is a hit and derivation is not repeated. Fail if every request misses, usually from a changing query string or a bypass rule. - Access. Request a private object with no token, a valid token, an expired token, and a tampered token. Pass if only the valid token returns bytes and the others are non-200. Fail if any invalid request returns the object, or a public variant serves the private object.
- Playback. Fetch the manifest and confirm it lists multiple renditions with distinct bandwidths. Fetch the first segment and confirm a media content type. Pass if a player starts, switches, and seeks. Measure startup from manifest request to first played segment across several runs, and report the spread. Fail if the manifest is a single progressive file or segments need a token the player never receives.
- Bypass. Try the R2 public URL, origin hostname, and any
r2.devURL for a private object. Pass if all direct paths are denied or absent.
Self-check with explained answers.
- Why does adding
?v=2to an image URL increase cost? For a transformation, the query string is part of the source URL, so the edge sees a new source-and-parameter combination. That is a new unique transformation and a new cache entry; the old entry cannot be reused. - Why not serve one MP4 from R2 and call it streaming? A progressive MP4 can be cached and range-requested, but it gives the player no renditions to switch between as bandwidth changes. Stream packages the source into segmented HLS and DASH with adaptive bitrate, which is a different delivery model.
- Does
format=autobill AVIF and WebP separately? No.formatandqualityare excluded from uniqueness, so one source and geometry count once even if clients receive different encodings. Width, height, fit, and DPR still count.
Unresolved limitations. Pricing and plan entitlements were checked on 2026-11-04 and can change. Hosted storage, Stream, and Enterprise-only inputs such as AVIF were not exercised. Exact HTTP status codes for every rejected token were not verified; the checks ask for non-200. Cache behavior can differ by colo, rule, and purge history, so one curl is not a global measurement. Browser Accept headers and AVIF support vary. No playback startup or byte-size numbers are claimed as measured results.
References.
- Cloudflare Images pricing
- Images transformations overview
- Images optimization features
- Images limits and formats
- Make responsive images
- Create predefined variants
- Serve private images
- Images troubleshooting
- Cloudflare Stream pricing
- Upload videos to Stream
- Direct creator uploads
- Secure your Stream
- Use your own player
- Cloudflare R2 pricing
- R2 public buckets
Next in the Series
In Build a Mental Model for Realtime Audio and Video, we'll explore Separate interactive sessions from on-demand streaming.