Why do two read-only requests in SQLite get ‘cannot start a transaction within a transaction’?

May 6, 2025

I ran into a puzzling SQLite error while building an asset management page. To display the user list, the backend counted the users, fetched the current page, and looked up permissions for the users on that page. I put those three queries in one transaction so they would all see the data as it stood at the same point in time. When two requests overlapped, SQLite reported SQLITE_ERROR: cannot start a transaction within a transaction. Both requests were only reading.

Why does the second request fail on its first SQL statement?

In Node.js, each request called the query function separately, but both calls used the same db object. Here’s the order in which statements could reach that connection.

BEGIN;                        -- Request A starts
SELECT COUNT(*) FROM users;   -- A has the count and still needs the page of users
BEGIN;                        -- Request B starts while A's transaction is still open

As the SQLite documentation puts it, “Transactions created using BEGIN...COMMIT do not nest.” A transaction belongs to a connection. When B issues BEGIN before A commits, it is asking SQLite to start a transaction inside A’s transaction. The third statement fails even if the driver executes the statements one at a time, in exactly the order shown. Increasing busy_timeout cannot help here. The shared connection already has an open transaction. B hasn’t reached a point where it needs to wait for another connection to release a lock.1

If B should start reading immediately, give it another connection. If A and B share one connection, let B wait for A’s entire transaction to finish before it starts.

Let two requests read concurrently with a connection pool

A connection pool keeps several connections to the same database file. A borrows connection 1, B borrows connection 2, and each runs BEGIN on its own connection. SQLite allows multiple read transactions at once. Each request sees a snapshot from the time of its first read, so its count and page of users agree. The two requests may see slightly different snapshots.1

The Node.js examples below fit in a single CommonJS module. They use sqlite3@5.1.7 and sequelize-pool@7.1.0, which handles checking connections out and returning them. Create the pool once at service startup and share it across requests.2

const sqlite3 = require('sqlite3');
const { Pool } = require('sequelize-pool');
const { promisify } = require('node:util');

function createPool(filename, max) {
  return new Pool({
    min: 0,
    max,
    create: () => new Promise((resolve, reject) => {
      const db = new sqlite3.Database(filename, err => {
        if (err) reject(err);
        else resolve(db);
      });
    }),
    validate: db => db.open,
    destroy: db => promisify(db.close).call(db),
  });
}

async function withTransaction(pool, work) {
  const db = await pool.acquire();
  const exec = promisify(db.exec).bind(db);
  try {
    await exec('BEGIN');
    const result = await work(db);
    await exec('COMMIT');
    pool.release(db);
    return result;
  } catch (error) {
    await pool.destroy(db);
    throw error;
  }
}

If a query or commit fails, this example closes the connection. SQLite rolls back any uncommitted transaction when the connection closes, so the next borrower gets a clean connection. On success, the function returns the connection to the pool only after COMMIT finishes.3

const userPool = createPool('users.sqlite', 4);

async function readUserPage(db) {
  const get = promisify(db.get).bind(db);
  const all = promisify(db.all).bind(db);
  const { total } = await get('SELECT COUNT(*) AS total FROM users');
  const users = await all(
    'SELECT user_id, user_name FROM users ORDER BY user_id LIMIT 20'
  );
  return { total, users };
}

function listUsers() {
  return withTransaction(userPool, readUserPage);
}

This example fetches the count and the first page. To fetch permissions as well, use the same db inside readUserPage(db) and await that query before returning. If you borrow another connection halfway through, the permissions query might see a more recent update. With a pool size of four, up to four transactions can hold connections at once. A fifth request waits for one to become available.

Queue whole transactions when sharing one connection

One connection may be enough for a lightly used user list. Set the pool size to one. Once A borrows the connection, B automatically joins the queue. Both requests can use the same transaction function as before.2

const transactionQueue = createPool('users.sqlite', 1);

function listUsersInOrder() {
  return withTransaction(transactionQueue, readUserPage);
}

When two requests call listUsersInOrder() at the same time, B waits at pool.acquire() before it even sends BEGIN. A keeps the connection across each await between queries. Passing an async function to db.serialize() alone doesn’t give that guarantee. The driver can order statements submitted directly inside the callback, but SQL submitted after the callback returns can interleave with other requests. Every operation on this connection has to go through the same queue.4

Use a semaphore to queue just the writes

A single-connection queue makes the second reader wait even when both people are just viewing the list. What happens if we go back to four connections? Suppose A and B each have a connection and are changing permissions for two different users. SQLite allows only one write transaction at a time per database file. If A gets the write lock first, B may have to wait. For this kind of lock contention, the Node driver sqlite3@5.1.7 sets a default timeout of one second on each new connection. If A commits in time, B can proceed. If B still can’t get the lock after waiting, it may receive SQLITE_BUSY. With write-ahead logging (WAL), readers can keep reading their snapshots during a write, and writers still take turns.56

In a Stack Overflow question I read at the time, a UI thread and a background thread were both writing in batches. One answer suggested sending the write jobs to a single queue.7 In Node.js, a semaphore can enforce that rule. It has a fixed number of permits. A task that gets a permit can run, and the rest wait in line. Giving writers one permit makes write transactions take turns.

run() waits for the supplied task to finish. Its finally block hands the permit directly to the task that has waited the longest. Since the task covers the whole transaction, the next task starts only after the commit finishes or error cleanup completes.

class Semaphore {
  constructor(permits) {
    this.available = permits;
    this.waiters = [];
  }

  async run(task) {
    if (this.available > 0) {
      this.available--;
    } else {
      await new Promise(resolve => this.waiters.push(resolve));
    }

    try {
      return await task();
    } finally {
      const next = this.waiters.shift();
      if (next) next();
      else this.available++;
    }
  }
}

Create the writes semaphore once per process. A request to view the list still borrows a connection directly from the four-connection userPool. A request to revoke a privilege first acquires the write permit, then borrows a connection from the same pool.

const writes = new Semaphore(1);

function revokePrivilege(userId, privilege) {
  return writes.run(() => withTransaction(userPool, async db => {
    const run = promisify(db.run).bind(db);
    await run('DELETE FROM user_privileges WHERE user_id = ? AND priv_name = ?',
              [userId, privilege]);
  }));
}

The order matters. Suppose A is updating permissions when B, C, and D also request changes. All three wait at writes.run() without holding any connections. Someone opening the list can still borrow an idle connection. If writers borrowed connections before waiting for the permit, those four write requests could occupy the entire pool and make readers wait too.

The pool size of four determines how many connections can be checked out at once. The single write permit determines how many write transactions this process can start at once. Setting the limits independently lets readers bypass the writers’ queue. If another process writes to the same file, it has its own semaphore. SQLite still coordinates file locking between processes.5

Footnotes

  1. SQLite. (2026, February 18). Transaction, §§ 2–2.2. Quotation from the paragraph on nested transactions in § 2. SQLite Documentation. Transactions. ↩ ↩2

  2. Sequelize contributors. (n.d.). Sequelize Pool (v7.1.0), “Create pool using a factory object” and “Use pool in your code to acquire/release resources.” GitHub. Connection pool example. ↩ ↩2

  3. SQLite. (n.d.). Closing a database connection, final paragraph. SQLite C Interface. Rollback when closing a connection. ↩

  4. Tan, A. (2016, November 29). Control flow, “Database#serialize([callback]).” node-sqlite3 Wiki. When statements enter the queue. ↩

  5. SQLite. (n.d.). Isolation in SQLite, “Isolation between database connections” and “Isolation and concurrency.” SQLite Documentation. Single writer and WAL snapshots. ↩ ↩2

  6. node-sqlite3 contributors. (n.d.). database.cc (v5.1.7), Database::Work_Open. GitHub. The 1,000 ms default for new connections. SQLite. (n.d.). Set a busy timeout. SQLite C Interface. Waiting and SQLITE_BUSY. ↩

  7. Vasilyev, K. (2018, November 29). Answer to “Concurrency issue with two SQLite connections in two different Threads”, steps 1–4 of the write queue proposal. Stack Overflow. Queuing writes from both threads. ↩

© 2025 borui. All rights reserved. This content may be freely reproduced, displayed, modified, or distributed with proper attribution to borui and a link to the article: borui (2025-05-06). Why do two read-only requests in SQLite get ‘cannot start a transaction within a transaction’?. https://caiborui.com/blog/2025-05-06-en-sqlite-concurrent-requests-begin-transaction

@misc{borui2025-0010ad14,
  author = {borui},
  title = {{Why do two read-only requests in SQLite get ‘cannot start a transaction within a transaction’?}},
  year = {2025},
  publisher = {borui's blog},
  url = {https://caiborui.com/blog/2025-05-06-en-sqlite-concurrent-requests-begin-transaction}
}