July 17, 2025
Adding latency to dev APIs
A few weeks ago, a couple of major releases popped up. Rolldown became stable. Tiptap 3 was released. Nuxt 4 was released.
I'm not quite sure which one was the culprit, but the render speed improved enough that some race conditions were popping up.
Basically, some pages were throwing errors 'cause the data Medley needed to show the users, haven't finished being pulled down yet.
Throttling the network isn't an option 'cause even with Fast 4G, pulling down the larger dev files are painfully slow.
Instead I added this middleware
<?php
declare(strict_types=1);
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Lottery;
use Symfony\Component\HttpFoundation\Response;
class AddLatency
{
public function handle(Request $request, Closure $next): Response
{
if (config('app.env') === 'local') {
usleep($this->latency() * 1000);
}
return $next($request);
}
private function latency(): int
{
$base = Arr::random([
30, 30, 30, 30, 30, 30,
40, 40, 40, 40, 40, 40, 40,
50, 50, 50, 50, 50, 50, 50, 50,
60, 60, 60, 60, 60, 60, 60, 60, 60,
70, 70, 70, 70, 70, 70, 70, 70, 70, 70,
80, 80, 80, 80, 80, 80, 80, 80, 80, 80,
90, 90, 90, 90, 90, 90, 90, 90, 90,
100, 100, 100, 100, 100, 100,
110, 110, 110, 110, 110,
120, 120, 120, 120,
130, 130, 130,
140, 140,
150,
]);
$latency = $base + mt_rand(0, 9);
return Lottery::odds(9 / 10)
->winner(fn () => $latency)
->loser(fn () => $latency * 5)
->choose();
}
}
It's slow enough that race conditions will pop up but fast enough that I won't be annoyed working locally.