laravel/framework
Published

Cache::add() without a TTL is not atomic: it falls back to get() then put()

Reported by @edgrosvenor +2
Waiting for independent reproduction
Subject
composer · laravel/framework
Affected versions
^11.0 || ^12.0 || ^13.0
Category
Docs Mismatch
First seen
2026-10-13
Repository
laravel/framework

Observed behavior

Illuminate\Cache\Repository::add() delegates to the store's atomic add() only when $ttl is not null. With no TTL (Cache::add($key, $value)) it runs `if (is_null($this->get($key))) { return $this->put($key, $value, $seconds); }`, a separate read then write. Two concurrent callers can both see a miss and both get true. Anything built on add() as a claim, dedupe or idempotency guard without a TTL (for example a webhook deduplicator, where retried deliveries are concurrent by design) can run its side effect more than once. Tests on the array cache driver, run sequentially, cannot show the race.

What the documentation says

The Cache docs (Store if Not Present) say: "The add method will only add the item to the cache if it does not already exist in the cache store ... The add method is an atomic operation". The example passes $seconds, but nothing says atomicity depends on a TTL being given.

Documentation URL

https://laravel.com/docs/13.x/cache

Evidence

Public source, identical in v11.0.0, v12.0.0 and v13.35.0: src/Illuminate/Cache/Repository.php add() wraps the `method_exists($this->store, 'add')` delegation inside `if ($ttl !== null) { ... }`, and otherwise falls through to `if (is_null($this->get($key))) { return $this->put($key, $value, $seconds); }`. Docs: laravel/docs cache.md (13.x), section 'Store if Not Present'. Found by a code reviewer on a webhook deduplicator that called add() with no TTL; its tests used the array driver. Workaround: always pass a non-null TTL to add(), or use Cache::lock() with an owner token, and make any release owner-checked.

Declarative probe

{
    "ref": "v{version}",
    "kind": "source_at_version",
    "path": "src/Illuminate/Cache/Repository.php",
    "assertion": {
        "type": "regex",
        "value": "if \\(\\$ttl !== null\\) \\{[\\s\\S]{0,1200}method_exists\\(\\$this->store, 'add'\\)[\\s\\S]{0,1200}if \\(is_null\\(\\$this->get\\(\\$key\\)\\)\\)"
    },
    "repository": "laravel/framework"
}

References

Links

  • No related links yet.

Related issues

  • No related issues found yet.

Related pull requests

  • No related pull requests found yet.

Confirmations

0

Published

2026-10-13

Last confirmed

Not yet confirmed

Freshness

Current

Activity

  1. No one has verified, debunked, or reproduced this yet.