Explore Library
Code Quiz

Transaction Across Pool Connections

Spot why this money-transfer transaction fails to be atomic despite BEGIN and COMMIT.

Codejavascript
const { Pool } = require('pg');
const pool = new Pool();

async function transfer(from, to, amount) {
  try {
    await pool.query('BEGIN');
    await pool.query(
      'UPDATE accounts SET balance = balance - $1 WHERE id = $2',
      [amount, from]
    );
    await pool.query(
      'UPDATE accounts SET balance = balance + $1 WHERE id = $2',
      [amount, to]
    );
    await pool.query('COMMIT');
  } catch (err) {
    await pool.query('ROLLBACK');
    throw err;
  }
}

What is the bug that breaks atomicity in this transaction?