You Don't Always Need a Workflow Engine to Roll Back a Failed Checkout
Here's a sequence that shows up in almost every Laravel app that talks to the outside world: Charge the customer's card. Create a policy (or order, or booking) with a partner API. Generate a PDF confirmation. Step 3 throws. Maybe the PDF library ran out of memory, maybe the storage disk is full. Whatever the reason, you're now sitting on a charged card and a partner-side record that your own…
When a checkout process in a Laravel application encounters an error, it can create a situation where a payment has been made, but the associated partner data has not been updated, leaving the system in an inconsistent state. The Saga pattern addresses this by modeling the operation as a series of steps, each with an execute() method to perform the action and a compensate() method to undo the action if the step fails.
By using this approach, if a step fails, the system can roll back the successful steps in reverse order, restoring the system to its original state.
The article highlights that creating a correct compensation step is more complicated than it seems. While there are existing solutions in Laravel, such as Durable Workflow and Saga, they offer additional features like long-running workflows, signals, and parallel branches, which may be unnecessary for simple scenarios like a payment followed by a policy creation and a PDF generation.
The author decided to implement a synchronous orchestrator with no queue, database, or migrations, where steps run within the same request and compensation happens before the response is sent back to the user.
The Compensator package, named after the compensating action, provides a simple API for defining steps and their compensations. Each step has an execute() function to perform the action and a compensate() function to undo it. If any compensation step fails, the result can be inspected to identify which steps failed and why. The author emphasizes the importance of handling compensation failures gracefully to avoid leaving unresolved side effects behind, and the package is designed to make this process straightforward.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.