DEV Community

Cover image for Laravel RateLimited Jobs: Waiting in Line Burns Your $tries
Ivan Mykhavko
Ivan Mykhavko

Posted on

Laravel RateLimited Jobs: Waiting in Line Burns Your $tries

Our price mails started failing with MaxAttemptsExceededException, and the job had never thrown anything. It was just waiting in line.

The job had public int $tries = 3 and a RateLimited middleware. I read that as "try to send this mail three times". Laravel reads it as "pick this job up three times". And waiting for a free slot in the rate limiter counts as a pickup.

The Problem

The project I work on sends price lists to clients by email. A client picks one or more send hours. Every two hours, at :15, a dispatcher queues the mails for the next hour: 07:00, 09:00 and so on, up to 19:00. withDelay() holds each mail until its hour. The notification looked like this:

final class PriceExportNotification extends Notification implements ShouldQueue
{
    use InteractsWithQueue;
    use Queueable;

    public int $tries = 3;

    public function backoff(): array
    {
        return [5, 15, 30];
    }

    public function middleware(): array
    {
        return [new RateLimited(LimiterName::MAIL->value)];
    }

    public function failed(): void
    {
        PriceExport::query()->whereKey($this->priceExportDTO->priceExportId)->update(['is_send' => false]);
    }

    // __construct(), via(), withDelay(), toMail() ...
}
Enter fullscreen mode Exit fullscreen mode

And the limiter, in AppServiceProvider:

RateLimiter::for(LimiterName::MAIL->value, fn() => Limit::perHour(100));
Enter fullscreen mode Exit fullscreen mode

Looks safe. Three tries, a backoff, a limit so we don't flood the mail provider. But some send hours, like 07:00, carry a lot of mails. When more mails were queued for an hour than the limiter let through, the ones at the back of the line ended up in failed_jobs. No mail error, no exception from toMail(). Just MaxAttemptsExceededException, and failed() marked the export as not sent.

Why a Release Is an Attempt

When the limit is hit, RateLimited does not fail the job. It calls $job->release() and puts the job back on the queue until the limiter window opens again. With perHour(), that means the job comes back when the hour resets.

The problem is how the worker counts attempts. Every time it picks a job up, the attempt counter goes up by one. It doesn't matter whether handle() ran or the middleware released the job before that. Before running the job, Worker::markJobAsFailedIfAlreadyExceedsMaxAttempts() checks the counter:

$maxTries = ! is_null($job->maxTries()) ? $job->maxTries() : $maxTries;

$retryUntil = $job->retryUntil();

if ($retryUntil && Carbon::now()->getTimestamp() <= $retryUntil) {
    return;
}

if (! $retryUntil && ($maxTries === 0 || $job->attempts() <= $maxTries)) {
    return;
}

$this->failJob($job, $e = $this->maxAttemptsExceededException($job));
Enter fullscreen mode Exit fullscreen mode

So a job that was released three times is dead on its fourth pickup, before it does anything. And backoff() doesn't apply to a release: it only spaces out retries after an exception. A release waits as long as the limiter says.

WithoutOverlapping works the same way. By default it releases the job when the lock is taken, and that pickup counts too.

The Laravel docs do say this, in one paragraph under Rate Limiting:

Releasing a rate limited job back onto the queue will still increment the job's total number of attempts.

Easy to miss. So I checked it in a sandbox: Laravel 12.43.1, database queue. The worker code above is the same in 11.x (our production) and 13.x. Five jobs, Limit::perHour(1), $tries = 3. I moved the clock one hour between worker runs. Each line is the job number, the time it was sent and its attempt:

1@07:00 attempt 1
2@08:01 attempt 2
3@09:02 attempt 3
tries    sent=3 failed=2 {"Illuminate\\Queue\\MaxAttemptsExceededException":2}
Enter fullscreen mode Exit fullscreen mode

Jobs 4 and 5 never ran handle(). They waited three times and then failed.

Attempts, Exceptions or a Deadline

Laravel has three limits here, and each one counts something else:

Setting What it counts Good for
$tries Every pickup, releases included Jobs that are never released
$maxExceptions Only unhandled exceptions "Stop if it's really broken"
retryUntil() Wall-clock time "Stop when it's too late to matter"

For a job that gets released, $tries is the wrong tool. A bigger number only moves the problem: on a busy day the line gets longer and you hit the new cap too. And $tries = 0 (unlimited) also removes the cap on real errors, so a broken mail would retry forever.

If a skipped run is fine for you, there's one more option: (new RateLimited(...))->dontRelease() drops the job instead of putting it back. For a price mail it isn't fine.

When does this mail stop being useful? For us that's easy. The dispatcher runs every 2 hours, and a client can have two send hours in a row, say 07:00 and 09:00. If the 07:00 mail is late, it must not land after the 09:00 mail with a newer price. We gave it one hour.

Heads up: if retryUntil() is set, the worker ignores $tries completely (since Laravel 8, PR #35214). Look at the first if in the worker code: with a deadline, only the time matters. So you can't mix "until 08:00, but max 3 times". The attempt cap moves to $maxExceptions.

The Fix

// BEFORE
public int $tries = 3;

// AFTER
// A RateLimited release counts as an attempt, so cap real exceptions, not attempts.
public int $maxExceptions = 3;

// Until 1 h past the send hour: schedules repeat every 2 h, so a late mail must not land after the next price.
public function retryUntil(): CarbonInterface
{
    return $this->sendHourStart()->addHour();
}

private function sendHourStart(): CarbonInterface
{
    return Date::now()->setHour($this->priceExportDTO->hourSend)->startOfHour();
}
Enter fullscreen mode Exit fullscreen mode

Now a 07:00 mail can wait in line as long as it needs, until 08:00. If toMail() throws three times, it fails. If 08:00 passes, it fails too, and that's fine for us: the next scheduled price mail carries the fresh price anyway.

Heads up: Laravel calls retryUntil() once, at dispatch, and stores the timestamp in the job payload. Our dispatcher runs between 06:15 and 18:15, so Date::now()->setHour() always lands on the right day. If your send hour can be after midnight, build the deadline from the real send time.

The same sandbox run with $maxExceptions = 3 and a deadline 10 hours ahead, so all five fit:

1@07:00 attempt 1
2@08:01 attempt 2
3@09:02 attempt 3
4@10:03 attempt 4
5@11:04 attempt 5
deadline sent=5 failed=0 []
Enter fullscreen mode Exit fullscreen mode

All five sent. Job 5 went out on attempt 5, which $tries = 3 would never allow.

One more check: this is a notification, not a job. Laravel wraps a queued notification in SendQueuedNotifications. The wrapper copies tries and maxExceptions from the notification and forwards retryUntil() to it. So the test asserts on the wrapper, because the wrapper is what the worker sees (the test uses 08:00, the rule is the same):

public function test_price_export_notification_retries_by_deadline_not_by_attempt_count(): void
{
    // The dispatcher runs at :15 and schedules the mail for the next hour.
    Date::setTestNow('2026-11-02 07:15:00');

    $notification = new PriceExportNotification(new PriceExportDTO(userId: 1, supplierId: 1, priceExportId: 1, isAuto: true, hourSend: 8));
    $job = new SendQueuedNotifications(new Collection(), $notification, ['mail']);

    $this->assertNull($job->tries);
    $this->assertSame(3, $job->maxExceptions);
    // Deadline 09:00, one hour before a 10:00 schedule of the same client could send a newer price.
    $this->assertEquals(Date::parse('2026-11-02 09:00:00'), $job->retryUntil());
}
Enter fullscreen mode Exit fullscreen mode

The Limit Nobody Re-checked

While fixing this, I asked a different question: why 100 per hour at all?

Turns out that number came from Mailgun's 100/h limit for evaluation accounts. Mailgun lifted it for our account back in 2024. Our limiter kept throttling mails against a cap that didn't exist anymore.

// Our own brake: Mailgun lifted its 100/h evaluation cap in 2024.
RateLimiter::for(LimiterName::MAIL->value, fn() => Limit::perHour(1000));
Enter fullscreen mode Exit fullscreen mode

I kept a limiter, because a bug that queues thousands of mails should still get stopped. But now it's our own brake, with a comment that says so. The deadline fix still matters: a backlog after an outage can fill the line at 1000/h too. If you copy a limit from a provider, re-check it now and then. Theirs change.

TL;DR

  • With RateLimited and WithoutOverlapping, every release means one more pickup, and every pickup counts as an attempt. $tries = 3 means "wait in line 3 times, then fail".
  • backoff() doesn't apply to releases, only to exceptions.
  • Use $maxExceptions for "it's really broken" and retryUntil() for "it's too late to matter". With retryUntil() set, $tries is ignored.
  • If a skipped run is fine, RateLimited(...)->dontRelease() drops the job instead of re-queuing it.
  • For a queued notification, test SendQueuedNotifications: that's what the worker sees.
  • Check where your rate limit number came from. Ours had been out of date since 2024.

💡 For us, "when is this mail useless?" had a clear answer. Ask it before you pick a number for $tries.


Author's Note

Thanks for sticking around!
Find me on dev.to, linkedin, or you can check out my work on github.

Laravel, after the happy path.

Top comments (0)