Skip to content

design: cache media files in the route cache - #4735

Merged
swissky merged 5 commits into
emdash-cms:mainfrom
swissky:design/media-route-cache
Nov 17, 2026
Merged

swissky merged 5 commits into
emdash-cms:mainfrom
swissky:design/media-route-cache

Conversation

@swissky

@swissky swissky commented Nov 7, 2026

Copy link
Copy Markdown
Member

Design proposal

Proposal: proposals/media-route-cache.md

Uploaded images and their /_image variants are served with max-age=0 and no route-cache intent, so on Cloudflare every view is a BYPASS that runs the Worker, reads R2 and transforms variants again. The short lifetime exists because replacing an image keeps its storage key and nothing purges caches.

This plan stores image responses in the configured Astro route cache for one day, tagged emdash:media:<storageKey>, and purges that tag on replace and delete. Browsers keep revalidating with the existing validators. A prototype on a throwaway Worker went from BYPASS to HIT (about 50 ms), and replace and delete took effect immediately for the file and its variants. Audio and video stay uncached because memoryCache() ignores Range.

Proposal type

  • Feature plan
  • RFC
  • Amendment, supersession, or withdrawal

Related work

Discussion: #3159

Readiness

  • The proposal identifies its author and, for an RFC, its champion and Maintainer sponsor
  • The proposal describes observable behavior, compatibility, failure handling, and verification in proportion to its risk
  • Conflicting accepted or pending proposals are reconciled in this pull request
  • This pull request contains no implementation code
  • The proposal status is accepted (check only when ready to merge)

AI assistance

  • This proposal used AI assistance — model/tool: Claude Opus 5.5

@changeset-bot

changeset-bot Bot commented Nov 7, 2026 •

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: 7c1d0c5

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@swissky
swissky marked this pull request as ready for review November 7, 2026 13:10
@github-actions github-actions Bot added the review/needs-review No maintainer or bot review yet label Nov 7, 2026
@alibosworth

Copy link
Copy Markdown

@swissky thanks for this! it solves most of what i raised in #4214

I wanted to ask about this

Limiting which widths, formats or qualities /_image accepts. Issue #4214 asks for that too; it is a separate decision.

It seems to me that not limiting what variants can be generated/cached would easily lead to both unintentional and malicious cache bloat, which could result in real user-costs for the site operator. Is there a reason you are hesitant to include something about that in this design?

I wonder if it could actually just fit into a cache normalization phase, eg ?w=400&q=80 should probably not be generated/cached separately from ?q=80&w=400, and if pre-defined image dimensions were set, ?w=401 could normalize to the most appropriate preset width like ?w=400. Thoughts?

@swissky

swissky commented Nov 9, 2026

Copy link
Copy Markdown
Member Author

Thanks @alibosworth, that's a fair point and worth settling before this moves forward.

Some of this exists today, without the cache: /_image accepts any w and h from 1 to 4000, and every distinct combination is already transformed on each request. So the number of variants an attacker can request doesn't change with this proposal. What changes is what we keep afterwards.

On cost: Cloudflare Images bills per unique transformation per month, and format and quality don't count towards uniqueness. Width, height and fit are the drivers. Caching saves the repeated transformations for the same variant, but it doesn't stop someone from requesting new ones.

Where caching does add a new risk is memoryCache() on Node. It's an LRU with 1,000 entries by default, so a flood of image variants could push cached pages out. I'll add that to "Errors and edge cases".

For normalization, I'd like to add this to the plan: build the cache key only from the known parameters (href, w, h, f, q, fit) and skip caching for requests with unknown parameters, so &x=random can't create new entries. memoryCache() already sorts query parameters. I still need to check how Workers Cache handles parameter order.

Snapping to preset widths (w=401 to w=400) or rejecting other widths changes which URLs work and needs configuration, so I'd keep it as a separate feature plan together with #4214 instead of growing this one.

Does that work for you, or would you rather have the width limits in this plan as well?

@github-actions

github-actions Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Approval status

The current revision meets the approval requirements.

  • ✅ 1 human Maintainer approval from someone other than the author (normal change); found 1: @ascorbic.
  • ✅ No outstanding change requests.

This comment updates as reviews arrive. See MAINTAINING.md and the proposal process for the rules.

Comment thread proposals/media-route-cache.md Outdated

When the site configures an Astro cache provider (`cacheCloudflare()`, `memoryCache()` or another adapter's provider), EmDash stores image responses in the route cache and purges them when the image changes:

- A whole `200` image response from the media file route, and every successful variant from the image endpoints (Node and the Cloudflare Images binding), calls `context.cache.set({ maxAge: 86400, tags: ["emdash:media:<storageKey>"] })`.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why just a day? If we're invalidating it on change, we could send a year-long expiry.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @ascorbic!

Lifetime: I went with a day to be on the safe side for the first version, but you're right: the purge is what keeps it correct, so a year is the better choice. To make that safe, deletes through the plugin API and the MCP tool will purge the tag in this plan too, instead of a follow-up. The one case left is a purge that Workers Cache rejects (rate limit). I'll document that and point to manual invalidation (#4587) as the way out.

Normalization: I like this better than skipping unknown params. While checking, I noticed that Astro's getURL also emits position and background (my own site's URLs end in &fit=cover&position=center), so the plan's current allowlist would have left those variants uncached. I'll normalize to the order getURL produces (href, w, h, q, f, fit, position, background), drop unknown and repeated params with a 301, and cache only the canonical form. Astro's own URLs are already canonical, so they never hit the redirect, and the open question about Workers Cache parameter order goes away.

I'll push the update and ping you for a fresh look.

Comment thread proposals/media-route-cache.md Outdated
When the site configures an Astro cache provider (`cacheCloudflare()`, `memoryCache()` or another adapter's provider), EmDash stores image responses in the route cache and purges them when the image changes:

- A whole `200` image response from the media file route, and every successful variant from the image endpoints (Node and the Cloudflare Images binding), calls `context.cache.set({ maxAge: 86400, tags: ["emdash:media:<storageKey>"] })`.
- A variant is only stored when its query contains nothing but `href`, `w`, `h`, `f`, `q` and `fit`, each at most once. A request with any other parameter (for example `&x=1`) is still served, but not cached, so extra parameters can't create new cache entries.

@ascorbic ascorbic Nov 11, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We could normalise the params, doing a permanent redirect to remove any unknown params (and possibly sort the params if we can be sure they're always generated in the same order.) That would let us cache everything.

@emdashbot emdashbot Bot added review/needs-review No maintainer or bot review yet and removed review/needs-review No maintainer or bot review yet labels Nov 11, 2026
@github-actions github-actions Bot added review/approved Approved; no new commits since and removed review/needs-review No maintainer or bot review yet labels Nov 11, 2026
@swissky swissky mentioned this pull request Nov 13, 2026
6 of 9 tasks
@emdashbot emdashbot Bot added review/approved Approved; no new commits since and removed review/approved Approved; no new commits since labels Nov 13, 2026
@github-actions github-actions Bot added review/needs-rereview New commits since the last review and removed review/approved Approved; no new commits since labels Nov 13, 2026
@swissky
swissky requested a review from ascorbic November 13, 2026 14:54

## Open questions

- Does Workers Cache key entries by the full query string? Normalization makes the answer irrelevant for correctness, but it decides whether the redirect is also needed to avoid duplicate entries on Cloudflare.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, it includes the full URL

@emdashbot emdashbot Bot added review/needs-rereview New commits since the last review and removed review/needs-rereview New commits since the last review labels Nov 17, 2026
@github-actions github-actions Bot added the review/awaiting-author Reviewed; waiting on the author to respond label Nov 17, 2026
@github-actions github-actions Bot removed the review/needs-rereview New commits since the last review label Nov 17, 2026
@emdashbot emdashbot Bot added review/awaiting-author Reviewed; waiting on the author to respond and removed review/awaiting-author Reviewed; waiting on the author to respond labels Nov 17, 2026
@github-actions github-actions Bot added review/approved Approved; no new commits since and removed review/awaiting-author Reviewed; waiting on the author to respond labels Nov 17, 2026
@swissky
swissky merged commit 4563e83 into emdash-cms:main Nov 17, 2026
34 checks passed
@swissky swissky mentioned this pull request Nov 17, 2026
11 of 22 tasks
@bimsonz bimsonz mentioned this pull request Nov 19, 2026
5 of 9 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants