4.4 Autocommit and Common Misunderstandings
Sometimes queries are run directly without opening a transaction with the BEGIN command. Since no transaction was created, it may seem that ACID is not kept. On closer inspection, however, every change operation in a database runs through a transaction. For reads, the database may optimize by not creating a transaction, but it still guarantees read consistency by referring to the point in time of the query. If you did not use BEGIN, the database executes an invisible BEGIN and COMMIT around each statement. This behavior is called autocommit.
In autocommit mode, if you send the two UPDATE statements of a transfer separately, the first UPDATE is committed the moment it finishes. Even if the second fails, the first cannot be undone. That is, unless you explicitly start a transaction, one transaction is implicitly created per query. In this case, if the second update hits a constraint violation after the first update and cannot complete, the accident of 100,000 won disappearing can occur even without a server failure. If several changes must be grouped as one, you must start a transaction explicitly.
Connection pools and transaction leaks. In practice, transactions are sometimes left open for a long time without ending. The most common cause is the code, not the user. Most applications do not open a new database connection every time; they borrow one from a connection pool and return it. If a transaction is started on a connection with autocommit off, an exception occurs, and the connection is released without going through either COMMIT or ROLLBACK, the transaction remains open on that connection. The pool lends that connection to another request, and the next session ends up working inside a transaction it does not know about. A transaction leaked this way stays in the "idle in transaction" state for hours and holds all three resources described in the next section. There are three countermeasures: always ROLLBACK on the exception path, configure the pool to clean up open transactions when it takes a connection back, and set the database to forcibly terminate transactions that stay idle beyond a certain time (such as PostgreSQL's idle_in_transaction_session_timeout).