> ## Documentation Index
> Fetch the complete documentation index at: https://kawax.biz/llms.txt
> Use this file to discover all available pages before exploring further.

# Monitor database transaction duration

> Learn how to use Connection::whenTransactionRunsLongerThan in Laravel 13 to detect long-running transactions when they commit or roll back.

When you investigate slow transactions, you need to look beyond SQL execution time to the application code that runs inside the transaction and the time spent waiting for database locks. In Laravel 13.x, `Connection::whenTransactionRunsLongerThan` invokes a callback when the total elapsed time of a transaction exceeds a threshold you specify.

> [!NOTE]
>
> This page is based on the [Laravel Framework 13.x implementation](https://github.com/laravel/framework/blob/13.x/src/Illuminate/Database/Connection.php). Make sure the Framework version you use includes this method.

## Register a callback

To monitor database connections across your whole application, register the callback in the `boot` method of a service provider. The threshold is in **milliseconds**.

```php theme={null}
<?php

namespace App\Providers;

use Illuminate\Database\Connection;
use Illuminate\Database\Events\TransactionCommitted;
use Illuminate\Database\Events\TransactionRolledBack;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        DB::connection()->whenTransactionRunsLongerThan(
            500,
            function (
                Connection $connection,
                TransactionCommitted|TransactionRolledBack $event,
                float $duration,
            ): void {
                Log::warning('Long database transaction detected.', [
                    'connection' => $connection->getName(),
                    'duration_ms' => $duration,
                    'event' => $event::class,
                ]);
            },
        );
    }
}
```

The callback receives three arguments.

* `Connection`: the database connection being monitored
* `TransactionCommitted|TransactionRolledBack`: the event indicating whether the transaction was committed or rolled back
* `float`: the measured elapsed time (in milliseconds)

To monitor only a specific connection, specify the connection name, as in `DB::connection('mysql')`. To monitor several connections, register a callback on each `Connection`.

## What is measured

Measurement starts when the outermost transaction begins and ends when the outermost transaction commits or rolls back.

```php theme={null}
DB::transaction(function () {
    // Measurement starts here

    Order::create($orderData);

    DB::transaction(function () {
        // The inner transaction is not measured separately
        Inventory::reserve($product);
    });

    // Measurement ends here, and the callback runs if the threshold is exceeded
});
```

Laravel saves the start time only when the transaction level goes from `0` to `1`. So even when an inner transaction runs as a savepoint, its processing time is included in the elapsed time of the outer transaction. This mechanism does not let you monitor an inner transaction with its own threshold.

The callback runs after the transaction level returns to `0`. If the callback passed to `DB::transaction` throws an exception and the transaction rolls back, you still receive the `TransactionRolledBack` event and the measured time. The same events fire when you call `beginTransaction` / `commit` / `rollBack` manually.

## Specify the threshold

The first argument of `whenTransactionRunsLongerThan` accepts the following types.

| Value | Meaning |
| - | - |
| `int` or `float` | Milliseconds |
| `CarbonInterval` | Total milliseconds of the interval |
| `DateTimeInterface` | Seconds until the given time, converted to milliseconds |

Passing milliseconds directly is usually enough. If you prefer to express the threshold in time units, you can use `CarbonInterval`.

```php theme={null}
use Carbon\CarbonInterval;
use Illuminate\Support\Facades\DB;

DB::connection()->whenTransactionRunsLongerThan(
    CarbonInterval::seconds(1),
    static function (): void {
        // Record monitoring logs or metrics
    },
);
```

The check is whether the elapsed time is greater than the threshold. If the elapsed time equals the threshold, the callback is not called. Setting the threshold to `0` makes every measured transaction trigger the callback.

## Distinguish it from slow SQL

Laravel also provides `whenQueryingForLongerThan`, which monitors the cumulative time of the SQL executed within a single request. The two APIs measure different things.

| API | What it measures | Callback event |
| - | - | - |
| `whenQueryingForLongerThan` | Cumulative SQL execution time within the request | `QueryExecuted` |
| `whenTransactionRunsLongerThan` | Elapsed time from the start of the outer transaction to its commit or rollback | `TransactionCommitted` or `TransactionRolledBack` |

If a transaction calls an external API or waits on locks, its elapsed time can be longer than the cumulative SQL time. Recording both makes it easier to tell whether a delay comes from the SQL itself or from other work inside the transaction.

## Operational considerations

The callback runs during commit or rollback processing, so limit it to monitoring work. Logging and recording metrics are fine, but do not run additional writes on the same connection or perform slow external calls.

Calling an external API inside a transaction also adds its wait time to the measurement. Consider whether you can move external calls out of the transaction. This not only reduces alerts but also shortens how long locks are held.

## Primary sources

* [Laravel official database documentation](https://github.com/laravel/docs/blob/13.x/database.md)
* [`Connection::whenTransactionRunsLongerThan` implementation](https://github.com/laravel/framework/blob/13.x/src/Illuminate/Database/Connection.php)
* [Commit adding it to Laravel Framework](https://github.com/laravel/framework/commit/5edfeeed86961983042d0bdbbe7265d5b6dc7bba)


## Related topics

- [Advanced Topics](https://kawax.biz/en/advanced/index.md)
- [Database configuration](https://kawax.biz/en/database.md)
- [Database Testing](https://kawax.biz/en/database-testing.md)
- [Laravel Pennant](https://kawax.biz/en/pennant.md)
- [Handling migration failures with the MigrationFailed event](https://kawax.biz/en/advanced/migration-failed-event.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.