PHPackages                             fyennyi/async-cache-php - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Caching](/categories/caching)
4. /
5. fyennyi/async-cache-php

ActiveLibrary[Caching](/categories/caching)

fyennyi/async-cache-php
=======================

Asynchronous caching library with rate limiting and stale-while-revalidate support.

v1.2.1(2mo ago)04194LicenseRef-CSSM-Unlimited-2.0PHPPHP &gt;=8.1CI passing

Since Jan 23Pushed 1mo agoCompare

[ Source](https://github.com/Fyennyi/async-cache-php)[ Packagist](https://packagist.org/packages/fyennyi/async-cache-php)[ Fund](https://opencollective.com/cssm)[ Patreon](https://www.patreon.com/ChernegaSergiy)[ RSS](/packages/fyennyi-async-cache-php/feed)WikiDiscussions main Synced today

READMEChangelog (7)Dependencies (45)Versions (9)Used By (4)

Async Cache PHP
===============

[](#async-cache-php)

[![Latest Stable Version](https://camo.githubusercontent.com/860f63350c96fbf982a68b23f1b6174da39be96a11fd254a981fc9fbc8e64418/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6679656e6e79692f6173796e632d63616368652d7068702e7376673f6c6162656c3d5061636b6167697374266c6f676f3d7061636b6167697374)](https://packagist.org/packages/fyennyi/async-cache-php)[![Total Downloads](https://camo.githubusercontent.com/3cc212e09bdc6709cc3092a77fe3c7095f3e5178332affcccae397e460af8c1f/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6679656e6e79692f6173796e632d63616368652d7068702e7376673f6c6162656c3d446f776e6c6f616473266c6f676f3d7061636b6167697374)](https://packagist.org/packages/fyennyi/async-cache-php)[![License](https://camo.githubusercontent.com/a5b65cd777e573d8432162f7592eb57aaa3a09fd743c9892840afb328fcc1951/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6679656e6e79692f6173796e632d63616368652d7068702e7376673f6c6162656c3d4c6963656e6365266c6f676f3d6f70656e2d736f757263652d696e6974696174697665)](https://packagist.org/packages/fyennyi/async-cache-php)[![Tests](https://camo.githubusercontent.com/22e7c7537a8d0a3a673b1c630182c1516b2c6f7953dc34e8859f4f649c3ab18e/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f4679656e6e79692f6173796e632d63616368652d7068702f706870756e69742e796d6c3f6c6162656c3d5465737473266c6f676f3d676974687562)](https://github.com/Fyennyi/async-cache-php/actions/workflows/phpunit.yml)[![Test Coverage](https://camo.githubusercontent.com/9d848003e87219426927b6530d13cf4395d4cb08264ac45216dace8be3b0047a/68747470733a2f2f696d672e736869656c64732e696f2f636f6465636f762f632f6769746875622f4679656e6e79692f6173796e632d63616368652d7068703f6c6162656c3d54657374253230436f766572616765266c6f676f3d636f6465636f76)](https://app.codecov.io/gh/Fyennyi/async-cache-php)[![Static Analysis](https://camo.githubusercontent.com/cf57eff7506726599e62200ed9dbb05a62c7682b5657e5a98fb1cdf7d9f2e88a/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f4679656e6e79692f6173796e632d63616368652d7068702f7068707374616e2e796d6c3f6c6162656c3d5048505374616e266c6f676f3d676974687562)](https://github.com/Fyennyi/async-cache-php/actions/workflows/phpstan.yml)

An asynchronous caching abstraction layer for PHP with built-in rate limiting and stale-while-revalidate support. This library is designed to wrap promise-based operations (like ReactPHP Promises) to provide robust caching strategies suitable for high-load or rate-limited API clients.

Features
--------

[](#features)

- **Asynchronous Caching**: Wraps `PromiseInterface` or any callable returning a value/promise to handle caching transparently without blocking execution.
- **Stale-While-Revalidate**: Supports background revalidation and stale-on-error patterns.
- **X-Fetch (Probabilistic Early Recomputation)**: Implements the X-Fetch algorithm to prevent cache stampedes (dog-pile effect).
- **Atomic Operations**: Support for atomic `increment` and `decrement` operations using Symfony Lock.
- **Logical vs. Physical TTL**: Separates the "freshness" of data from its "existence" in the cache, enabling soft expiration patterns.
- **Rate Limiting Integration**: Supports Symfony Rate Limiter for request throttling.
- **PSR-16 &amp; ReactPHP Compatible**: Works with any PSR-16 Simple Cache adapter or ReactPHP Cache implementation.

Installation
------------

[](#installation)

To install the Async Cache PHP library, run the following command in your terminal:

```
composer require fyennyi/async-cache-php
```

Usage
-----

[](#usage)

### Basic Setup

[](#basic-setup)

The easiest way to create a manager is using the fluent configuration API.

```
use Fyennyi\AsyncCache\AsyncCacheManager;
use React\Cache\ArrayCache;

// 1. Setup Cache (using ReactPHP ArrayCache as an example)
$cache = new ArrayCache();

// 2. Create the Manager using fluent configuration
$manager = new AsyncCacheManager(
    AsyncCacheManager::configure($cache)
        ->build()
);
```

### Wrapping an Async Operation

[](#wrapping-an-async-operation)

Use the `wrap` method to cache a promise-based operation.

```
use Fyennyi\AsyncCache\CacheOptions;
use Fyennyi\AsyncCache\Enum\CacheStrategy;
use React\Http\Browser;

$browser = new \React\Http\Browser();

$options = new CacheOptions(
    ttl: 60,                        // Data is fresh for 60 seconds
    strategy: CacheStrategy::Strict // Default strategy
);

$promise = $manager->wrap(
    'cache_key_user_1',
    fn() => $browser->get('https://api.example.com/users/1')->then(
        fn($response) => (string)$response->getBody()
    ),
    $options
);

// Handle the result asynchronously
$promise->then(function ($data) {
    echo "User data: " . $data;
});
```

### Advanced Configuration Options

[](#advanced-configuration-options)

The `CacheOptions` DTO allows you to configure behavior per request:

```
use Fyennyi\AsyncCache\Enum\CacheStrategy;

new CacheOptions(
    ttl: 300,                        // Time in seconds data is considered fresh
    stale_grace_period: 86400,       // Keep stale data physically in cache for 24h
    strategy: CacheStrategy::Strict, // Strict, Background, or ForceRefresh
    rate_limit_key: 'nominatim',     // Key for rate limiting (if limiter is configured)
    serve_stale_if_limited: true,    // Return stale data if rate limited
    tags: ['geo', 'kyiv'],           // Cache tags (if adapter supports them)
    compression: false,              // Enable data compression
    compression_threshold: 1024,     // Minimum size in bytes to trigger compression
    fail_safe: true,                 // Catch cache exceptions and treat as misses
    x_fetch_beta: 1.0                // Beta coefficient for X-Fetch (0 to disable)
);
```

### Atomic Increments

[](#atomic-increments)

```
$manager->increment('page_views', 1)->then(function($newValue) {
    echo "New value: " . $newValue;
});
```

How It Works
------------

[](#how-it-works)

1. **Cache Hit**: If data is found in the cache and is fresh (within `ttl`), the promise resolves immediately with the cached value. The factory function is not called.
2. **Cache Miss**: If data is not found, the factory function is executed, and the result is stored in the cache.
3. **Stale Data**:
    - If data is in the cache but expired (older than `ttl`), the manager behavior depends on the chosen `strategy`.
    - **Strict**: Fetches fresh data while the request waits.
    - **Background**: Returns stale data immediately and triggers an asynchronous refresh in the background.
4. **X-Fetch**: Helps avoid simultaneous cache misses for the same key by probabilistic early recomputation.

Contributing
------------

[](#contributing)

Contributions are welcome and appreciated! Here's how you can contribute:

1. Fork the project
2. Create your feature branch (`git checkout -b feature/AmazingFeature`)
3. Commit your changes (`git commit -m 'Add some AmazingFeature'`)
4. Push to the branch (`git push origin feature/AmazingFeature`)
5. Open a Pull Request

Please make sure to update tests as appropriate and adhere to the existing coding style.

License
-------

[](#license)

This library is licensed under the CSSM Unlimited License v2.0 (CSSM-ULv2). See the [LICENSE](LICENSE) file for details.

###  Health Score

42

—

FairBetter than 88% of packages

Maintenance87

Actively maintained with recent releases

Popularity14

Limited adoption so far

Community12

Small or concentrated contributor base

Maturity49

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~13 days

Recently: every ~19 days

Total

7

Last Release

82d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/e2471bdadcf4a5ea969fe763a72d03fb46525b59a7e4cedc3ed4d855029e7785?d=identicon)[ChernegaSergiy](/maintainers/ChernegaSergiy)

---

Top Contributors

[![ChernegaSergiy](https://avatars.githubusercontent.com/u/60980650?v=4)](https://github.com/ChernegaSergiy "ChernegaSergiy (359 commits)")

---

Tags

asynccachingguzzle-promisesperformancephpphp8psr-16rate-limitstale-while-revalidatethrottling

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/fyennyi-async-cache-php/health.svg)

```
[![Health](https://phpackages.com/badges/fyennyi-async-cache-php/health.svg)](https://phpackages.com/packages/fyennyi-async-cache-php)
```

###  Alternatives

[shopware/core

Shopware platform is the core for all Shopware ecommerce products.

585.6M574](/packages/shopware-core)[shopware/platform

The Shopware e-commerce core

3.4k1.5M3](/packages/shopware-platform)[symfony/symfony

The Symfony PHP framework

31.4k87.2M2.2k](/packages/symfony-symfony)[web-auth/webauthn-lib

FIDO2/Webauthn Support For PHP

12310.5M135](/packages/web-auth-webauthn-lib)[web-auth/webauthn-framework

FIDO2/Webauthn library for PHP and Symfony Bundle.

515100.5k3](/packages/web-auth-webauthn-framework)[flow-php/flow

PHP ETL - Extract Transform Load - Data processing framework

85036.3k](/packages/flow-php-flow)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
