Skip to content

Commit

Permalink
[FIX] Re-enable CDN caching (#4471)
Browse files Browse the repository at this point in the history
When looking at the server statistics, there is a disproportionate
amount of 304 responses being served by the Hedy website.

The reason is that since migrating to Flask 2.0, the defaults for
caching changed. In Flask 1.x, static file caching was enabled
by default, in Flask 2.x it no longer is.

For the CDN, we still up the caching lifetime to a day, but
the caching directive still contains `no-cache`, which leads to
a confusing HTTP response header:

```
$ curl -vv https://hedycode.com/static-c845eac78bba21798d23a3ea3134639ad0194d35/css/additional.css -o /dev/null

...
< Cache-Control: no-cache, max-age=86400
...
```

This response says: "don't cache me, but you can do that for up
to a day".

The upshot is that our CDN doesn't cache, hits the upstream server
every time, and gets served a `304 Not Modified` response.

As a fix, enable caching by default so Flask doesn't set `no-cache`,
and also make sure to remove the `no_cache` setting in the CDN
handler.
  • Loading branch information
rix0rrr authored Sep 12, 2023
1 parent 8b8be5d commit 40ea287
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 0 deletions.
8 changes: 8 additions & 0 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,11 @@
app = Flask(__name__, static_url_path='')
app.url_map.strict_slashes = False # Ignore trailing slashes in URLs
app.json = JinjaCompatibleJsonProvider(app)

# Most files should be loaded through the CDN which has its own caching period and invalidation.
# Use 5 minutes as a reasonable default for all files we load elsewise.
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = datetime.timedelta(minutes=5)

babel = Babel(app)

jinja_partials.register_extensions(app)
Expand Down Expand Up @@ -2245,6 +2250,9 @@ def try_parse_int(x):
# own file loading routines also hot-reload.
utils.set_debug_mode(not os.getenv('NO_DEBUG_MODE'))

# For local debugging, fetch all static files on every request
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = None

# If we are running in a Python debugger, don't use flasks reload mode. It creates
# subprocesses which make debugging harder.
is_in_debugger = sys.gettrace() is not None
Expand Down
1 change: 1 addition & 0 deletions website/cdn.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,5 +65,6 @@ def _send_static_file(self, filename):
"""
response = self.app.send_static_file(filename)
response.headers["Access-Control-Allow-Origin"] = "*"
response.cache_control.no_cache = None
response.cache_control.max_age = 24 * 3600 # A day
return response

0 comments on commit 40ea287

Please sign in to comment.