Run multiple/batch jobs with transaction rollback on fail and commit on complete

Posted 4 months ago by lambooni

My scenario is in relation to a large order that needs to be cancelled.

  • The order contains 200 different item lines i.e. orderItems.
  • Each line of the order is cancelled and triggers a calculation of stock and subsequent movement of stock.
  • When all order lines have been successfully, the order status can be updated to "cancelled".

For a few lines of an order this operation can be done synchronously, no problem. When orders are large then the processing power required means that my best option it to split the process down into separate operations within a queue.

i.e.

Run job

OrderController.php

CancelOrder::dispatch($order);

Jobs/CancelOrder.php handle()

$this->order->orderItems()->each(function(OrderItem $orderItem){
    CancelAndReallocateOrderItem::dispatch($orderItem, $this->user);
});

Jobs/CancelAndReallocateOrderItem.php handle()

$this->orderItem->cancelAllocatedAndReservedStock();
$this->orderItem->product->reAllocateOrderItems();

For this order with 200 lines, 200 instances of CancelAndReallocateOrderItem will be started, allowing the cancellation to process in a couple of minutes.

I am now trying to work out if its possible to:

  1. If any of the child jobs throw an error, can I rollback the entire batch of transactions.
  2. When all child jobs have completed successfully, how can I run some some final code (i.e. send notification, change order status etc.)

Please sign in or create an account to participate in this conversation.