From 82db0c47039173d74ea437ea1423bc43071c020c Mon Sep 17 00:00:00 2001 From: David Taylor Date: Wed, 15 Feb 2023 09:13:19 +0000 Subject: [PATCH] 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. --- app/controllers/user_avatars_controller.rb | 4 +++- spec/requests/user_avatars_controller_spec.rb | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/app/controllers/user_avatars_controller.rb b/app/controllers/user_avatars_controller.rb index db47e4b701f..1007760b13d 100644 --- a/app/controllers/user_avatars_controller.rb +++ b/app/controllers/user_avatars_controller.rb @@ -192,7 +192,9 @@ class UserAvatarsController < ApplicationController end 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 end diff --git a/spec/requests/user_avatars_controller_spec.rb b/spec/requests/user_avatars_controller_spec.rb index db4146208a9..0d5a7973e73 100644 --- a/spec/requests/user_avatars_controller_spec.rb +++ b/spec/requests/user_avatars_controller_spec.rb @@ -139,7 +139,9 @@ RSpec.describe UserAvatarsController do expect(response.status).to eq(302) 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 it "serves new version for old urls" do