2 min read

Laravel Tips : Retrying Failed Jobs in Specific Conditions

Laravel Tips : Retrying Failed Jobs in Specific Conditions
Photo by Praveen Thirumurugan / Unsplash

When working with Laravel queues, it’s common to encounter jobs that fail due to network hiccups, external API timeouts, or temporary database locks. Instead of manually retrying each job or retrying all failed jobs blindly, you can create a strategy to retry only the jobs that meet certain conditions.

1. Using the queue:retry Command

Laravel provides a built-in command:

php artisan queue:retry {id}

You can specify a single job ID or multiple IDs. To retry all failed jobs:

php artisan queue:retry all

But in real scenarios, you may only want to retry jobs of a specific type or those that failed under certain conditions.

2. Querying Failed Jobs

Failed jobs are stored in the failed_jobs table. You can query this table to filter which jobs should be retried.

3. Retrying Jobs Programmatically

Once you have the filtered jobs, you can loop through and retry them using Laravel’s queue system:

You can wrap this into a custom Artisan command (e.g., php artisan queue:retry-timeouts) to streamline the process.

4. Advanced Example: Retry Based on Payload

Sometimes, you may want to retry jobs not just by exception type, but by inspecting their payload. For instance, retry only failed jobs related to a specific order ID:

This allows very fine-grained control over which jobs you bring back to the queue.

5. Retrying Failed Jobs via Bash Script

For large-scale retries, you can also use a Bash + MySQL query approach. This is helpful if you want to retry jobs in bulk without writing additional PHP code.

Example script:

  • source .env loads your Laravel environment variables.
  • The MySQL query fetches the last 10,000 failed jobs (by uuid).
  • The loop calls php artisan queue:retry for each failed job ID.
  • The outer loop (for j in {1..10}) retries multiple times to catch jobs that may still fail intermittently.

This method is simple, effective, and works well for large-scale retries in production environments.


Conclusion

Instead of retrying all failed jobs, Laravel makes it possible to selectively retry jobs based on exception type, job payload, or even using direct database queries in Bash. By combining database queries with the queue:retry command, you gain more control over how and when your jobs are retried—keeping your queues efficient and avoiding unnecessary processing.