Why I put payments on a queue
A slow payment provider shouldn't freeze your whole order flow. The setup I use with Horizon, idempotency keys and a retry strategy.
On the first evening of the November sales, the payment provider's response time went from 300 milliseconds to 9 seconds. Because the charge happened synchronously inside the controller, PHP workers filled up one by one and the site stopped responding, even for visitors who weren't paying.
Since that night my rule is simple: no request to an external service makes the user's request wait.
How the flow changed
- When the user clicks "Pay", the order is saved with a
payment_pendingstatus. - A
ChargeOrderjob is queued and the user is sent straight to a waiting screen. - The job attempts the charge; when the result arrives, the order is updated and the screen refreshes itself.
ChargeOrder::dispatch($order)->onQueue('payments');
Never charge twice
Queues run jobs "at least once", so a job can occasionally run twice. That's why every charge request gets a fixed key tied to the order:
$response = $gateway->charge(
amount: $order->total,
conversationId: 'order-'.$order->id,
);
The provider treats a second request with the same key as a repeat of the first, not as a new charge. Inside the job I also check that the order is still payment_pending before charging.
Retry strategy
public $tries = 5;
public function backoff(): array
{
return [10, 30, 90, 300];
}
Network errors and timeouts are retried at growing intervals. Permanent failures like a declined card stop immediately and show the user a clear message. Retrying every error would mean trying to charge a declined card five times.
Visibility with Horizon
The payments queue runs in its own process, independent of everything else. Even if emails pile up, payments don't wait. In Horizon I can retry failed jobs with a single click.
The result
On the next campaign night the provider slowed down again. This time the site stayed up, payments completed with a few seconds' delay and not a single double charge happened.