Skip to content

Reconnect the database after any failed worker cycle - #170

Merged
LauJosefsen merged 1 commit into
masterfrom
lejo/reconnect-after-failed-worker-cycle
Aug 6, 2026
Merged

Reconnect the database after any failed worker cycle#170
LauJosefsen merged 1 commit into
masterfrom
lejo/reconnect-after-failed-worker-cycle

Conversation

@LauJosefsen

Copy link
Copy Markdown
Contributor

The worker only reconnected when a cycle failed because of a lost database connection. Any other failure left the connection in place, which is not always safe to do.

A transaction that is aborted by a connection dying mid-flight makes Laravel roll back, and that rollback fails too, because there is nothing left to talk to. handleRollBackException() then resets transactions to 0 while keeping the PDO instance, so the connection believes it has no transaction open, but the driver still believes it has: rollBack() only clears that flag when it succeeds, and it can never succeed again on a dead socket.

From there the connection is permanently unusable. beginTransaction() sees transactions === 0, reconnectIfMissingConnection() does nothing because the PDO instance is not null, and the driver rejects the BEGIN before it even reaches the network:

PDOException: There is already an active transaction

That message is not in the lost connection list, so the worker logged it and carried straight on to the next cycle with the same broken connection, failing every cycle at ~10 errors per second until the process was restarted by hand.

Giving up on the connection after any failed cycle covers this, and everything else where a failure leaves state behind that the connection cannot clear itself. The reconnect is cheap next to the 100 ms the worker already sleeps after a failed cycle, and the existing logging policy is unchanged: lost connections stay quiet until they start repeating, anything else is still reported in full.

A failed cycle can leave the connection in a state it never recovers from on
its own. When a transaction is aborted and the rollback that follows also
fails, the connection throws away its own transaction bookkeeping while the
driver keeps considering a transaction open. Every later attempt to begin one
is then rejected by the driver with "There is already an active transaction",
which is not a lost connection, so the worker held on to the connection and
failed every single cycle until it was restarted by hand.
@LauJosefsen LauJosefsen self-assigned this Aug 6, 2026
@LauJosefsen
LauJosefsen merged commit d8a4aac into master Aug 6, 2026
4 checks passed
@LauJosefsen
LauJosefsen deleted the lejo/reconnect-after-failed-worker-cycle branch August 6, 2026 07:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

2 participants