ActiveRecord and Cloudflare R2. Images disappearing

For Workers & Pages, what is the name of the domain?

demo.ryalto.app

What is the issue or error you’re encountering

Images uploaded through ActiveStorage and Cloudflare R2 are disappearing after 5 minutes.

What steps have you taken to resolve the issue?

We use ActiveStorage and Cloudflare R2 to upload images in our Rails application.

Recently, uploaded images have started disappearing after 5 minutes.

It seems that the problem is specific to Rails ActiveStorage and Cloudflare R2 in combination, and is due to Cloudflare caching a little too hard.
More detail can be found in this helpful article: A gotcha with Active Storage and Cloudflare

We have tried the suggested fix in that article, namely adding a page rule in Cloudflare to set the cache level for all ActiveStorage urls to bypass. This has not resolved the issue.

If anyone has experienced this same issue, some help would be appreciated!

May I ask if you see an 404 error for particular asset being uploaded to R2, while wanting to see it immediately while it’s still begin in the process of upload, meaning you’re requesting asset from R2 bucket and it’s returning a 404 which is cached, or?
If so, you could try to implement a purge cache by the URL via the API to trigger upon the asset is successfully uploaded to the R2 bucket. No need to bypass all the assets all the time.

1 Like

Ok, so it sounds like Active Storage uses Signed URLs, and requests for that resource get a 302 to the signed URL.

Except that the signed URL expires after five minutes, making the cached 302 no longer valid.

Are you saying that the 302s are staying in cache for longer than five minutes? If so, please post a screenshot with all the request and response headers of one of these 302s that send you to the expired URL.

Hi
Thanks for your response!

This is the output I get when I curl the src of a broken image. I think the issue is the cache-control: public, max-age=31536000 header but I’m not certain as some images have this header and are not broken.

There are two cache-control headers, so that’s not good.

Your next step is to figure out why there are two cache control headers, and try to eliminate that 31536000 one.

Based your screenshot, that response is definitely not cached by Cloudflare, since it’s a BYPASS. That indicates that the rule you put in place is working, and that stale Location URL is coming from somewhere else.