Laravel Queue Jobs for Third-Party APIs: Idempotency, Retries and Rate Limits
A queue job that calls someone else's API looks like three lines of code. In production it meets timeouts that leave you not knowing whether the call happened, rate limits that answer with a 429, outages that last ten minutes, and retries that quietly send the same request twice. The standard retry settings handle none of this on their own, and the usual consequence is a duplicate contact, a double charge or a job that retries forever.
This guide builds one job, SyncContactToCrm, that holds up against those failures: an idempotency record so repeats are harmless, rate limiting that works across workers, separate handling for rate limits, transient errors and permanent errors, and timeouts that fit together. The CRM is generic; the same structure suits payments, e-mail, messaging or any HTTP API.
What this covers, and what was tested
The code was run on Laravel 13 with PHP 8.3 and MySQL. There are 7 automated tests (20 assertions) using a faked HTTP layer. I also ran a real queue worker against a small fake API that returns 503 twice then 200, a 429 with Retry-After, a permanent 422, and a permanent 503. Whether a particular provider honours an Idempotency-Key header is provider-specific and comes from its documentation, not from this test. The examples target PHP 8.2+ and Laravel 11 or newer.
Five rules for jobs that call APIs
| Rule | Why |
|---|
| Make the operation idempotent | A retry after a timeout may repeat a request the API already processed. |
| Treat 429, 5xx and 4xx differently | Wait on a 429, retry a 5xx with backoff, and stop on a 4xx: the same request will fail again. |
| Rate limit across all workers | Ten workers each "politely" calling the API add up to a flood. |
| Count failures, not waiting | A job that waits for a rate limit is not failing, so it should not burn its retries. |
| Fit the timeouts together | HTTP timeout, then job timeout, then the queue's retry_after, each one longer than the last. |
Step 1: Record every logical operation
Give each logical operation, such as "sync contact 42 as of this version", a key, and store one row per key. The key describes the work, not the job: if the same work is dispatched twice, or the same job is delivered twice, both carry the same key. The job checks the row first, and the same key is sent to the API as an Idempotency-Key header for providers that support it, so a repeated request is recognised at their end too. The local row is the part you control.
database/migrations/..._create_api_operations_table.php (up)
Schema::create('api_operations', function (Blueprint $table) {
$table->id();
$table->string('key')->unique(); // one row per logical operation
$table->string('status', 20)->default('pending'); // pending, succeeded, failed
$table->json('response')->nullable();
$table->text('error')->nullable();
$table->timestamps();
});
app/Models/ApiOperation.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class ApiOperation extends Model
{
protected $fillable = ['key', 'status', 'response', 'error'];
protected function casts(): array
{
return ['response' => 'array'];
}
}
Step 2: One small client class
All knowledge of how to talk to the API lives in one place. It has a short connect timeout so an unreachable API fails fast, an overall timeout so a slow one cannot hold a worker forever, and it never retries on its own. A timeout does not tell you whether the API received the request, so retrying inside the HTTP client can repeat a request that worked. Retries belong in the job, where the idempotency record protects you.
app/Services/Crm/CrmClient.php
<?php
namespace App\Services\Crm;
use Illuminate\Http\Client\Response;
use Illuminate\Support\Facades\Http;
class CrmClient
{
public function upsertContact(array $contact, string $idempotencyKey): Response
{
return Http::baseUrl(rtrim(config('services.crm.base_url'), '/'))
->withToken((string) config('services.crm.token'))
->withHeaders(['Idempotency-Key' => $idempotencyKey])
->acceptJson()
->connectTimeout(3)
->timeout(10)
->put('/contacts/'.rawurlencode($contact['email']), $contact);
}
}
// config/services.php
'crm' => [
'base_url' => env('CRM_BASE_URL'),
'token' => env('CRM_TOKEN'),
// Seconds to wait after the 1st, 2nd, 3rd... exception.
'backoff' => array_map('intval', explode(',', (string) env('CRM_BACKOFF', '30,120,600'))),
],
Step 3: The job
The class properties and the three response branches carry the design, so it is worth reading slowly.
$tries = 25 with $maxExceptions = 3. Every release back to the queue, including a wait for a rate limit, uses up an attempt. A small $tries would kill a perfectly healthy job that was merely told to wait. $maxExceptions is the real limit: three genuine failures and the job is done.
backoff() spaces the retries after an exception. It reads from config so tests and slow environments can change it.
- Middleware.
RateLimited keeps all workers together under one limit. WithoutOverlapping stops two jobs for the same contact running at the same time, which is a common cause of out-of-order writes.
- A 429 releases the job for the seconds the API asked for (
Retry-After), with a sensible default if the header is missing.
- A 5xx throws, so the queue retries it after the backoff and counts it as an exception.
- A 4xx fails the job at once. A rejected request, such as an invalid email address, will be rejected again, and retrying only delays the alert.
failed() leaves an honest record when the queue gives up, and never overwrites a success.
app/Jobs/SyncContactToCrm.php
<?php
namespace App\Jobs;
use App\Models\ApiOperation;
use App\Services\Crm\CrmClient;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\Middleware\RateLimited;
use Illuminate\Queue\Middleware\WithoutOverlapping;
use Illuminate\Support\Str;
use RuntimeException;
use Throwable;
class SyncContactToCrm implements ShouldQueue
{
use Queueable;
// Rate-limit releases use up attempts, so allow many attempts...
public int $tries = 25;
// ...but give up after 3 real failures (exceptions). Releases do not count here.
public int $maxExceptions = 3;
public int $timeout = 30; // longer than the 10 s HTTP timeout, shorter than the queue's retry_after
/** @param array{email: string, name?: string} $contact */
public function __construct(public string $key, public array $contact) {}
/** @return array<int, int> seconds before each retry after an exception */
public function backoff(): array
{
return config('services.crm.backoff');
}
public function middleware(): array
{
return [
new RateLimited('crm-api'), // stay under the provider's limit across all workers
(new WithoutOverlapping($this->contact['email'])) // never two jobs for the same contact at once
->releaseAfter(30)
->expireAfter(120),
];
}
public function handle(CrmClient $crm): void
{
$operation = ApiOperation::firstOrCreate(['key' => $this->key]);
if ($operation->status === 'succeeded') {
return; // redelivered after success: do not call the API again
}
$response = $crm->upsertContact($this->contact, $this->key);
if ($response->status() === 429) {
$this->release((int) $response->header('Retry-After') ?: 60);
return;
}
if ($response->serverError()) {
$response->throw(); // transient: counts as an exception, retried after the backoff
}
if ($response->failed()) {
// 4xx: the same request will fail again, so stop retrying.
$message = "CRM rejected the contact (HTTP {$response->status()})";
$operation->update(['status' => 'failed', 'error' => $message]);
$this->fail(new RuntimeException($message));
return;
}
$operation->update(['status' => 'succeeded', 'response' => $response->json(), 'error' => null]);
}
/** Called once the queue has given up: leave an honest record of why. */
public function failed(Throwable $e): void
{
ApiOperation::where('key', $this->key)
->where('status', '!=', 'succeeded')
->update(['status' => 'failed', 'error' => Str::limit($e->getMessage(), 500)]);
}
}
Dispatch it with a key that describes the work:
SyncContactToCrm::dispatch(
key: "crm.contact:{$contact->id}:{$contact->updated_at->timestamp}",
contact: ['email' => $contact->email, 'name' => $contact->name],
);
Step 4: Define the rate limiter
The limiter is named in the job middleware and defined once, usually in AppServiceProvider::boot(). It counts in your cache store, so with several servers the cache must be shared (Redis or the database), or each server enforces its own limit.
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Support\Facades\RateLimiter;
RateLimiter::for('crm-api', fn () => Limit::perMinute((int) env('CRM_RATE_PER_MINUTE', 60)));
Set the number below the provider's documented limit, not at it. When the limiter is exhausted, jobs are released back to the queue instead of calling the API.
Step 5: Make the timeouts fit
| Setting | Value here | Rule |
|---|
| HTTP connect / total timeout | 3 s / 10 s | As short as the API can reasonably answer. |
Job $timeout | 30 s | Longer than the HTTP timeout, or the worker is killed before the client gives up. |
Queue retry_after | 90 s (the database queue default) | Longer than the job timeout, otherwise a slow job is handed to a second worker while the first is still running. |
| Backoff after an exception | 30 s, 120 s, 600 s | Long enough for a short outage to clear. Tune it to the API. |
| Cache store for locks and limits | Database or Redis | RateLimited and WithoutOverlapping need a store shared by every worker. |
Also remember that long-running workers hold the code and config they started with. After a deploy or an .env change, run php artisan queue:restart.
Testing: unit tests and a real worker
Laravel's fake queue interactions let you test what a job does with each response without running a worker. These seven tests lock in the behaviour above:
| Test | What it protects against |
|---|
| Sends the idempotency key and bearer token, and records success | A client that forgets the header |
| A second delivery of the same operation makes no second API call | Duplicate writes after a redelivery |
A 429 releases the job for the number of seconds in Retry-After | Hammering a rate-limited API |
| A 503 throws and leaves the operation pending | Silent failures that are never retried |
| A 422 fails the job permanently and records the reason | Retrying a request that can never succeed |
| The retry settings are what the article says they are | A silent change to tries, backoff or timeout |
failed() records why, and never overwrites a success | Hiding a success behind a late failure |
Unit tests do not prove that the queue itself behaves, so I also ran a real worker against a throwaway fake API (a PHP script run with php -S that returns the response you choose and logs every request). With a backoff of one second to keep the run short, the four scenarios behaved as follows:
| Fake API behaviour | What the worker did | Final state |
|---|
| 503, 503, then 200 | Three calls one second apart, all with the same Idempotency-Key | Operation succeeded; no failed jobs |
429 with Retry-After: 2, then 200 | Second call two seconds after the first; the wait was not counted as a failure | Operation succeeded; no failed jobs |
| 422 (rejected) | One call, no retries | Operation failed with the reason; one failed job |
| 503 on every call | Three calls, then gave up, even though $tries is 25 | Operation failed (after adding the failed() hook); one failed job |
The last row is the reason $maxExceptions matters: without it, an API that is down for a day would keep the job retrying until its 25 attempts ran out. In my first run of that scenario the operation was still marked pending after the job had given up, which is why the failed() hook exists.
Common mistakes
- Retrying inside the HTTP client (
->retry()) as well as in the job, which multiplies attempts and repeats requests.
- A small
$tries with a rate limiter, so healthy jobs run out of attempts while waiting.
- Treating every error alike, either retrying 4xx errors or giving up on a 503.
- Building the idempotency key from the job instance, for example a random id created in the constructor, so a redelivered job looks like new work.
- Rate limiting per worker instead of across workers.
- Storing response bodies and error text without a limit. An API error body can be long and can contain data you would rather not keep, so truncate it as the
failed() hook does.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|
| Job runs twice at the same time | Slow job redelivered because retry_after is shorter than the job | Raise retry_after above $timeout, or shorten the work. |
| Job fails after only a few waits | $tries is small and rate-limit releases use attempts | Raise $tries and rely on $maxExceptions for real failures. |
| Rate limit exceeded despite the limiter | Limiter counts per server, or the limit is higher than the provider allows | Use a shared cache and lower the number. |
| New config or code not applied to the queue | Workers hold the old version | Run php artisan queue:restart after every deploy or .env change. |
Operation stuck on pending | The job gave up before the failed() hook existed, or a worker was killed | Add the hook, and treat old pending rows as unknown: check the API before retrying. |
| Duplicate records at the provider | The provider ignores Idempotency-Key, or the key changes per attempt | Check the provider documentation. Build the key from the work, not the attempt. |
Frequently asked questions
Do I need both a database record and an Idempotency-Key header?
The record is the part you control and it works with every API. The header helps only where the provider supports it. Using both covers a retry from your side and a retry that crosses the network boundary.
Why not simply set $tries = 3?
Because a rate-limit release is not a failure. With three tries a job that was told to wait twice would be dead on the third pass. $maxExceptions counts the failures that matter.
What should I alert on?
Failed jobs, operations in failed, and operations that stay in pending longer than they should. Alert on a count over time, not on every single failure.
How do I retry a failed job?
php artisan queue:retry re-queues a failed job. Because the operation is idempotent, retrying is safe, but fix the cause first, or it will fail the same way.
Does this work for payments?
The structure does. For money, check how the provider handles idempotency keys and how long it remembers them, and confirm the outcome with the provider's API when it matters.
Where this fits
This is the part of an integration that rarely shows in a demo and decides whether it survives a bad day at the provider. If you are connecting your Laravel application to a CRM, a payment provider or any third-party API and want it to hold up, see API Integration & Custom Automation and Laravel & PHP Development, or describe your project here. More Laravel guides are collected under Laravel.