# 🔥 Monitor Query Speed in Laravel Using Benchmark + Spatie

By Dinesh Uprety
Published: 2025-06-20
Updated: 2025-06-21
Canonical: https://laranepal.com/blog/monitor-query-speed-in-laravel-using-benchmark-spatie

# 🧪 Keep Your Laravel App Fast: Build a Custom Query Speed Health Check

Performance is not just a backend concern — it's a **user experience priority**. When your app starts to feel sluggish, the usual suspect is the database. But what if you could detect slow queries _before_ they impact your users?

In this article, we’ll build a **custom query speed check** in Laravel 11/12 using:

- Laravel’s new `Benchmark` helper,
- Spatie’s powerful `laravel-health` package,
- And a sprinkle of developer insight.

Let’s make sure your database stays snappy. 🏎️

---

## 🎯 Why Check Query Speed?

Your Laravel app might be beautiful on the surface, but if each database query takes 500ms, users will start noticing.

That’s where query monitoring comes in. Instead of waiting for performance issues to show up in logs (or worse, support tickets), you can **proactively benchmark your app’s critical queries** — right inside your health monitoring system.

---

## 🧰 Tools We’ll Use

- **Laravel 11 or 12**: With built-in `Benchmark::measure()` helper.
- **Spatie Laravel Health**: For registering and monitoring system checks.
- **Eloquent Models**: To test a realistic query scenario.

---

## ⚙️ Step 1: Install Spatie Health

First, install the `spatie/laravel-health` package if you haven’t already:

```bash
composer require spatie/laravel-health
```

Then, publish the config:

```bash
php artisan vendor:publish --tag="health-config"
```

---

## 🛠 Step 2: Create the Query Speed Check

This is where the magic happens. We’ll write a custom check that benchmarks a real query.

```php
namespace App\Checks;

use App\Models\Post;
use Illuminate\Support\Benchmark;
use Spatie\Health\Checks\Check;
use Spatie\Health\Checks\Result;

class QuerySpeedCheck extends Check
{
    public function run(): Result
    {
        $result = Result::make();

        $executionTimeMs = (float) Benchmark::measure(function () {
            Post::with('author')->orderBy('publish_at')->get();
        });

        if ($executionTimeMs >= 50 && $executionTimeMs <= 150) {
            return $result->warning("Database is starting to slow down: {$executionTimeMs}ms");
        }

        if ($executionTimeMs > 150) {
            return $result->failed("Database is slow: {$executionTimeMs}ms");
        }

        return $result->ok("Database performance is good: {$executionTimeMs}ms");
    }
}
```

### 🧠 What’s Happening Here?

- We’re running a real-world query on the Post model.
- `Benchmark::measure()` times the entire query execution.
- We return `ok()`, `warning()`, or `failed()` depending on the result.

You can tailor this logic and thresholds based on your app’s needs.

---

## 🔗 Step 3: Register the Custom Check

In a service provider (e.g. `HealthCheckServiceProvider`), register your custom check:

```php
namespace App\Providers;

use App\Checks\QuerySpeedCheck;
use Illuminate\Support\ServiceProvider;
use Spatie\Health\Facades\Health;

class HealthCheckServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        Health::checks([
            QuerySpeedCheck::new(),
        ]);
    }
}
```

Make sure this service provider is registered in your `config/app.php` or via auto-discovery.

---

## 📈 Step 4: Run the Health Check

You can view the check results using:

```bash
php artisan health:run
```

Or expose it via API:

```php
Route::get('/health', \Spatie\Health\Http\Controllers\HealthCheckResultsController::class);
```

Or in the beautiful Spatie Health Dashboard:

```bash
php artisan health:install-dashboard
```

---

## ✅ Result Output Examples

Here’s what your check might return:

| Status     |             Description              |
| :--------- | :----------------------------------: |
| ✅ OK      |       Response time under 50ms       |
| ⚠️ Warning | Response time between 50ms and 150ms |
| ❌ Failed  |       Response time over 150ms       |

---

## 🧩 Real-World Use Cases

- Monitor production DB response times daily or hourly.
- Run health checks before every deploy.
- Trigger alerts to Slack, Discord, or email when performance degrades.

---

## 💡 Bonus Tip: Customize the Query

You can change the benchmarked query to match your actual business logic. For example:

```php
User::where('status', 'active')->withCount('orders')->get();
```

Benchmark something critical to your application flow — not a toy query.

---

## 🧘 Conclusion

With just a few lines of code, you’ve created a lightweight and effective **performance radar** for your Laravel application.

- ✅ Easy to implement
- ✅ Tracks real-world database performance
- ✅ Fully integrates with Spatie Health’s ecosystem

Proactive monitoring isn't just for large-scale systems — it should be part of every Laravel developer’s toolbox. By benchmarking your critical queries, you ensure that your application stays fast, responsive, and user-friendly.

Start small, monitor smart, and scale with confidence. 🚀
