Make a Laravel job safe to run twice
A failed job may have already done some of its work. Here's how I decide what a Laravel queue worker can safely try again.
When I design a queued job, I assume the worker can stop between any two lines. That matters most at the point where the job changes something outside the app. A timeout while calling an email provider, for example, leaves a question behind. Did the provider reject the request, or did it accept the message before the response got lost?
Give the operation its own identity
For an invoice email, I’d identify the operation by the invoice and the purpose of the message. A retry should use the same identity. An intentional resend should create a new one. That gives the application a way to tell the difference between recovering from a failure and doing something the customer explicitly asked for.
When the provider supports idempotency keys, I’d send that same key on each retry. I’d also keep a delivery record with the provider’s response or message ID when available. A local record alone cannot prove what happened if the provider accepted a request and the worker stopped before saving the result.
Wait for the data the job needs
If an invoice and its job are created inside the same database transaction, the worker needs a committed invoice to read. Laravel supports that directly when dispatching the job.
SendInvoiceEmail::dispatch($invoice->id)->afterCommit();
That controls when the job is dispatched. The job still needs its own rules for retries.
Decide what to do when the outcome is unclear
I’d retry an outcome the provider explicitly marks as temporary. If the send might already have happened and the provider cannot deduplicate or confirm it, I’d mark the delivery as uncertain so someone can check it. After an interruption, I want enough evidence to decide whether it is safe to try again.