Stale results or errors: choosing a stale-data policy

Separate freshness, maximum cache age, and source age across three teaching workloads: news, a profile, and a forecast. Explicit failures and time limits determine when old data remains eligible.

A reserve remains useful only within a defined age policy.

A fictional journal cannot refresh its news feed because the source is temporarily unavailable. The previous list is still in memory. Should the journal display it with an explanation or leave the reader with an error message? The same question can have a different answer for a personal profile. An old value sometimes helps someone continue reading and sometimes conceals an important change.

Choosing between stale data and an error is therefore part of the product contract. A universal TTL cannot determine that choice on its own. We need to define what becomes old, which failure permits reuse of the previous result, and when that permission ends. Consider an independent teaching model for news, a profile, and a forecast, with explicit limits and controlled time.

What a stale result promises

A fresh read means that the result remains within the accepted interval after the source was successfully checked. A stale read means something different: the check was due, it failed, but a particular policy still permits the old result. The stale label must not silently turn into an ordinary success.

HTTP has separate mechanisms: RFC 5861 describes stale-if-error and stale-while-revalidate. The former permits an old response following a qualifying error; the latter permits one during background revalidation. Our exercise reads the source synchronously once freshness ends. There is no background queue.

This is an application policy for reading data. It does not set HTTP headers or configure a browser or CDN. RFC 9111 separately defines HTTP cache rules and response age calculation. A field containing seconds in our object does not implement the Age header.

Three workloads instead of one universal TTL

We choose the following numbers for the teaching data. They illustrate differences between policies; they do not recommend lifetimes for real news, accounts, or meteorological services.

Result Freshness after a check, s Maximum cached-result age, s Additional condition
News feed 60 300 The old list is permitted only when the source is temporarily unavailable
Personal profile 0 0 Bypass the cache entirely; require a new authorized read
Fictional forecast 300 1800 The source dataset must also be younger than 7200 s

max_cache_age is an absolute limit measured from a successful check, not an additional period after freshness ends. All upper limits are exclusive. News aged 59 s is still fresh; at 60 s a source request is required. Following a qualifying failure, a value aged 299 s can still be returned, but one aged 300 s cannot. The corresponding forecast limits are 300 and 1800 s.

A profile with a 0/0 policy is not a record that may briefly be shown before its TTL expires. The reader never accesses its cache and writes nothing to it. This deliberately chooses failure without an old value, even if someone left such an entry in the store. The profile does not establish a universal ban on caching personal data: another product would need its own contract.

An allowed stale period also does not permit ignoring an article's withdrawal from publication. If a product must immediately hide withdrawn text, an old list without a current visibility signal can break that promise. Such a result needs reliable invalidation, a separate check, or no fallback. The teaching feed does not model that mechanism. Choosing numbers starts with the consequence of an error: can the reader act on the previous value, and is an honest label sufficient to avoid misleading them?

Check age and source age answer different questions

A snapshot stores checkedAt: the moment the application successfully received and validated the data. Check age indicates how long ago the application confirmed that result. A separate sourceAsOf field comes from the synthetic source and identifies the origin of its dataset. Fetching an old dataset again resets only the first age.

For the forecast, sourceAsOf means when the fictional dataset was prepared, not the time for which the weather is predicted. A complete weather contract must distinguish those times as well. Here, the independent 7200 s limit simply shows why another HTTP request or cache write cannot make an old source younger.

Once source age reaches its limit, even a young snapshot requires another read. If the source is unavailable, its previous data can no longer be returned. If the source responds with an invalid or overly old dataset, that response is rejected; an otherwise eligible cached value does not conceal it.

A negative time, a snapshot from the future, or a clock moving backwards does not mean “very fresh data.” The teaching model rejects that uncertainty. This checks the chosen time model; it is not a clock synchronization service for different machines.

Not every error permits fallback

The example distinguishes an explicit SourceUnavailable, an upstream access refusal, invalid data, and an unexpected programming error. Only the first case opens the stale branch. An application adapter in a real product must carefully decide which transport failures map to that category. Catching every exception would conceal a broken schema or incorrect authorization.

Current permission is checked before reading either the cache or the source. The key contains the workload, site, locale, and subject of the read; it separates results but grants no rights. Permission is a trusted fixture in this exercise. Real authentication, permission refresh, and session revocation require separate integration.

A refresh operation can take a long time. Eligibility for fallback is therefore checked again after the failure, using the current time. A snapshot may have been eligible before the request and crossed its age limit while waiting. The initial decision does not grant indefinite permission to return it.

Retention is not the same as freshness

To keep a previous result available for fallback, the store must retain it beyond the freshness interval. If the entry disappears immediately after 60 s, the news policy has nothing to choose from during the rest of its allowed period. Retention in the teaching store equals max_cache_age; a separate rule determines whether the result is fresh.

This does not read an expired entry through PSR-6. The PSR-6 contract requires an entry to be treated as a miss after expiration and permits a store to lose it earlier. Consequently, even correctly configured retention does not guarantee that a fallback value exists. A miss combined with an unavailable source makes the read fail.

Fallback does not write the snapshot again. Otherwise, every failure would postpone the final deadline and data could survive indefinitely. A new checkedAt appears only after a successful response, structure validation, and an acceptable source age. Merely reading an old value is not such a check.

An independent exercise with controlled time

Add the src/StaleRead module, StaleDemoCommand, fixture, and tests to one article_demo on Symfony 8.1 and 64-bit PHP 8.4+. Earlier steps already use Console and Clock; no new skeleton is created. Policies live in fixtures/stale-policies.json:

{
  "news": {"fresh_for": 60, "max_cache_age": 300, "max_source_age": null},
  "profile": {"fresh_for": 0, "max_cache_age": 0, "max_source_age": null},
  "forecast": {"fresh_for": 300, "max_cache_age": 1800, "max_source_age": 7200}
}

The reader and local store receive a clock interface. MockClock changes time in tests without real sleeps; a failed source call can deliberately advance it across a hard deadline. An earlier step already registered NativeClock. Add only these entries under the existing services block, preserving the earlier Psr Clock alias and other configuration:

services:
    App\StaleRead\PolicyCatalog:
        arguments:
            $path: '%kernel.project_dir%/fixtures/stale-policies.json'
    App\StaleRead\SnapshotStore: ~
    App\StaleRead\SyntheticSource: ~
    App\StaleRead\Source:
        alias: App\StaleRead\SyntheticSource
    App\StaleRead\StaleReader: ~
    App\Command\StaleDemoCommand: ~
    Symfony\Component\Clock\ClockInterface:
        alias: Symfony\Component\Clock\NativeClock

The command in the same application shows one new synthetic read:

php bin/console app:stale-demo --workload=news

The memory store lives only in that process. Repeated separate commands do not reproduce freshness transitions; controlled-time tests check them. The source makes no network calls. A Console test through the Kernel checks wiring rather than an HTTP controller.

What to check before acceptance

19 tests with 48 assertions were executed: cold/fresh reads, exact boundaries, repeated failures without extending age, successful refresh, independent source age, profile bypass, disallowed errors, access context, key partitioning, clock anomalies, and Console wiring. This checks a local model without a real upstream, Redis, distributed cache, or production permissions.

The returned object contains the value, fresh or stale, its origin, both ages, and the reason for degraded service. The interface should explain that a previous result is being shown and when it was last checked. A raw exception message is unnecessary. Once the allowed limit has passed, an explanation must not accompany a concealed old value.

In operation, it is useful to count refresh attempts, permitted stale responses, and failures after the deadline separately. A large proportion of successful responses does not by itself show that the source is healthy: the product might have relied on old snapshots for a long time. Counters in the teaching code help verify read ordering, but they do not form a complete metrics or alerting system. Configuring that monitoring remains a separate task.

Applying the approach requires separate decisions about invalidation, concurrent readers, load, and observability. This exercise does not prove those properties. Its practical purpose is to make the tradeoff visible: which previous result remains useful, following which specific failure, and until which limit, after which the product honestly reports unavailability.

  1. Architecture HTTP cache and application cache: who refreshes the page?
  2. Architecture Testing degraded operation: how a page behaves without its cache service
  3. Weather The provider is late: when can a forecast remain on display?