Let’s say you have a Create Order API. The first thing you will do is store the order in the orders table in your database, then store the products of that order in a separate table, order_products table for example. However, things don’t always go as planned. At some point, an error might occur when storing the products of this order—perhaps due to database constraints, network issues, or a problem with the data itself.

The issue here is that, in case of an error, you will see that the order is stored, but the products are not. This could lead to an inconsistency in your database, where you have an order record without corresponding products, which is not ideal.

This is where transaction comes into play. It ensures that a sequence of codes either completes successfully or, if any part of the code fails, the entire sequence is rolled back. This means that if you store the order and then attempt to store the products, but an error occurs while inserting the products, the order record will be rolled back (deleted) as well. keeping your database in a consistent state.

continue reading on medium.com

⚠️ This post links to an external website. ⚠️