Laravel 13.40 landed on November 3, 2026 with two features that solve long-standing operational blind spots: slow job/task alerts and precise read-replica sync detection. Both arrive as first-party APIs you can drop into existing applications without redesigning your queue or database layer.
Slow Job and Task Alerts
Production queues and schedulers tend to fail quietly. A job that usually finishes in two seconds starts taking ninety; a nightly report that ran in three minutes now runs for forty-five. You find out when customers complain or the cron output lands in an inbox nobody reads.
Laravel 13.40 adds two symmetrical methods: Queue::whenJobRunsLongerThan() and Schedule::whenTaskRunsLongerThan(). Each registers a callback that fires when an execution exceeds a threshold you define.
Queue::whenJobRunsLongerThan
The method lives on the QueueManager, so it applies to every configured connection. It hooks into the existing JobAttempted event, which means it catches successful attempts, failed attempts, and released attempts — anything that increments the attempt count.
use Carbon\CarbonInterval;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\Facades\Log;
Queue::whenJobRunsLongerThan(CarbonInterval::seconds(90), function ($job, int $durationMs) {
Log::warning("Slow job detected", [
'job' => $job->resolveName(),
'duration_ms' => $durationMs,
'attempt' => $job->attempts(),
'queue' => $job->getQueue(),
]);
});
The threshold accepts a CarbonInterval, a DateTime, or an integer (interpreted as milliseconds). The callback receives the job instance and the measured duration in milliseconds. This mirrors the signature of Connection::whenQueryingForLongerThan() introduced earlier for slow query detection.
Common use cases:
- Alert when a job approaches its timeout (default 60s, often extended for batch work)
- Detect jobs that would benefit from a dedicated Pro worker or a separate queue
- Correlate slow jobs with deployments or dependency upgrades
Because the listener runs after the attempt finishes, it adds no latency to the job itself. The overhead is a single event dispatch and your callback.
Schedule::whenTaskRunsLongerThan
The scheduler counterpart works the same way but measures in seconds and receives the ScheduledTaskEvent (the same object you get in after/onSuccess/onFailure callbacks) plus the runtime as a float.
use Carbon\CarbonInterval;
use Illuminate\Console\Scheduling\Event;
use Illuminate\Support\Facades\Schedule;
use Illuminate\Support\Facades\Log;
Schedule::whenTaskRunsLongerThan(CarbonInterval::minutes(45), function (Event $task, float $runtime) {
Log::warning("Slow scheduled task", [
'summary' => $task->getSummaryForDisplay(),
'runtime_seconds' => $runtime,
'expression' => $task->expression,
]);
});
Register this in a service provider's boot() method (typically AppServiceProvider or a dedicated ScheduleServiceProvider). The callback fires on both ScheduledTaskFinished and ScheduledTaskFailed events, so you catch overruns regardless of exit status.
This is particularly valuable for:
- Long-running report generation or data exports
- Cleanup tasks that grow with data volume
- Third-party API syncs where latency varies
Replica Commit IDs: Precise Read-After-Write Consistency
Since Laravel 13.38, PreventStaleDatabaseReads middleware has offered a fixed-time window (default 2 seconds) to route reads to the primary after a write. That works, but it's blunt: two seconds is too long for a local replica, too short for a cross-region one, and it doesn't actually know whether the replica has caught up.
Laravel 13.40 introduces three methods on the Connection class (MySQL, MariaDB, PostgreSQL drivers) that let you verify replication progress at the commit level.
The API
// On the primary connection, after a write
$lastCommitId = DB::connection('mysql-write')->getLastCommitId();
// On a replica connection, before dependent reads
$caughtUp = DB::connection('mysql-read')->hasCommitId($lastCommitId); // instant check
$caughtUp = DB::connection('mysql-read')->hasCommitId($lastCommitId, wait: 2); // wait up to 2 seconds
// For multi-source replication (e.g., multiple primaries)
$mergedId = DB::connection('mysql-read')->mergeCommitIds([$id1, $id2]);
| Method | Runs on | Returns |
|---|---|---|
getLastCommitId() |
Primary/write | Commit token (GTID/LSN) |
hasCommitId($id, $wait?) |
Read replica | bool — whether the replica has applied that commit |
mergeCommitIds($ids) |
Any | Combined token for multi-source setups |
Driver Support
- MySQL: GTID mode must be
ON. Returns the GTID set after the write. - MariaDB: Binary logging must be enabled. Uses MariaDB's GTID implementation.
- PostgreSQL: Uses WAL LSNs via
pg_current_wal_insert_lsn(). Thewaitparameter requires PostgreSQL 19+ (earlier versions throwRuntimeException). - SQLite / SQL Server: Throw
RuntimeException— not supported.
Practical Pattern: Session-Backed Verification
The most ergonomic pattern stores the commit ID in the session after a write, then verifies on the next request before reading from the replica. This avoids a round-trip to the primary on every request.
// OrderController.php
public function store(StoreOrderRequest $request)
{
$order = $request->user()->orders()->create($request->validated());
// Capture the commit ID on the primary
$commitId = DB::connection('mysql-write')->getLastCommitId();
// Store for the next request
$request->session()->put('last_write_commit_id', $commitId);
return redirect()->route('orders.show', $order);
}
// OrderController.php (show method)
public function show(Request $request, Order $order)
{
$readDb = DB::connection('mysql-read');
$commitId = $request->session()->pull('last_write_commit_id');
if ($commitId) {
// Wait up to 1 second for replica to catch up
$readDb->hasCommitId($commitId, wait: 1);
}
// Now safe to read from replica
$order->load(['items', 'payments']);
return view('orders.show', compact('order'));
}
Wrap the check and the dependent reads in withPinnedSession() if you need to guarantee the same replica connection handles both:
$readDb->withPinnedSession(function ($db) use ($commitId) {
$db->hasCommitId($commitId, wait: 2);
return $db->table('orders')->where('user_id', auth()->id())->get();
});
Why This Beats Fixed Windows
- Local replicas (same AZ): typically catch up in <10ms. Fixed 2s window wastes 1990ms per request.
- Cross-region replicas (US-EAST → EU-WEST): may need 100–500ms. Fixed window either fails (too short) or adds unnecessary latency (too long).
- Multi-source replication:
mergeCommitIds()lets you wait for all upstream primaries before reading. - No primary contact on read path: after the initial write, the replica check is purely local to the read connection.
When to Use What
| Scenario | Tool |
|---|---|
| Detect jobs creeping toward timeout | Queue::whenJobRunsLongerThan() |
| Alert on scheduled tasks that grow over time | Schedule::whenTaskRunsLongerThan() |
| Read-after-write on local replica (sub-ms lag) | hasCommitId($id) without wait |
| Read-after-write on cross-region replica | hasCommitId($id, wait: N) |
| Multi-primary replication topologies | mergeCommitIds([...]) + hasCommitId() |
| Simple apps without replica lag concerns | PreventStaleDatabaseReads middleware (13.38) |
Gotchas
whenJobRunsLongerThanthresholds are milliseconds;whenTaskRunsLongerThanthresholds are seconds (viaCarbonInterval). Don't mix them up.- The job callback fires after the attempt. It won't help you kill a running job — only observe and alert.
- Commit IDs are driver-specific tokens. Don't serialize them across driver types (e.g., MySQL GTID → PostgreSQL LSN).
- PostgreSQL
waitrequires v19+. On older versions, catch theRuntimeExceptionand fall back to polling or the middleware. mergeCommitIds()is only meaningful if your read replica actually replicates from multiple primaries. For single-primary setups, it's a no-op wrapper.
Takeaway
Laravel 13.40 gives you surgical tools for two problems that previously required custom event listeners, external monitoring, or blunt middleware. Slow job/task alerts let you catch performance regressions the deploy after they appear. Replica commit IDs let you read from replicas with confidence, not hope. Both are opt-in, zero-dependency, and backward compatible — drop them in where you need them.
Sources
- Laravel 13.40 release: Laravel News (Nov 3, 2026)
Queue::whenJobRunsLongerThanPR: #62141Schedule::whenTaskRunsLongerThanPR: #62233- Replica commit IDs PR: #62198
- Laravel Framework CHANGELOG: 13.x