PHP 8.6 Duration and clamp() for retry backoff
PHP 8.6 went GA on November 19, and most of the coverage has gone to partial function application. The two additions I actually expect to touch my code first are quieter: a \Time\Duration class and a clamp() function. Every project I maintain has a retry loop somewhere with usleep($attempt * 250000) buried in it, and those two finally give that loop proper types.
What the manual actually says
I read the Time\Duration manual page before writing anything. It is a final readonly class with a private constructor, so you only get instances from factories: fromHours(), fromMinutes(), fromSeconds(int $seconds, int $nanoseconds = 0), fromMilliseconds(), fromMicroseconds(), fromNanoseconds() and fromIso8601DurationString().
It is immutable. add(), sub(), multiplyBy(int), divideBy(int), negate() and absolute() each return a new object. The public properties are $seconds (always non-negative), $nanoseconds (0 to 999999999) and a separate $negative flag. The sign lives in that flag, not in the other two fields. Comparison operators work on instances, but arithmetic operators do not, and a result that overflows the supported range throws Time\TimeException.
The clamp() page gives the signature clamp(mixed $value, mixed $min, mixed $max): mixed. It returns the value limited to [$min, $max] using normal comparison rules, and it keeps the original type. It throws a ValueError if $min is greater than $max, or if either bound is NAN. The 8.6 release page shows clamp() accepting Duration objects directly.
An exponential backoff with no magic numbers
Here is the shape I'm going to use. I traced it by hand and have not run it on 8.6 yet.
<?php
declare(strict_types=1);
use Time\Duration;
function backoffDelay(int $attempt): Duration
{
$base = Duration::fromMilliseconds(200);
// Cap the exponent so 2 ** $attempt can never overflow an int.
$factor = 2 ** min($attempt, 10);
return clamp(
$base->multiplyBy($factor),
min: $base,
max: Duration::fromSeconds(30),
);
}
function sleepFor(Duration $delay): void
{
time_nanosleep($delay->seconds, $delay->nanoseconds);
}
foreach (range(0, 5) as $attempt) {
if (callRemoteApi()) {
break;
}
sleepFor(backoffDelay($attempt));
}
Attempt 0 waits 200 ms, attempt 3 waits 1.6 s, and anything past attempt 7 is pinned at 30 s. The old version would have been min(30_000_000, 200_000 * 2 ** $attempt) passed to usleep(). That works, but the unit is only in your head, and the next developer has to guess whether it was microseconds or milliseconds.
A deadline budget you can compare
Because Duration supports comparison operators, a total retry budget reads like what it means:
<?php
use Time\Duration;
$budget = Duration::fromMinutes(2);
$spent = Duration::fromSeconds(0);
foreach (range(0, 20) as $attempt) {
$delay = backoffDelay($attempt);
if ($spent->add($delay) > $budget) {
throw new RuntimeException('Retry budget exhausted');
}
sleepFor($delay);
$spent = $spent->add($delay);
if (callRemoteApi()) {
return;
}
}
Both snippets assume a callRemoteApi() of yours that returns a bool. The point is the arithmetic: no division by a million, and no float seconds that quietly lose precision.
Gotchas I'd watch for
First, Duration measures elapsed stopwatch time. It is not a calendar interval, so it knows nothing about months or DST. Keep DateInterval for "one month from now" and use Duration for timeouts, backoff and TTLs. Second, the clamp() page itself warns that mixing argument types can give unpredictable results. Pass three Duration objects or three ints, never a blend. Third, a swapped min/max is a ValueError at runtime, so if the bounds come from config, validate them at boot.
None of this is exciting in a release-notes sense, and that is why I like it. It replaces a small, repeated source of unit bugs with a typed value, and I'll be moving my retry helpers over once my hosting images carry 8.6.