Framework-independent PHP library for preventing duplicate execution of logical operations, replaying their results, and reconciling uncertain outcomes. Designed for HTTP APIs, command handlers, message consumers and integrations that may receive the same operation more than once.
- Atomic claim acquisition, fingerprint validation and ownership checks.
- Exact, binary-safe result replay within a configurable retention period.
- Conservative lease expiry: an uncertain operation is never retried automatically.
- Separate capabilities for inspection, reconciliation, discovery and cleanup.
- PSR-20 clock; no framework, database or serialization dependency.
Production boundary: the included MemoryStore is an in-process reference
implementation. It does not survive process termination and is not shared
between workers. Persistent adapters and framework integrations are not included.
Do not use it to protect real payments or other operations requiring durable
duplicate suppression.
PHP 8.4 or newer within PHP 8.x, Composer and psr/clock 1.x.
For the development branch, before a stable package is published:
composer config repositories.componenta-idempotency vcs https://github.com/componenta/idempotency.git
composer require componenta/idempotency:dev-mainAfter a stable package is available through your Composer repositories:
composer require componenta/idempotencyThe following example uses a single store instance and a simulated operation. The second call returns the saved bytes without invoking the operation again.
use Componenta\Idempotency\{Executor, MemoryStore, Policy, Request};
use Psr\Clock\ClockInterface;
$clock = new class implements ClockInterface {
public function now(): DateTimeImmutable
{
return new DateTimeImmutable('now');
}
};
$store = new MemoryStore($clock);
$executor = new Executor($store, new Policy(
leaseSeconds: 30,
retentionSeconds: 3600,
));
$request = Request::fromPayload(
scope: 'tenant:42:orders:create',
key: 'operation-123',
payload: '{"sku":"A42","qty":1}',
);
$executions = 0;
$operation = static function () use (&$executions): string {
++$executions;
return '{"orderId":42}';
};
$first = $executor->execute($request, $operation);
$second = $executor->execute($request, $operation);
// $first === $second; $executions === 1The result is a byte string, including the empty string or binary data. Encode
the application's result explicitly; the core does not serialize objects or
normalize JSON. A successful callback is not sufficient by itself: execute()
returns only after the store acknowledges completion or supplies a saved result.
Runnable example: examples/basic.php.
| Type or property | Meaning |
|---|---|
Request::$scope |
Application-defined namespace, including the relevant tenant/principal and operation |
Request::$key |
Stable identifier of one logical operation, reused across retries |
Request::$fingerprint |
64 lowercase hexadecimal characters representing SHA-256 or HMAC-SHA-256 of the operation's semantic input |
Policy::$leaseSeconds |
Positive integer seconds before an active attempt becomes uncertain |
Policy::$retentionSeconds |
Positive integer seconds to retain a completed or explicitly retryable record after settlement |
Scope and key are case-sensitive byte strings of 1–255 bytes each. Identity is
the pair (scope, key), not the fingerprint alone. Different keys identify
different operations, even when their payloads are identical.
Request::fromPayload() hashes exactly the supplied bytes. For equivalent
structured inputs, canonicalize them in the application before hashing.
For sensitive low-entropy inputs, construct Request with an application-owned
HMAC-SHA-256 instead of an unkeyed hash. Never derive authorization from a key
or fingerprint. Authenticate and authorize before acquisition and replay.
The policy is captured when a new claim is acquired. Duplicate requests cannot
change the existing deadlines. Deadlines are Unix seconds, exclusive at the
boundary; retention starts at the settlement time sample, not acquisition or
acknowledgement. Transaction and acknowledgement delays can shorten the remaining
lease/retention interval, even to zero. After retention
expires, a key can be acquired again, even with a different fingerprint.
Choose retention according to the maximum expected retry/delivery horizon and
allow a margin for database and network delays. A new claim is rejected if
adding either policy duration to the acquisition time would overflow an integer.
At settlement, retention uses the later sample. If it reaches or exceeds
PHP_INT_MAX, RetentionDeadline::NEVER is stored instead of stranding the
attempt. Terminal expiresAt === RetentionDeadline::NEVER means no automatic
expiry. This conservative boundary rule does not apply to active leases.
| Acquisition result | Meaning | Caller action |
|---|---|---|
Claim |
New attempt; ownership granted | Execute once; settle with this claim |
InProgress |
Matching attempt still active | Wait or return a conflict; do not execute |
Completed |
Matching retained result | Replay payload unchanged |
Unknown |
Outcome not confirmed | Reconcile; do not execute blindly |
Conflict::FingerprintMismatch |
Key reused for different input | Reject the conflicting request |
inspect() additionally returns Retryable (a matching new claim is permitted)
or null (no retained record). Inspection does not grant ownership.
A lease is an observation deadline, not permission to steal execution.
Expiry moves an unresolved attempt to Unknown; it does not delete the record.
Only a verified settlement or reconciliation can allow a new execution.
The original owner can still record a definitive result after expiry, provided
the attempt has not been settled or superseded.
Executor::execute(Request $request, callable $operation): string handles normal
acquisition and replay. The callback takes no arguments and returns a string.
It is never invoked when acquisition is blocked or fails.
| Exception | Meaning |
|---|---|
ExecutionBlockedException |
Callback was not invoked; inspect reason for InProgress, Unknown or Conflict |
StoreException during acquisition |
Callback was not invoked; the claim write itself may have committed |
UncertainExecutionException |
Callback was invoked but the result or its persistence was not confirmed |
UncertainExecutionException::$attempt identifies the attempt.
getPrevious() preserves the original error and recordingFailure preserves an
additional failure to mark uncertainty, if present. A null recordingFailure
does not by itself prove the record is unknown: completion may already have
committed. Inspect the authoritative store before deciding what to do next.
The executor neither retries nor renews leases automatically. It does not provide a transaction around external effects.
All types below live in Componenta\Idempotency.
StoreInterface method |
Contract |
|---|---|
acquire(Request, Policy) |
Atomically claim or return one of the acquisition results above |
renew(Claim): bool |
Extend a live active lease using its original policy |
complete(Claim, string): bool |
Persist a definitive result, including after lease expiry if still owned |
markUnknown(Claim): bool |
Record uncertainty while retaining the current owner |
abandon(Claim): bool |
Permit a matching retry only after proving no effects occurred and none can still occur |
Owner operations return false for a stale, missing, unauthorized or inapplicable
claim; storage failures throw StoreException. False is not a storage error.
Claim::$attempt identifies the current attempt; Claim::token() is a private
adapter-facing bearer credential, not an identifier to return to API clients.
Use the low-level contract instead of Executor when the caller must renew a
lease, prove a no-effect failure, or coordinate an application transaction.
These capabilities are intentionally separate from the execution port.
| Interface | Method | Purpose |
|---|---|---|
RecoveryStoreInterface |
inspect(Request) |
Observe a retained record without acquiring it |
resolveCompleted(Attempt, string): bool |
Record an authoritative result for the exact unknown attempt | |
resolveRetryable(Attempt): bool |
Permit retry only after verifying no effects and quiescence or effective fencing | |
UnknownAttemptProviderInterface |
findUnknown(int $limit = 100, ?Request $after = null): array |
List unknown attempts, including expired active leases |
PrunableStoreInterface |
pruneExpired(int $limit = 100): int |
Remove at most the specified number of expired terminal records |
Persistent adapters may document a maximum batch size; limits above it are rejected, not silently truncated. The default batch size is always supported.
Discovery returns a list of Attempt values in binary (scope, key) order.
The cursor is exclusive: pass the last returned attempt's request for the next
page. Pages are advisory, not a consistent snapshot; run subsequent sweeps and
validate the exact attempt again at settlement. A discovered attempt ID is not
an ownership credential.
Only trusted, authorized recovery operators may use these capabilities. An unknown attempt must not be deleted or made retryable just because it is old. A new attempt requires proof that previous execution cannot still cause an effect.
MemoryStore(ClockInterface $clock, int $capacity = 10000, int $maxStoredPayloadBytes = 67108864) implements all four store capabilities.
The default limits are 10,000 retained records and 64 MiB of logical result
bytes. Exceeding either limit fails closed with StoreException; there is no
eviction of unresolved or live records. The byte limit is not a PHP process
memory limit. Reclaim expired terminal records with pruneExpired().
Unknown attempts remain retained until reconciled.
The store supports cooperating Fibers in one PHP process and one instance. It cannot coordinate different instances, processes, threads or asynchronous signal handlers. Keep the instance alive for the lifetime of the in-process operations you want to deduplicate.
Idempotency is not authentication, distributed locking, or exactly-once delivery. A crash after an external side effect but before recording completion cannot be resolved by this library alone. Use a durable atomic store, the external provider's idempotency key, or an appropriately coordinated domain transaction. Never infer absence of side effects from a timeout, network error or expired lease.
Keep ownership tokens and sensitive result bytes out of application logs, serialization and API responses. The implementation redacts sensitive arguments in its own exception stack frames; this is not protection against arbitrary object export, caller-owned exception traces or unsafe PHP deserialization. Access to the store and recovery interfaces is a trusted application boundary.
- Normative storage and transaction contract: mandatory semantics for alternative storage implementations.
- Design rationale and sources: architecture decisions.
composer install
composer test
composer analyse
php examples/basic.php
php tests/run.php
composer test:modelCI checks PHP 8.4 and 8.5, PHPStan at its maximum level, PHPUnit with line and branch/path coverage, and Infection mutation testing with a verified positive and negative control. The minimum full and covered MSI is 90%. The separate seeded model test compares 50,000 generated transitions against an independent oracle, including quota accounting, lazy expiry, clock rollback and recovery pagination.
MIT.