Skip to content

GraphQL response cache can miss keys on invalidation under concurrent requests #15523

Closed

Description

Bug description

Statamic\GraphQL\ResponseCache\DefaultCache invalidates by forgetting the keys it has recorded under gql-cache:tracked-responses. That list is maintained in track() with a read-modify-write (Cache::get → push → Cache::put) that is not atomic, so when several GraphQL requests are cached at the same moment they overwrite each other's copy of the list and some keys are never recorded.

A response whose key was dropped is never forgotten by handleInvalidationEvent(). It keeps being served until statamic.graphql.cache.expiry runs out (60 minutes by default), no matter how many EntrySaved or other content events fire in between.

We hit this on a headless site where the front end fires the entry-by-slug query, the listing query and a metadata query for the same page in parallel. A slug was queried a minute before its entry was created, so the null response was cached; the entry was then published from the CP (which did fire EntrySaved, and other keys were flushed), but this one key had been lost from the tracked list and the page 404'd for the full hour while its siblings rendered.

I would have expected every cached response to be dropped on a content event, whatever the request concurrency.

How to reproduce

  1. Fresh install with GraphQL enabled and a cache store that is shared across PHP workers (database here; redis or file behave the same, only array hides it).
  2. Serve the site with more than one PHP worker, for example:
    cd public && PHP_CLI_SERVER_WORKERS=8 php -S 127.0.0.1:8123 index.php
    
  3. Fire 30 distinct queries concurrently, then compare the tracked list with what was actually stored:
    php artisan cache:clear
    seq 1 30 | xargs -P 30 -I{} curl -s -o /dev/null -X POST http://127.0.0.1:8123/graphql \
      -H 'Content-Type: application/json' \
      -d '{"query":"{ entry(collection: \"pages\", slug: \"missing-{}\") { id } }"}'
    php artisan tinker --execute 'echo count(Cache::get("gql-cache:tracked-responses", []))." tracked, ".DB::table("cache")->where("key","like","%gql-cache:%")->where("key","not like","%tracked%")->count()." stored";'
    
  4. Fire any content event and count what survives:
    php artisan tinker --execute 'event(new Statamic\Events\EntrySaved(Statamic\Facades\Entry::query()->first())); echo DB::table("cache")->where("key","like","%gql-cache:%")->where("key","not like","%tracked%")->count()." still cached";'
    

Five runs of step 3 on a database cache store gave 29 of 30, 19 of 30, 30 of 30, 28 of 30 and 27 of 30 tracked. After the last run, step 4 left 3 responses in the cache that no event will ever remove. With a single worker (php artisan serve without PHP_CLI_SERVER_WORKERS) the requests are serialised and it never reproduces, which is probably why it has gone unnoticed.

The code in question, unchanged on 6.x:

https://github.com/statamic/cms/blob/6.x/src/GraphQL/ResponseCache/DefaultCache.php#L38-L52

Suggested fix

Drop the tracked list and key responses under a generation number instead, so invalidation is a single atomic operation:

protected function getCacheKey(Request $request)
{
    return 'gql-cache:'.$this->generation().':'.md5($query).'_'.md5(json_encode($vars));
}

public function handleInvalidationEvent(Event $event)
{
    if (Cache::increment('gql-cache:generation') === false) {
        Cache::add('gql-cache:generation', 1); // database store returns false on a missing key
    }
}

Superseded generations age out at the existing expiry. Two details worth keeping if you go this way: read the generation once in get() and reuse it in put() (the middleware calls them either side of executing the query), so a response computed before an event cannot land in the new generation; and note that DatabaseStore::increment() returns false rather than creating a missing key, so the counter needs seeding. We are running this shape in production behind our own ResponseCache binding and can send a PR if it would help.

Logs

No response

Environment

Environment
Laravel Version: 13.33.0
PHP Version: 8.5.0
Composer Version: 2.8.12
Environment: local
Debug Mode: ENABLED
Maintenance Mode: OFF
Timezone: UTC
Locale: en

Cache
Config: NOT CACHED
Events: NOT CACHED
Routes: NOT CACHED
Views: CACHED

Drivers
Broadcasting: log
Cache: database
Database: sqlite
Logs: stack / single
Mail: log
Queue: database
Session: database

Storage
public/storage: NOT LINKED

Statamic
Addons: 2
License Key: Not set
Sites: 3
Stache Watcher: Enabled (auto)
Static Caching: Disabled
Version: 6.34.0 PRO

Statamic Addons
cboxdk/statamic-mcp: 3.0.0
statamic/eloquent-driver: 5.11.1

Statamic Eloquent Driver
Addon Settings: file
Asset Containers: file
Assets: eloquent
Blueprints: file
Collection Trees: eloquent
Collections: file
Entries: eloquent
Fieldsets: file
Form Submissions: eloquent
Forms: file
Global Sets: file
Global Variables: eloquent
Navigation Trees: eloquent
Navigations: file
Revisions: eloquent
Sites: file
Taxonomies: file
Terms: eloquent
Tokens: eloquent

Installation

Existing Laravel app

Additional details

Headless: the GraphQL API is the only consumer of the content, statamic.routes.enabled is false and the entries live in the database via the Eloquent driver. Production runs the same versions on MySQL with the database cache store and two or more PHP workers per instance.

Activity

  1. marcingajda commented on Oct 29, 2026

    @marcingajda

    The REST API cache has the same problem. Statamic\API\Cachers\DefaultCacher keeps api-cache:tracked-responses with the same read-modify-write in trackEndpoint(). The class is identical on the current 6.x, and 5.x has the same tracking logic:

    public function handleInvalidationEvent(Event $event)
    {
    $this->getTrackedResponses()->each(function ($key) {
    Cache::forget($key);
    });
    Cache::forget($this->getTrackingKey());
    }
    /**
    * Track endpoint and return new cache key.
    *
    * @param Request $request
    * @return string
    */
    protected function trackEndpoint($request)
    {
    $newKey = $this->getCacheKey($request);
    $keys = $this
    ->getTrackedResponses()
    ->push($newKey)
    ->unique()
    ->values()
    ->all();
    Cache::put($this->getTrackingKey(), $keys);
    return $newKey;
    }

    Reproduced locally (Statamic 6.36.0, Laravel 13.37, PHP 8.5, Redis 7 cache store) with 8 PHP processes calling put() concurrently, 300 distinct URLs each: all 2400 responses were stored, but only 644 were tracked (630 and 653 in other runs), and after an invalidation 1756 were still cached. Nothing removes them before statamic.api.cache.expiry, whatever content events fire in between.

    Reproduction

    A cache store shared between processes (we used redis), default statamic.api.cache config, at least one entry:

    php artisan cache:clear
    
    for w in $(seq 1 8); do
      php artisan tinker --execute '
        $cacher = app(Statamic\API\Cacher::class);
        foreach (range(1, 300) as $i) {
            $cacher->put(
                Illuminate\Http\Request::create("http://localhost/api/repro/'"$w"'/$i"),
                new Illuminate\Http\JsonResponse(["ok" => true])
            );
        }' &
    done
    wait
    
    php artisan tinker --execute 'echo count(Cache::get("api-cache:tracked-responses", [])), " of 2400 tracked\n";'
    
    php artisan tinker --execute '
        event(new Statamic\Events\EntrySaved(Statamic\Facades\Entry::query()->first()));
        $left = 0;
        foreach (range(1, 8) as $w) {
            foreach (range(1, 300) as $i) {
                $left += Cache::has("api-cache:".md5("/api/repro/$w/$i")) ? 1 : 0;
            }
        }
        echo $left, " still cached after invalidation\n";'

    Besides concurrent put() calls, the same class has two more windows:

    • handleInvalidationEvent() forgets the tracked keys one by one and only then forgets the list. A key tracked by another request during that loop is dropped together with the list, so its response is not invalidated before expiry either. We confirmed this by calling put() from a KeyForgotten listener during the loop: the response stayed cached through that and the next invalidation.
    • The middleware calls get() before the controller runs and put() after it. A response built from content read before an event but stored after it goes into the fresh list, so the stale content is served until the next content event (or expiry).

    Our setup: a headless Nuxt front end on the REST API, several PHP pods sharing one Redis (Valkey). Every content event empties the whole API cache, so the requests that refill it arrive from several pods at once, which is when the tracked list gets rewritten concurrently. We found this by reading the code and reproduced it locally; we haven't measured how often it happens in production.

    The generation approach suggested above would fix the REST cacher too. Two details we are taking into account for our own cacher (bound via statamic.api.cache.class):

    • A random token instead of a counter for the generation. If the generation key is ever lost while responses from earlier generations are still within expiry (deleted by hand, or evicted under an allkeys-* policy), a counter starts again from 1 and can serve those responses again; a new random token cannot.
    • Superseded generations stay in the cache until expiry. With a long expiry and frequent content events that adds up, so we plan to also remove the previous generation's keys on invalidation, tracked per generation in a set (SADD is atomic). Losing an entry there only costs memory until expiry, never correctness.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions