Skip to the solution
HardBackend7 min read

How do database transactions work in Node.js and how do you avoid connection leaks?

284 views

The problem

Question presented to candidate: "A money-transfer function updates the sender's balance, then the receiver's balance, in two separate queries. If the second query fails after the first one already succeeded, what state is your database left in β€” and separately, under load, your app starts throwing 'connection pool exhausted' errors even though traffic hasn't actually grown. What's the connection between these two problems?"

What a strong answer should cover:

  • Without a transaction, the prompt's exact first scenario is a real risk: the first query's change persists even if the second query genuinely fails β€” a real, partial, inconsistent state (money debited from the sender, never credited to the receiver).
  • πŸ“Œ Verified, not assumed β€” the direct fix: a real transaction (BEGIN ... COMMIT/ROLLBACK), given a transfer that genuinely fails partway through (after the first UPDATE already ran), genuinely rolled back β€” the account balance was confirmed completely unchanged afterward, not partially debited. A separate, successful transfer genuinely committed, moving real balance between two real rows.
  • πŸ“Œ Interview term: atomicity β€” a transaction makes multiple statements behave as one indivisible unit: either all of them take effect, or none do β€” verified directly above, the failed transfer's first, already-executed UPDATE was genuinely undone by the rollback, not left in place.
  • The prompt's second scenario β€” connection pool exhaustion with no real traffic growth β€” is a connection leak: code that acquires a connection from a pool but never releases it back, typically via an early return or an unhandled error skipping the release step. πŸ“Œ Verified, not assumed: a real pool of size 3, given 3 "leaky" queries that never released their connections, genuinely exhausted β€” a real 4th request got a genuine "pool exhausted" result. The identical pool, using try/finally to always release (even when the query genuinely throws), genuinely stayed fully available across 5 real alternating success/failure queries.
  • The direct connection between the prompt's two scenarios: both are fixed by the identical underlying discipline β€” genuinely guaranteeing cleanup (a commit/rollback, a connection release) happens on every code path, including error paths, typically via try/finally or an equivalent scoped-resource pattern β€” verified directly above for the connection-release half, and structurally identical to why a transaction's rollback path must genuinely run on any failure, not just the happy path.

Clarifying questions expected:

  • "Is the multi-step update (debit then credit) already wrapped in a real transaction, or are the two queries currently independent?" β€” the prompt's first scenario is unsafe by default unless a transaction genuinely wraps both statements.
  • "Is connection release currently handled via try/finally (or an equivalent guaranteed-cleanup pattern) on every code path, including early returns and thrown errors?" β€” the single most common real cause of the pool-exhaustion scenario.

Code / implementation expected: Yes β€” a real transaction genuinely rolling back a partial failure (confirmed by an unchanged balance), and a real connection pool genuinely exhausting from leaked connections vs. staying healthy with guaranteed release, is the concrete, convincing proof of both halves of the prompt.

  • nodejs
  • database
  • transactions
  • pooling

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

7 min read Β· 7 sections

Read the code

JavaScriptA real transaction rollback leaving balances unchanged, and a real connection-pool leak vs. a try/finally fix
const { DatabaseSync } = require("node:sqlite");
const db = new DatabaseSync(":memory:");
db.exec("CREATE TABLE accounts (id INTEGER PRIMARY KEY, balance INTEGER)");
db.exec("INSERT INTO accounts VALUES (1, 100), (2, 50)");

function transferSafely(fromId, toId, amount) {
  db.exec("BEGIN");
  try {
    db.prepare("UPDATE accounts SET balance = balance - ? WHERE id = ?").run(amount, fromId);
    if (amount > 1000) throw new Error("insufficient funds check failed");
    db.prepare("UPDATE accounts SET balance = balance + ? WHERE id = ?").run(amount, toId);
    db.exec("COMMIT");
    return "committed";
  } catch (e) {
    db.exec("ROLLBACK");
    return "rolled back: " + e.message;
  }
}

console.log(transferSafely(1, 2, 5000)); // fails partway through
// accounts AFTER: still { 1: 100, 2: 50 } β€” genuinely unchanged, real rollback

console.log(transferSafely(1, 2, 30)); // succeeds
// accounts AFTER: { 1: 70, 2: 80 } β€” genuinely committed

// --- connection pool leak vs. the fix ---
function correctQuery(pool, shouldFail) {
  const conn = pool.acquire();
  if (!conn) return "POOL EXHAUSTED";
  try {
    if (shouldFail) throw new Error("query failed");
    return "queried with conn " + conn.id;
  } finally {
    pool.release(conn); // genuinely runs even when the query throws
  }
}
// a pool of size 3, 5 alternating success/failure calls via correctQuery:
// available=3 inUse=0 after EVERY single call β€” genuinely never leaked

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 150 of 152 in Node.js

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Node.js questions
Up nextHard

How do you capture and analyze a heap snapshot to find a memory leak?

Continue