DEV Community

hbgl
hbgl

Posted on β€’ Edited on

Backend shorts - Use database transactions

Database transactions have many use cases, but in this post we will be only looking at the simplest and most common one: all or nothing semantics aka atomicity.

If you issue multiple related database queries that modify data (INSERT, UPDATE, DELETE), then you should most likely use a transaction. Here is a quick example using Laravel:

function submitOrder(Request $request)
{
    // ....

    $order = new Order($someOrderData);
    $payment = new Payment($somePaymentData);

    DB::transaction(function () use ($order, $payment) {
        $order->save();
        $payment->save();
    }

    // ...
}

Enter fullscreen mode Exit fullscreen mode

Maybe for a better understanding, here is what is going on:

function submitOrder(Request $request)
{
    // ....

    // YOU: Hey DB, I want to save a bunch of data.
    DB::transaction(function () {
        // DB: Ok, tell me everything you want to save.

        // YOU: This order right here.
        $order->save();

        // YOU: And this payment right there.
        $payment->save();

       // YOU: And that's all. Just those two.
    });
    // DB: Alright, order and payment have been saved.

    // ...
}

Enter fullscreen mode Exit fullscreen mode

By wrapping the save() calls in a DB::transaction, we make sure that either all models are saved or none of them. Or said differently, our data is always in a consistent state, which is one of the primary tasks of a backend developer. There will never be an order without a payment.

What could go wrong?

Let's play through the scenario in which we did not use a transaction. Say the order was successfully saved but just when calling $payment->save() the DB goes offline, or the PHP process times out, or it crashes, or the whole machine crashes. You now have an order without a payment, which is probably not something that your application was designed to handle correctly.

The consequences will depend on the exact circumstances, but it is not something that you want to get an angry phone call at 8pm on a Sunday for.

Image of Stellar post

Check out Episode 1: How a Hackathon Project Became a Web3 Startup πŸš€

Ever wondered what it takes to build a web3 startup from scratch? In the Stellar Dev Diaries series, we follow the journey of a team of developers building on the Stellar Network as they go from hackathon win to getting funded and launching on mainnet.

Read more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, β€œnot bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

πŸ‘‹ Kindness is contagious

DEV is better (more customized, reading settings like dark mode etc) when you're signed in!

Okay