Short-lived database transactions

We all know that database transactions ensure that data is only persisted if all write queries are successfully executed. Otherwise, the entire operation is automatically rolled back. This is super helpful, and I believe we all rely or relied on this feature forever!

But transactions have trade-offs. The engine will lock either entire tables, or rows, depending on the operations being made. And depending on the type of locks, even read queries will wait for the transaction to be completed to gain access to the data. This can accumulate, in a busy enough service or domain, and can become a performance bottleneck.

So be very careful about operations that could make those transactions opened for an extended period of time. As a rule of thumb, we should open transactions as close as possible of the write operations and close them as soon as the work is done. This is to lower the possibilities of extending those locks for too long.