# How the API Cache Works (ELI5)

> Copy of the shared document (kept in the repo so it travels with the code). The drawings are Mermaid diagrams, which GitHub and GitLab render. Written 15 to 16 October 2026; the numbers were measured on the dev site.

2026-10-15 · Mohammad Qasem

The API remembers every page it has read from WordPress, so visitors get answers in about 2 milliseconds and edits show up within seconds, without anyone waiting.

## The big idea

The API keeps a copy of every answer on a shelf, so visitors get it in about 2 milliseconds instead of waiting half a second for WordPress.

Think of a shop:

| In the shop | In our system | Job |
| --- | --- | --- |
| The warehouse | WordPress | Holds the real, up-to-date content. Slow to ask. |
| The shelf by the door | Redis cache | Holds ready copies. Instant to grab. |
| The shopkeeper | The API | Looks on the shelf first, goes to the warehouse only when the shelf is empty. |

Keeping the shelf both full and fresh is the hard part. The cases below show how it is done.

## Words used in this document

| Word | Meaning |
| --- | --- |
| Shelf | The picture used here for Redis and the copies it holds. |
| Copy | A saved answer for one page, kept in Redis. |
| Hit, miss | A hit is answered from a copy. A miss has no usable copy, so the API must ask WordPress. |
| Fresh, stale | A copy is fresh until its lifetime ends and stale after. A stale copy is still kept, and is served only while WordPress is down. |
| Module | A group of endpoints that is cached and refreshed together, such as `offices` or `blogs`. There are 16. |
| Refresh | Re-fetching a page from WordPress and replacing its copy. |
| Purge note | The message WordPress sends to the API after an edit, asking it to refresh a module. |
| Remembered URL | A page address the API has served before. Refreshes and the timer re-fetch exactly these. |
| Seed | Loading the whole site into the cache at startup. |
| Seed-finished note | A small marker in Redis saying a seed completed, so a restart can skip it. |

## The parts

```mermaid
flowchart LR
    W["Website or app"] -->|"asks for a page"| A["Reach API"]
    A <-->|"read or save a copy"| R[("Redis: the shelf")]
    A -->|"only on a miss: GraphQL"| P["WordPress"]
    P -->|"on every save: purge note"| A
```

*The parts*

The website only ever talks to the API. The API goes to WordPress on a miss, and WordPress sends a purge note whenever someone saves. Seven cases follow, each with a drawing and the settings that control it.

| Part | Real name |
| --- | --- |
| API | Reach Immigration API (NestJS), port 105 on the dev server |
| Shelf | Redis, keys named `facade:cache:*` |
| Source of content | WordPress through WPGraphQL, port 99 |
| Edit notice | `ri-cache-purge-webhook.php` calling `POST /v1/internal/cache/purge?target=` |
| Stocking at start | `CacheSeedService` |
| Timer and startup logic | `CacheRefreshService` |
| Re-fetching after an edit | `CacheWarmService.purgeAndRefresh` |

## The cases at a glance

| Case | What starts it | What happens | Main settings |
| --- | --- | --- | --- |
| 1. A visitor asks for a page | Any GET request | Answered from the shelf, or fetched once from WordPress and saved | `CACHE_TTL_FALLBACK`, `CACHE_TTL_FULL_LIST` |
| 2. The app starts | A start or a restart | An empty cache is seeded; a finished seed in Redis means no work | `CACHE_WARM_ON_BOOT`, `CACHE_SEED_*` |
| 3. Someone edits content in WordPress | A save, trash, delete, term or options-page change | The affected modules are re-fetched and replaced in place within seconds | `CACHE_WARM_ENABLED`, `RI_API_BASE_URL`, `RI_API_PURGE_KEY` |
| 4. The timer | Every 4 h 48 m by default | Every copy is renewed before it goes stale | `CACHE_REFRESH_ENABLED`, `CACHE_REFRESH_INTERVAL_SECONDS` |
| 5. Something goes wrong | A failed re-fetch, an unreachable API, an empty Redis, two servers | Old copies are kept and the next round tries again | see the case |
| 6. The manual purge link | An admin clicks it and confirms | All 16 modules are refreshed in place | `RI_API_BASE_URL`, `RI_API_PURGE_KEY` |
| 7. WordPress is down | A timeout, a refused connection or a 5xx | Visitors get the last good copy with `X-Cache: STALE` | `CACHE_STALE_MAX_SECONDS`, `WPGRAPHQL_TIMEOUT_MS` |

## What is cached

Every public GET endpoint belongs to one module, and each module is a purge target. Language is part of most copy names.

| Module | Endpoints | Copy names | Refreshed when this changes in WordPress |
| --- | --- | --- | --- |
| `aboutus` | `/v1/aboutus` | `aboutus:<language>` | About Us options page |
| `blogs` | `/v1/media-center/blogs`, `/filter`, `/{slug}` | `blogs:list`, `:all`, `:filter`, `:detail` | Blog posts and their categories |
| `branch-map` | `/v1/branch-map/nearest` | `branch-map:nearest:<country code>` | Offices, Branch Map options page |
| `case-evaluation` | `/v1/case-evaluation` | `case-evaluation:<language>` | Case evaluation options page, programs |
| `country-programs` | `/v1/programs/countries`, `/filter` | `country-programs:...` | Country programs |
| `events` | `/v1/media-center/events`, `/{slug}` | `events:list`, `:detail` | Events |
| `homepage` | `/v1/homepage` | `homepage:<language>` | Home options page, programs, blogs, events, reviews, country programs |
| `languages` | `/v1/languages` | `languages:all` | WPML settings |
| `newsletters` | `/v1/media-center/newsletters`, `/{slug}` | `newsletters:list`, `:detail` | Newsletters |
| `offices` | `/v1/offices` | `offices:<language>` | Offices |
| `our-credentials` | `/v1/our-credentials` | `our-credentials:<language>` | Credentials options page |
| `passport-index` | `/v1/passport-index`, `/filter`, `/methodology`, `/{slug}` | `passport-index:list`, `:all`, `:filter`, `:detail`, `:methodology` | Passports |
| `programs` | `/v1/programs`, `/content`, `/{slug}` | `programs:list`, `:all`, `:content`, `:detail` | Programs, country programs |
| `social-media` | `/v1/social-media` | `social-media:<language>` | Social media options page |
| `success-stories` | `/v1/success-stories` | `success-stories:<language>` | Success stories, reviews |
| `sitemap` | none (it writes the sitemap files) | `sitemap` | Most content types |

Not cached: Google reviews, which are fetched fresh each time, and the consultation booking and newsletter subscribe endpoints, which only send data.

## Case 1: a visitor asks for a page

```mermaid
flowchart LR
    V["Visitor: GET /v1/offices"] --> A["API looks in Redis"]
    A --> D{"A copy on the shelf?"}
    D -->|"yes"| Y["Answer the visitor<br/>about 2 ms"]
    D -->|"no (miss)"| W["Ask WordPress<br/>0.5 to 3 s, once"]
    W --> S["Save the copy<br/>with a lifetime (TTL)"]
    S --> Y
```

*Case 1: hit and miss*

A copy on the shelf is a hit: it answers in about 2 ms and never touches WordPress. A missing copy is a miss: it costs one WordPress call (0.5 to 3 s on the dev site), and the result is saved for the next visitor. Two settings decide how long a saved copy stays fresh:

| Setting | Default | Exact effect in this case |
| --- | --- | --- |
| `CACHE_TTL_FALLBACK` | 21600 s (6 h) | How long a saved normal page, list page or detail page stays fresh. After that the next visit asks WordPress for a new copy, and the old one stays as a backup (case 7). |
| `CACHE_TTL_FULL_LIST` | 86400 s (24 h) | How long a full unfiltered list stays fresh. The filter endpoints are built from these lists, and they are slow to rebuild (the passport list has 200 items). |

Examples of each kind:

- **Normal pages (****CACHE_TTL_FALLBACK****)** are what a visitor asks for directly: the offices list (`GET /v1/offices`, page 1 with 10 items), the same list at 50 per page, or one office or passport on its own.
- **Full lists (****CACHE_TTL_FULL_LIST****)** are never shown as they are. Each holds every item of a type, unfiltered, such as all 200 passports. When a visitor filters the passports, the API cuts the answer from this list instead of asking WordPress again.

The timer (case 4) renews copies before they go stale, so in normal running visitors almost never see a miss.

A copy's name holds everything that changes the answer: the module, the language, the status, the page number, the page size and any filters. For example `blogs:list:en:publish:1:10` and `blogs:list:en:publish:1:50` are two separate copies. Visitors who ask for the same missing copy at the same moment share one WordPress call instead of making one each.

## Case 2: the app starts

```mermaid
flowchart TD
    S["App starts, listening after about 1 s"] --> E{"Seeding turned on?<br/>CACHE_WARM_ENABLED + CACHE_WARM_ON_BOOT"}
    E -->|"no"| N0["Do nothing: pages are saved as visitors ask"]
    E -->|"yes"| F{"A finished seed is already in Redis?<br/>same settings, CACHE_SEED_FORCE false"}
    F -->|"yes"| N1["Skip: no WordPress calls at all"]
    F -->|"no"| L{"No other server is seeding?<br/>Redis lock, up to 1 hour"}
    L -->|"no"| N2["Leave it to that server"]
    L -->|"yes"| P1["Phase 1: the common pages<br/>default-size lists, all details, each language"]
    P1 --> P2["Phase 2: the long tail<br/>filters, extra page sizes, 249 country lookups"]
    P2 --> N["Save the finished-seed note<br/>kept for CACHE_TTL_FALLBACK, if nothing failed"]
```

*Case 2: what the app does at startup*

A restart with Redis intact needs no seeding. When a seed finishes cleanly, the app stores a "seed finished" note in Redis that records the page sizes it used, and the next start finds the note and skips the seed. The app seeds again when Redis is empty, when the seed settings changed, when the last seed had failures, or when `CACHE_SEED_FORCE=true` is set. The common pages are seeded first.

| Setting | Default | Exact effect in this case |
| --- | --- | --- |
| `CACHE_WARM_ENABLED` | true | Master switch. False turns off all seeding, re-caching after an edit and the timer. |
| `CACHE_WARM_ON_BOOT` | true | False skips the startup seed only; the timer and edit refresh still run. |
| `CACHE_SEED_FORCE` | false | True seeds on every start even when Redis holds a finished seed. |
| `CACHE_SEED_PAGE_SIZES` | 50 (`PAGINATION_MAX_LIMIT`) | Page sizes seeded besides each endpoint's default (`PAGINATION_DEFAULT_LIMIT`, 10). `12,50` seeds both. Changing it makes the old note stale, so the next start seeds again. |
| `CACHE_SEED_CONCURRENCY` | 4 | Parallel requests the seed makes against the API. |
| `CACHE_SEED_DELAY_MS` | 100 ms (0.1 s) | Pause after each request, so WordPress is not overloaded. |
| `CACHE_WARM_BASE_URL` | `http://127.0.0.1:PORT` | Where the seed sends its requests: the app calls its own address. |

The note lives for `CACHE_TTL_FALLBACK` and every timer refresh renews it (case 4). If two servers start together, a one-hour Redis lock lets only one of them seed. The other serves visitors on demand.

What the seed loads, in every active language:

- Every page of every list (blogs, events, newsletters, programs, passport index), at the default page size and at each size in `CACHE_SEED_PAGE_SIZES`.
- Every detail page: each blog, event, newsletter, program and passport.
- Every filter combination: passport index by sort order, continent and visa-free band; blogs by category; programs and country programs by type.
- The single pages: home, about, credentials, social media, offices, case evaluation, success stories, the programs content, country programs and the passport index methodology.
- The nearest branch for all 249 country codes, once rather than per language.

A page size that is not in the list, or a filter nobody has asked for yet, is cached on its first request and remembered from then on, so the timer renews it too.

While the seed runs, the app already answers requests, and a page that is not loaded yet is simply a miss (case 1). On the dev site the common pages take about 6 minutes and everything about 8.7 minutes, limited by WordPress. Skipping the seed on a restart only works if Redis keeps its data across restarts, so run Redis with saving turned on.

## Case 3: someone edits content in WordPress

```mermaid
sequenceDiagram
    participant WP as WordPress and its plugin
    participant API as API
    participant R as Redis
    participant V as Visitors
    WP->>API: 1. purge note with the edited slug, after the save
    API->>R: 2. note each copy's life
    API-->>WP: 3. reply 201 in about 26 ms
    API->>WP: 4. re-fetch, the edited item first
    V->>R: read the old copy, no wait
    WP-->>API: fresh content
    API->>R: 5. replace the copy, new TTL
    API->>R: 6. delete copies not rewritten (clean pass) or mark them stale (a re-fetch failed)
    V->>R: then the new copy
```

*Case 3: an edit in WordPress*

Visitors never wait: they keep getting the old copy until the new one is ready. In a test on the dev site, an edited passport showed its new value about 7 seconds after the purge, and the whole refresh pass took 17 seconds.

In order, as numbered in the drawing:

1. WordPress finishes the save and answers the editor. Only then does the plugin send a purge note to the API, one per affected module.
2. The API notes how long each existing copy of that module has left.
3. The API replies at once (about 26 ms), so the webhook is never held open.
4. In the background it re-fetches a bounded set of the module's remembered URLs (100 by default), two at a time with a short pause. The pages of the edited items come first (the plugin sends their slugs), then the shortest of the rest.
5. Each fresh answer replaces its copy and restarts the copy's lifetime.
6. Copies that were not re-fetched, or whose re-fetch failed, are marked stale: the next visitor fetches fresh data, or gets the old copy as a backup if WordPress is down. Only after a pass that re-fetched every remembered URL cleanly are copies that were not replaced deleted, because their content no longer exists.

Visitors read the old copy through steps 1 to 5 and the new one after.

An edit never floods WordPress. At most `CACHE_PURGE_REFRESH_LIMIT` URLs (100) are re-fetched, the edited items first. Every other copy of the module is marked stale, so it refreshes on its next visit instead of all at once.

A newer purge note for the same module replaces a refresh that is still running: the old pass stops picking up new URLs and the new one starts at once. An edit therefore never waits behind a slow older pass, and Gutenberg's second save request, the one that writes the custom fields, gets a pass that sees the final data.

Visitors do not wait for WordPress after an edit. A copy that just went stale is served at once, with the header `X-Cache: REVALIDATING`, while the API refreshes it in the background (the same URL at most once every 30 seconds, three refreshes at a time). The next visitor gets the fresh copy. This holds for `CACHE_SWR_SECONDS` (300 s) after the copy went stale. The one exception is the edited item's own page: it is made stale and marked "hard", so it is always fetched fresh and a visitor never sees the old value for it.

The website has its own page cache on top of this one. The Next.js site keeps every page for 60 seconds, then shows the old page once more while it rebuilds, so an edit could take a minute or more to appear there even though the API already had it. To close that gap the API tells the website to drop its pages: it calls the website's `POST /api/revalidate` with the module name and the shared secret, once right after the edited item is marked (the website then rebuilds with the new item) and once when the refresh pass ends (to correct the lists). It is off unless `FRONTEND_REVALIDATE_URL` and `FRONTEND_REVALIDATE_SECRET` are both set; it times out after 5 s, retries once, and never blocks an edit. The sitemap and languages have no website page and are skipped. The API log shows `Website refresh is ON` at startup and `Told the website to refresh "<module>"` after each edit.

How the website side works: the website already has an endpoint, `POST /api/revalidate`. It checks the `x-revalidate-secret` header against its `REACH_REVALIDATE_SECRET`, maps the module to cache tags (`passport-index` becomes `passports` and `methodology`), and drops the pages saved under those tags. The next visit rebuilds them from the API, which already has the new data. The API only needs the website's address and the same secret. A wrong secret gets a 401 and the API logs a warning. If the website is down, the call is retried once and then skipped, and the website falls back to its own 60 second timer.

To turn it off, leave `FRONTEND_REVALIDATE_URL` or `FRONTEND_REVALIDATE_SECRET` empty and restart the API; the log then shows `Website refresh is OFF`. To remove the 60 second wait in the website itself, change `revalidate: 60` in the website code (`src/lib/http.ts` and `src/lib/api.ts`) to `0` or use `cache: 'no-store'`. Edits then show as soon as the API has them, but the website renders every visit, pages load a little slower, the API gets a request per visit, and visitors feel any API slowness at once. Keeping the 60 second timer with the notification on is the recommended setup.

How the website gets its data from the API: the Next.js website calls the API from its own server, never from the visitor's browser. Its `.env` holds `REACH_API_URL` (the API address) and `REACH_API_KEY` (one of the API's `API_KEYS`); neither is sent to the browser. For each page its `apiGet()` helper does `GET <REACH_API_URL>/<path>` with the header `x-api-key`, with an 8 second timeout. It never throws: if the API fails, the page falls back to stand-in data. Next.js saves each answer for `revalidate: 60` seconds and tags it (for example `passports`), which is the 60 second wait described above.

| Direction | Call | Purpose |
| --- | --- | --- |
| Website to API | `GET` with `x-api-key` | Get the data for a page. The everyday path. |
| API to website | `POST /api/revalidate` with `x-revalidate-secret` | Say "this module changed" so the website drops its saved pages. |

The two secrets are different: `x-api-key` lets the website into the API, and `x-revalidate-secret` lets the API into the website.

What triggers a purge: publish, update of a published post, unpublish, trash, permanent delete, a term change, an ACF options-page save, a WPML settings save, and a change to a published post's custom fields made by code, such as the Passport Manager's "Sync Visa Information", the Henley sync and the Excel or CSV imports. Saving a draft does not. A bulk sync is purged once per module, with up to 20 of the changed slugs refreshed first. Each content type refreshes its own module and the modules that embed it, as the table below shows.

Which edit refreshes which modules:

| Content saved in WordPress | Modules refreshed |
| --- | --- |
| Passport | `passport-index`, `sitemap` |
| Newsletter | `newsletters`, `sitemap` |
| Success story | `success-stories` |
| Office | `offices`, `branch-map`, `sitemap` |
| Program | `programs`, `homepage`, `case-evaluation`, `sitemap` |
| Blog post | `blogs`, `homepage`, `sitemap` |
| Event | `events`, `homepage`, `sitemap` |
| Review | `success-stories`, `homepage` |
| Country program | `country-programs`, `programs`, `homepage`, `sitemap` |
| A category or other term | The modules of the content types that use it |
| An options page (home, about, credentials, social media, case evaluation, branch map) | All 16 modules |
| WPML settings | `languages` |

A module also refreshes when content it embeds changes. That is why editing a program also refreshes the home page and case evaluation.

The sitemap files are rebuilt about 15 seconds after a burst of edits settles, because the sitemap listens for purges.

| Setting | Default | Exact effect in this case |
| --- | --- | --- |
| `CACHE_WARM_ENABLED` | true | True: re-fetch the target's known URLs and replace copies in place. False: delete the target's copies outright. |
| `RI_API_BASE_URL` (wp-config.php) | none | Where the plugin sends the purge note. |
| `RI_API_PURGE_KEY` (wp-config.php) | none | The `x-api-key` the plugin sends. It must be one of the API's `API_KEYS`. |
| `FRONTEND_REVALIDATE_URL`, `FRONTEND_REVALIDATE_SECRET` | none (off) | 3 | The website's `/api/revalidate` address and the secret it expects (its `REACH_REVALIDATE_SECRET`). When both are set, the API tells the website to refresh its pages after each edit. |
| `API_KEYS` | none | The first key is also what the API uses for its own re-fetch requests. |

If the API is unreachable, the plugin retries once straight away, then from WP-Cron up to 6 times with a growing pause, and finally logs a line asking for a manual purge.

## Case 4: the timer refreshes everything

```mermaid
flowchart LR
    T["Timer fires<br/>every 4 h 48 m after the last"] --> L{"Lock free?<br/>one server at a time"}
    L -->|"no"| K["Skip this round<br/>another server is on it"]
    L -->|"yes"| F["Re-fetch every URL<br/>all modules, fresh from WordPress"]
    F --> RP["Replace the copies<br/>full lifetime again"]
    RP --> N["Renew the seed note<br/>keeps restarts cheap"]
    N --> W["Wait until the next round"]
    W --> T
```

*Case 4: the timer*

The timer is the safety net for changes that no edit notice announces. It re-fetches the remembered URLs of every module (at most 500 per module, shortest first), two at a time with a short pause, and replaces the copies in place, so a copy is renewed before it goes stale. A long tail of filter and paging URLs is left to refresh on a visit. Within one pass a rewritten copy is reused, so the full passport list is fetched once, not once per filter page.

| Setting | Default | Exact effect in this case |
| --- | --- | --- |
| `CACHE_REFRESH_ENABLED` | true | False stops the timer. The startup seed and the edit refresh still work. |
| `CACHE_REFRESH_INTERVAL_SECONDS` | 80% of the shortest TTL, so 17,280 s (4 h 48 m) | How often the pass runs. Never below 60 s. With the 6 h default lifetime it renews copies 1 h 12 m before they would expire. |
| `CACHE_TTL_FALLBACK` / `CACHE_TTL_FULL_LIST` | 21,600 s / 86,400 s | The interval default is computed from the shorter of these two. Raise one and the default follows; set the interval yourself and it does not. |
| `CACHE_WARM_ENABLED` | true | False also turns off the timer. |

The lock `refresh` is held for half the interval (at least 60 s), so a second server whose timer fires at the same moment skips the round.

Also worth knowing:

- The time of the last round is kept in Redis. A restart continues the schedule, and a round that is already overdue runs 3 seconds after boot. A round with failures is not recorded, so a restart soon after retries it.
- The API refreshes by calling itself with a secret header, new at every start, that makes it skip the cache and read from WordPress. Outside callers cannot use it.

Refreshes are paced so they cannot saturate WordPress:

| Setting | Default | What it does |
| --- | --- | --- |
| `CACHE_REFRESH_CONCURRENCY` | 2 | Parallel re-fetches during an edit refresh or a timer round |
| `CACHE_REFRESH_DELAY_MS` | 200 ms (0.2 s) | Pause after each re-fetch |
| `CACHE_PURGE_REFRESH_LIMIT` | 100 | Most URLs re-fetched after one edit (case 3) |
| `CACHE_REFRESH_MAX_URLS` | 500 | Most URLs per module re-fetched by one timer round |

## Case 5: something goes wrong

```mermaid
flowchart TD
    F["Re-fetch one URL<br/>repeated for every URL"] --> O["Answer 200: the copy is replaced"]
    F --> G["Answer 404: content is gone, not a failure"]
    F --> X["Error or 15 s timeout: counts as a failure"]
    O --> Q{"Pass over: any failure?"}
    G --> Q
    X --> Q
    Q -->|"no"| D["Delete copies that were not rewritten<br/>their content no longer exists"]
    Q -->|"yes"| K["Mark the old copies stale<br/>the next visit fetches fresh data"]
```

*Case 5: how a refresh pass ends*

What happens in each situation, and which setting changes it:

| Situation | What happens | Controlled by |
| --- | --- | --- |
| A re-fetch fails during an edit refresh (WordPress is down, or this API cannot reach itself) | Nothing is deleted. The old copies are marked stale and a warning is logged, so the next visit fetches fresh data, or serves the old copy as a backup if WordPress is down. The edit still shows up. | Fixed rule. If WordPress is up, check that CACHE_WARM_BASE_URL is the address the app listens on. |
| WordPress is down during the timer refresh | Each failed URL keeps its old copy (served as a backup, case 7), and the next round tries it again. | `CACHE_REFRESH_INTERVAL_SECONDS` sets the retry spacing, and `CACHE_STALE_MAX_SECONDS` how long old copies are kept. |
| A visitor asks for a page that was never cached while WordPress is down | That page returns an error. Cached pages are unaffected. | The seed and the timer keep the shelf full, so this is rare. |
| WordPress fails while the app restarts | The app still starts, and cached pages are served as backups (case 7). | `WPGRAPHQL_TIMEOUT_MS` sets what counts as a failure. |
| Content is deleted in WordPress | Its URL answers 404 on re-fetch, and after a clean pass its old copy is deleted. | Fixed rule. |
| The plugin cannot reach the API | One immediate retry, then WP-Cron retries with a growing pause (60 s times the attempt number) up to 6 times, then a log line asks for a manual purge. | `RI_API_BASE_URL`, `RI_API_PURGE_KEY`. |
| Redis is empty | Visitors fill missing pages on demand while the startup seed loads the rest (case 2). | `CACHE_WARM_ON_BOOT`, `CACHE_SEED_*`. |
| Two API servers share one Redis | One lock lets a single server seed, and another lock a single server refresh. A purge from WordPress reaches the server that `RI_API_BASE_URL` points to, and all servers read the same Redis. | Fixed locks. |
| Seed settings change between starts | The old finished-seed note no longer matches, so the next start seeds again. | `CACHE_SEED_PAGE_SIZES`. |

Not handled by this design: if Redis itself is unreachable, requests that need the cache wait or fail until it is back. Run Redis with saving turned on and a restart policy.

## Case 6: the manual purge link

```mermaid
flowchart LR
    A["Admin clicks<br/>Purge API Cache<br/>in the toolbar"] --> C{"Confirm dialog<br/>warns it takes a few minutes"}
    C -->|"cancel"| X["Nothing happens"]
    C -->|"ok"| P["Plugin sends 16 purges,<br/>one per module"]
    P --> R["API refreshes each module in place"]
    R --> M["Alert shown:<br/>purge started (N cached items)"]
```

*Case 6: the manual purge link*

This is the escape hatch for what no automatic hook can see: activating or deactivating a WPML language, edits made directly in the database, or a purge that kept failing. There is no per-post button, because saving already purges by itself.

The confirmation says: "All content will be reloaded from WordPress in the background. Visitors keep seeing the current version until the new one is ready, and it can take a few minutes before every page shows the latest data." Behind it, each module is refreshed in place exactly as in case 3.

## Case 7: WordPress is down

```mermaid
flowchart TD
    V["Visitor asks for a page"] --> C{"A copy is in Redis?<br/>kept up to 7 days after it was saved"}
    C -->|"no"| E["Never cached: error for this page,<br/>nothing to serve"]
    C -->|"yes"| F{"The copy is still fresh?<br/>within CACHE_TTL_FALLBACK or _FULL_LIST"}
    F -->|"yes"| S["Serve it<br/>about 2 ms, no WordPress call"]
    F -->|"no, stale"| U{"WordPress answers?<br/>down = timeout, refused or a 5xx"}
    U -->|"yes"| N["Fetch a new copy<br/>save it and serve it, as usual"]
    U -->|"no, down"| O["Serve the old copy<br/>header X-Cache: STALE"]
    O --> P["Keep checking WordPress<br/>a probe every 15 s until it answers"]
```

*Case 7: WordPress is down*

While WordPress is down, visitors keep getting the last good copy of each page, with the header `X-Cache: STALE`, for up to 7 days after it was saved. Nothing has to be done during the outage, and the copies are replaced by themselves once WordPress answers again.

### How a copy ages

Each copy has two times: when it stops being fresh, and when Redis finally removes it. The table uses the defaults: fresh for 6 hours (24 hours for full lists), kept for 7 days.

| Time since the copy was saved | State | WordPress is up | WordPress is down |
| --- | --- | --- | --- |
| Up to 6 h | Fresh | Answered from the copy | Answered from the copy |
| 6 h to 7 days | Stale | Just stale (up to 5 minutes): served at once and refreshed in the background. Stale for longer: the next visit fetches a new copy. The timer replaces it too. | Answered from the stale copy, with `X-Cache: STALE` |
| After 7 days | Removed by Redis | A normal miss | An error for that page |

In normal running the timer (case 4) replaces every copy long before it is 7 days old, so the 7 days only matter if refreshes keep failing.

### How the API knows WordPress is down

| What happens on a WordPress call | Counts as down? |
| --- | --- |
| No answer within `WPGRAPHQL_TIMEOUT_MS` (20 s) | Yes |
| The connection is refused or dropped | Yes |
| A 5xx answer | Yes |
| A 4xx answer | No |
| "Not found" or an empty result | No. The content was deleted, so its copy is removed. |

The first call that fails marks WordPress as down for the whole app. That request is run once more, so even the first visitor gets the old copy (23 ms in my test). While the mark is set, stale copies are served without calling WordPress at all. A probe every 15 s checks whether WordPress answers, and the first success clears the mark so normal fetching resumes.

### Special situations

| Situation | What happens |
| --- | --- |
| A page that was never cached | It returns an error, because there is nothing to serve. |
| A stale page whose content was deleted in WordPress | It answers 404 and its copy is removed. |
| The timer or an edit refresh runs during the outage | It is never answered from an old copy. A failed re-fetch counts as a failure and the old copy is marked stale instead of being replaced (case 5). |
| The app restarts during the outage | It starts normally and serves the stale copies. |
| A copy in the old format, without a fresh-until time | It keeps being served as fresh until Redis expires it at its old lifetime, so a deploy does not empty the cache. A refresh rewrites it in the new format. |

### Noticing an outage

- Every response built from an expired copy carries `X-Cache: STALE`, so the website can show a notice and monitoring can count them.
- The log has a warning when WordPress is first marked down, an error line every 10 minutes while it stays down, and a line when it is back.
- No alert is sent automatically. Connect your monitoring to the header or to those log lines.

### Settings for this case

| Setting | Default | Exact effect in this case |
| --- | --- | --- |
| `CACHE_STALE_MAX_SECONDS` | 604800 s (7 days) | How long Redis keeps a copy, counted from the moment it was saved. This is the longest an outage can be covered; after it, that page returns an error. |
| `CACHE_SWR_SECONDS` | 300 s (5 min) | 3, 7 | A copy that just went stale is served at once for this long while it is refreshed in the background, so no visitor waits on WordPress. After that it is fetched fresh. 0 turns it off. |
| `WPGRAPHQL_TIMEOUT_MS` | 20000 ms (20 s) | A WordPress answer slower than this counts as down. |
| `CACHE_TTL_FALLBACK` / `CACHE_TTL_FULL_LIST` | 21600 s (6 h) / 86400 s (24 h) | When a copy stops being fresh. They no longer decide when it disappears. |

Good to know: `CACHE_REFRESH_INTERVAL_SECONDS` still follows the shorter TTL, and `CACHE_STALE_MAX_SECONDS` does not change it. Redis memory grows with how long copies stay, not with how many pages are remembered.

## Every setting

All of these go in the API's `.env` file; the default is what runs if you set nothing. "Cases" are the numbered cases above.

| Setting | Default | Cases | Exact effect |
| --- | --- | --- | --- |
| `CACHE_TTL_FALLBACK` | 21600 (6 h) | 1, 2, 4, 7 | How long a normal copy stays fresh. Also the lifetime of the finished-seed note. |
| `CACHE_TTL_FULL_LIST` | 86400 (24 h) | 1, 4, 7 | How long the full unfiltered lists (that the filter endpoints are built from) stay fresh. |
| `CACHE_STALE_MAX_SECONDS` | 604800 s (7 days) | 7 | How long Redis keeps a copy, counted from the moment it was saved. While WordPress is down the API serves a stale one, with `X-Cache: STALE`. |
| `WPGRAPHQL_TIMEOUT_MS` | 20000 ms (20 s) | 7 | A WordPress answer slower than this counts as down. |
| `CACHE_WARM_ENABLED` | true | 2, 3, 4 | Master switch. False: no seeding, no timer, and an edit deletes copies instead of refreshing them. |
| `CACHE_WARM_BASE_URL` | `http://127.0.0.1:PORT` | 2, 3, 4 | Address the API uses to call itself for seeding and refreshing. |
| `CACHE_WARM_ON_BOOT` | true | 2 | False skips only the startup seed. |
| `CACHE_REFRESH_ENABLED` | true | 4 | False stops the timer. |
| `CACHE_REFRESH_INTERVAL_SECONDS` | 80% of the shortest TTL (17,280 s = 4 h 48 min) | 4 | Time between timer rounds, never below 60 s. The refresh lock lasts half of it. |
| `CACHE_REFRESH_CONCURRENCY` | 2 | 3, 4 | Parallel re-fetches during an edit refresh or a timer round. |
| `CACHE_REFRESH_DELAY_MS` | 200 ms (0.2 s) | 3, 4 | Pause after each re-fetch, so WordPress is not saturated. |
| `CACHE_PURGE_REFRESH_LIMIT` | 100 | 3 | Most URLs re-fetched after one edit; the module's other copies are marked stale. |
| `CACHE_REFRESH_MAX_URLS` | 500 | 4 | Most URLs per module re-fetched by one timer round, shortest first. |
| `CACHE_SEED_PAGE_SIZES` | 50 (`PAGINATION_MAX_LIMIT`) | 2 | Extra page sizes seeded besides each endpoint's default. A change forces a new seed. |
| `CACHE_SEED_CONCURRENCY` | 4 | 2 | Parallel requests during the seed. |
| `CACHE_SEED_DELAY_MS` | 100 ms (0.1 s) | 2 | Pause after each seed request. |
| `CACHE_SEED_FORCE` | false | 2 | True seeds on every start, ignoring the finished-seed note. |
| `PAGINATION_DEFAULT_LIMIT` / `PAGINATION_MAX_LIMIT` | 10 / 50 | 1, 2 | The default page size, and the largest one a visitor can ask for. Each module can override them (for example `BLOGS_DEFAULT_LIMIT`). |
| `API_KEYS` | none | 2, 3, 4 | The first key is what the API sends to itself when seeding and refreshing. |
| `RI_API_BASE_URL`, `RI_API_PURGE_KEY` | none | 3, 6 | Set in WordPress `wp-config.php`: where the plugin sends purges, and the key it sends. |

Some numbers are fixed in code, not settings: a 15 s timeout per re-fetch, 5,000 URLs remembered per module for 7 days, a 1-hour seed lock, 50 pages at most per list, and 249 country codes for the branch lookup.

## A day with the defaults

Each timer round runs 4 h 48 m after the last one, so a copy is renewed 1 h 12 m before its 6 h lifetime would end. The time of the last round is kept in Redis, so a restart continues the schedule instead of starting it over.

| Time | What happens | Case |
| --- | --- | --- |
| 0:00 | The app starts on an empty Redis and is listening after about 1 s. Visitors get misses at first, and the pages they ask for are saved. | 2, 1 |
| 0:06 | The common pages are seeded. | 2 |
| 0:09 | The seed is finished. The finished-seed note is saved, and the last-refresh time is set to now. | 2 |
| 0:30 | An editor saves a passport. About 7 s later the new copy is on the shelf, and nobody waited. | 3 |
| 4:57 | First timer round, 4 h 48 m after 0:09: every remembered URL is re-fetched and every copy gets a fresh 6 h (24 h for full lists). The note and the last-refresh time are renewed. | 4 |
| 6:00 | The first copies would have gone stale here, but the 4:57 round already renewed them. | 4 |
| 7:00 | A deploy restarts the app. The note is found, nothing is seeded, and it is listening after about 1 s. The last-refresh time is read from Redis, so the next round stays due at 9:45. | 2, 4 |
| 9:45 | Second timer round, 4 h 48 m after 4:57. | 4 |
| Restart with a round overdue | If the last round was longer than 4 h 48 m ago, the next one runs 3 s after boot. | 4 |
| App down for 8 h | The finished-seed note has expired, so the next start seeds again. The stale copies are still in Redis (for 7 days) and are replaced as the seed reaches them. | 2 |

## Measured on the dev site

These numbers come from the dev WordPress and a local copy of the API on 15 and 16 October 2026. A production WordPress with more PHP workers will be faster on the uncached rows.

### Speed

| What | Result |
| --- | --- |
| A page on the shelf | 1–8 ms |
| A page not on the shelf | 0.5–3 s |
| Reply to a purge note | 26 ms |

### Edits and refreshes

| What | Result |
| --- | --- |
| Edited passport visible after the purge | About 7 s; the slowest request during the pass took 15 ms |
| A whole refresh pass (10 remembered URLs) | 17 s |

### Startup

| What | Result |
| --- | --- |
| Seed on an empty Redis | Common pages in about 6 min; everything (2,396 URLs, about 2,100 copies) in about 8.7 min |
| Restart with Redis intact | Listening after about 1 s, seed skipped, 0 WordPress calls |
| Sampled requests right after that restart | 77 of 79 under 50 ms; the other 2 were page 2 of an empty list and a made-up country code |

### WordPress outage (case 7)

Run locally with the copies expired and WordPress replaced by a closed port.

| What | Result |
| --- | --- |
| App start | Starts normally |
| Cached pages asked for (6) | All answered 200 with `X-Cache: STALE`; the 2 compared were identical to the original answers |
| First request | 23 ms (it discovers the outage and runs once more) |
| Later requests | 2–4 ms |
| A page never cached | Returns an error |

### Automated tests

| What | Result |
| --- | --- |
| Suites and tests | 107 suites, 636 tests, all passing |
| End-to-end scenarios | 33, covering cases 1 to 7 on a real HTTP server with an in-memory Redis |
