Ref: https://learn.cantrill.io/courses/1820301/lectures/41301523
CF Caching - Example Scenario
- New image uploaded at origin
- User A requests image. Since no image at caching location, origin fetch performed. Image stored in Local Cache with a Time-To-Live (TTL) and returned to User A.
- Image is updated at origin, but image at local cache hasn't expired yet (still valid)
- User B requests image. Local cache returns its image (which is outdated)
- ‼️ THIS scenario is the disadvantage of caching! → Sometimes objects stored in cache are outdated.
- This scenario should be avoided when reasonable
- There are ways to mitigate this issue in CF
- Image at local cache expires. It is however not ejected yet, only considered stale.
- User C requests image. Local cache has an expired image, so it forwards request to origin.
- If image at origin has been updated (like in this case), origin answers
200 OK
and returns updated image. Local Cache replaces old image with updated, then returns updated image to User C.
- If the image at origin had NOT been updated, origin would simply respond with
304 Not Modified
and Local Cache would mark the image as valid again and renew its TTL.
- Similar scenario to above with a cat picture at S3 origin and Local Cache being an Edge Location
- 💡 Ideally an object stays cached for as long as its valid in the origin
- Sometimes an object can be ejected prematurely if cache has capacity problems (not a huge issue, an extra origin fetch will be performed)
CF Time-To-Live (TTL) or Validity Period
- 🔧 Trade-off between origin load and having current objects
- More frequent cache hits means:
- lower origin load → better performance
- higher risk of outdated objects
- Default TTL of a behavior
- All objects cached in this behavior will, unless specified otherwise, have TTL=Default TTL
- ‼️ Default value for “Default TTL” = 24h
- Minimum TTL and Maximum TTL of a behavior
- Lower and upper boundaries for custom TTLs of individual objects
- To define a per-object TTL (custom TTL), include headers:
- Origin header:
Cache-Control max-age
(seconds)
- Origin header:
Cache-Control s-maxage
(seconds)
- Origin header:
Expires
(Date & Time)
- TTL calculated from given date & time of expiry
- ❗ If an object is sent without a defined TTL, it gets the behavior's default TTL
- ❗ If the defined TTL is below Minimum TTL or above Maximum TTL, the boundary value (minimum or maximum) is used instead
- How to define headers:
- Custom origin → inject headers via app or via web server
- S3 origin → define per-object header via object metadata