The PHP stat cache explained
PHP Performance
The PHP stat cache: useful performance optimization or technical debt?
When I explain how PHP’s stat cache works, it often comes as a surprise to developers because its behavior differs from what they expect. The cache was designed to solve a very specific problem that occurs when multiple file-system operations are performed on the same file in quick succession.
Why is it important to know how it works? Because occasionally you need to bypass the cache by using clearstatcache() to ensure that PHP code runs without errors.
Historical Context
Let’s start from the very beginning. What is stat()? It is a C-level API call to the file system used to retrieve a file’s metadata, such as the user, group, read and write permissions, size, and modification times. PHP wraps this call in its own userland function, also called “stat(),” and uses this function internally in various places.
Historically, file operations were very costly, so avoiding unnecessary calls to the file system seemed like a logical optimization.
PHP’s stat cache
This is where the PHP stat cache comes into play: it caches the result of low-level stat operations. With one important caveat: the cache stores this information for exactly one file, namely, the last one that used the cache. Furthermore, caching occurs at the request level; it is not a cross-request or cross-process cache like OPcache.
This means that when PHP performs a low-level stat operation on a file that wasn’t in the stat cache before, it will overwrite the previously stored data completely.
How is the stat cache implemented?
If the stat cache were to be implemented in PHP, it would look something like this:
<?phpclass FileStat{ private static string $cachedPath; private static array $cached; public static function stat(string $path): array { if ($path === self::$cachedPath) { return self::$cached; } $statBuffer = stat($path); self::$cachedPath = $path; self::$cached = $statBuffer; return $statBuffer; }}
You can find the corresponding C code in “ext/standard/filestat.c” in the “php_stat” function.
List of functions using the cache
An (almost) full list of functions, depending on this cache, can be found in the documentation of clearstatcache().
Two things about this list
- Notice there is a distinction between local and non-local files. Some functions skip the cache for local files.
- This list only contains low-level functions, while other functions or PHP core class methods (e.g.,
SplFileInfo) might depend on those and therefore also rely on the cache.
Here is the current list from the docs:
- Local files:
stat(),lstat(),filesize(),fileatime(),filemtime(),filectime(),fileinode(),fileowner(),filegroup(),fileperms(),filetype(),is_file(),is_dir(),is_link() - These additionally use it for non-local stream wrappers:
file_exists(),is_readable(),is_writable()/is_writeable(),is_executable()
List of functions invalidating the cache
We started compiling a list of functions that automatically clear the cache if needed. While it is challenging to keep this list complete and up-to-date, we also discovered that usually cache invalidation just works. Every case in wich a function does not properly invalidate the cache while simultaneously changing metadata for a file, should be considered a bug.
While researching this post, we found such a case, where the ftruncate() function would not properly invalidate the cache and opened a bug report.
Even generic functions like exec(), system(), and passthru() have been invalidating the cache since PHP 8.3.18 (commit), so arbitrary shell commands, which will often modify files, will not lead to stale data.
Example: clearstatcache needed
Turns out, the example on the documentation page for clearstatcache is also out of date, as chown properly clears the cache since PHP 8.3.18 (commit). We opened a pull request to fix the docs.
So that leaves us with the most obvious example for a stale cache: a race condition. If another process modifies the file in between two function calls that rely on the cache, stale data can be served:
<?php $file = tempnam(sys_get_temp_dir(), 'stat-demo-');file_put_contents($file, 'Hello'); echo "Run this command in another shell:\n";echo "\techo \" World!\" >> $file\n"; $before = filesize($file); // caches the metadata sleep(20); // Run the echo-command in another shell $cached = filesize($file); // stale data is returned clearstatcache(); $fresh = filesize($file); // returns the correct data printf("Before: %d\nCached: %d\nFresh: %d\n", $before, $cached, $fresh); unlink($file);
Output
Run this command in another shell: echo " World!" >> /tmp/stat-demo-6fjvs4vir9ll2haCl4WBefore: 5Cached: 5Fresh: 13
Conclusion
So where does this leave us?
Is the stat cache relevant? Does it have merit? Yes, but only for a very limited scope. Especially on Windows, file operations can be really slow, even more so in the past, when disks were still spinning most of the time. On Linux, the benefits are less prominent since there is an operating-system-wide file cache that keeps recent files and their metadata in memory.
The main use case is checking multiple file properties in short succession on slow or remote filesystems. E.g., file_exists($file) && is_writable($file) is a widely used pattern that can profit from this cache. Knowing the cache size of “1” is the important takeaway here. Check one file after another, or the cache will be useless.
Manually calling clearstatcache() is only very rarely required nowadays. But be aware of possible bugs: if you really need to make sure that file metadata is trustworthy, clear the cache first. Especially with multiple requests modifying the same file.
