logo
podcast Podcast
get help Get Unstuck

Throttle lazy loading error reports in production

Avoid getting flooded with alerts

Joel Clermont
Joel Clermont
2025-09-02

I previously shared a way you could catch lazy loading issues in production without throwing errors for users.

What if you read that tip and wanted to turn it on in your production app, but you're worried about getting flooded with a bunch of alerts? Maybe you haven't been keep a close eye on lazy loading issues, and you suspect there could be a lot of them.

There are a number of ways you could tackle this, but here's an approach using Laravel's built-in exception throttling:

// In AppServiceProvider's boot method:
public function boot(): void
{
    Model::preventLazyLoading();
    
    Model::handleLazyLoadingViolationUsing(function ($model, $relation) {
        $exception = new LazyLoadingViolationException($model, $relation);
        
        if ($this->app->isProduction()) {
            // Throttling happens in bootstrap/app.php
            report($exception);
        } else {
            throw $exception;
        }
    });
}

Then configure the throttling in your bootstrap/app.php file:

use Illuminate\Cache\RateLimiting\Limit;

return Application::configure(basePath: dirname(__DIR__))
    // ... other routing/middleware config
    ->withExceptions(function (Exceptions $exceptions) {
        $exceptions->throttle(function (Throwable $e) {
            if ($e instanceof LazyLoadingViolationException) {
                $key = sprintf(
                    '%s:%s:%s',
                    get_class($e->model),
                    $e->relation,
                    request()->route()?->getName() ?? 'no-route'
                );
                
                return Limit::perDay(1)->by($key);
            }
        });
    })
    ->create();

Let's walk through the important parts of this throttling logic.

We're creating a throttle key that uniquely identifies the model, lazy loaded relation, and the current route. This allows us to get unique errors for each combination of these three values without getting bombarded if it happens to be on a busy route.

Our limit is configured to only report each unique error once per day, but you could adjust that depending on your preference.

Obviously, a solid test suite that would let you exercise all these routes locally is a nicer solution, but if you're not there yet, this is a way to get some visibility into lazy loading issues in production without overwhelming you with alerts.

Here to help,

Joel

P.S. And if you want some help getting that test suite in place for your app, we can help!

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼
email
No spam. Only real-world advice you can use.