Caching Layers

Last updated

This page explains the cache key, lifetime, and invalidation of each of the four cache layers an image passes through.

The Four Layers

Layer Cache key Lifetime Configured in
Browser Full URL 7 days (Cache-Control: public, max-age=604800) Nginx /c/img/ block and the Cloudflare Worker; Express itself does not send this header
Cloudflare Worker Origin URL plus query string, with an X-Custom-Cache-Key header 7 days worker/index.js
Nginx Default proxy_cache key (includes query) 7 days for 200 / 301 / 302 / 304, 1 minute otherwise; evicted after 30 idle days; 2 GB cap config/nginx/nodejs.conf
Local cache file Filename built from parameters (below) No expiry, never cleaned automatically GetFromPath.ts

Local Cache File Naming

Cache files live in storage/image/cache/, mirroring upload/. The original extension is stripped and the parameters are appended:

Parameters Filename pattern
s present {name}_{s}_{q}.{t}
w and h {name}_{w}_{h}_{q}.{t}
Only w {name}_{w}_auto_{q}.{t}
Only h {name}_auto_{h}_{q}.{t}
None {name}_auto_auto_{q}.{t}

Each segment uses the raw request string, unnormalized: ?w=800 yields {name}_800_auto_.webp (quality is empty when not given), while ?w=800&q=75 produces identical output but a separate cache file. {t} is the normalized format (jpeg → jpg, invalid values → webp).

Lookup Order

graph TB
    A[Request /c/img/...] --> B{.pdf / .svg?}
    B -->|Yes| C[Stream original, no cache]
    B -->|No| D{o = 1?}
    D -->|Yes| E[Stream original, no cache]
    D -->|No| F{Cache file exists?}
    F -->|Yes| G[Return cache file]
    F -->|No| H[sharp convert → respond → write cache file]

Invalidation and Purging

Situation Result
DELETE /del/... removes the original The original moves to trash; cache files in cache/ and the Nginx and Cloudflare caches are not purged
An original is overwritten under the same name Cannot happen: upload filenames are a random string plus timestamp
Purge the local cache Delete the matching directory under storage/image/cache/
Purge the Nginx cache Delete /var/cache/nginx/images in the container and reload Nginx
Purge the Cloudflare cache Purge from the Cloudflare Dashboard
中文