Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

GodziLaravel's avatar

Solving API Rate Limit Issues with Job Delay in Laravel

Hey fellow Laravel!

I've been working on a project where I need to generate jobs in a loop, but I've encountered a common problem:

API rate limits. Every time I dispatch a job that calls an external API, I run into the dreaded "too many requests" error from the API server.

To tackle this issue, I thought about adding a delay between each job. My initial idea was to use the loop index and delay each job by a certain amount of time. However, I faced a challenge when dealing with nested jobs – the loop index kept resetting to zero.

Here's a snippet of what I've been working on:

foreach ($milestones as $index => $milestone) {
    ProjectMilestones::dispatch($milestone['id'])
        ->onQueue('teamleader')
        ->delay(now()->addSeconds($index * 50));
}

$index log :

			0
			1
			2
			3
			4
			5
			6
			0
			1
			2
			0
			1
			2
			3
			6
			5
			4
			7

As you can see, the $index variable resets to zero when logging it within the loop of another job. This inconsistency in index values prevents me from implementing a consistent delay between jobs.

So, my question is: Is it possible in Laravel to make a delay dependent on the previous job's completion time?

I'd appreciate any insights or suggestions on how to solve this issue effectively. Let's brainstorm together!

Thanks,

0 likes
1 reply
Snapey's avatar

delay will not work unless it is very large because when jobs get delayed they ultimately reach the delay time before they have had chance to run, and so run immediately. If the queue is seriously delayed by some other long running job then lots of these jobs might all be past their delay time and then all run together.

Its a little clumsy but you could have a delay built into your job so that the worker cannot pick up a job until the first has finished executing. Then just queue all your jobs with no delay.

You would need a different solution though if you have multiple queue workers.

1 like

Please or to participate in this conversation.