Adjust user avatar redirect cache-control header (#20291)

Previously, a user avatar redirect had a lifetime of 24h. That means that a change to the S3 CDN URL would take up to 24h to propagate to clients and intermediate CDNs.

This commit reduces the max age to 1 hour, but also introduces a `stale-while-revalidate` directive. This allows clients and CDNs to use a 'stale' value if it was received between 1h and 24h ago, as long as they make a background request to update the cache. This should reduce the impact of S3 URL changes. 1 hour after the change, the CDN will start serving updated values. Plus, if users have cached bad responses, their browser will automatically fetch the correct version and use it on the next page load.
This commit is contained in:
David Taylor 2023-02-15 09:13:19 +00:00 committed by GitHub
parent 4f509b045c
commit 82db0c4703
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 6 additions and 2 deletions

View File

@ -192,7 +192,9 @@ class UserAvatarsController < ApplicationController
end end
def redirect_s3_avatar(url) def redirect_s3_avatar(url)
immutable_for 1.day response.cache_control[:max_age] = 1.hour.to_i
response.cache_control[:public] = true
response.cache_control[:extras] = ["immutable", "stale-while-revalidate=#{1.day.to_i}"]
redirect_to url, allow_other_host: true redirect_to url, allow_other_host: true
end end

View File

@ -139,7 +139,9 @@ RSpec.describe UserAvatarsController do
expect(response.status).to eq(302) expect(response.status).to eq(302)
expect(response.location).to eq("https://s3-cdn.example.com/optimized/path") expect(response.location).to eq("https://s3-cdn.example.com/optimized/path")
expect(response.headers["Cache-Control"]).to eq("max-age=86400, public, immutable") expect(response.headers["Cache-Control"]).to eq(
"max-age=3600, public, immutable, stale-while-revalidate=86400",
)
end end
it "serves new version for old urls" do it "serves new version for old urls" do