Web Development Bug Report

IndexedDB TransactionInactiveError after await inside a transaction

A cache refresh wrote half its records and then threw TransactionInactiveError. We awaited a fetch inside an open IndexedDB transaction, which auto-committed. Fetching first and writing in one tight transaction fixed it.

Isabel Ferreira Isabel Ferreira @isabelferreira · November 14, 2026 · 7 min read · 118 Views
566-indexeddb-transactioninactiveerror-after-await

Our product catalogue page caches around 4,000 items in IndexedDB so it loads instantly on repeat visits. A background refresh pulls changed items page by page and writes them. After a refactor "to make it cleaner with async/await", the refresh began failing on the second page of every run:

TransactionInactiveError: Failed to execute 'put' on 'IDBObjectStore': The transaction has finished.

Firefox reported the same failure in its own words:

TransactionInactiveError: A request was placed against a transaction which is currently not active,
or which is finished.

The first page of 100 items was saved, the rest were lost, and the "last synced" marker pointed at a page that never arrived. Users saw a mix of fresh and stale prices.

Reproducing it

const db = await openDB('catalogue', 2);
const tx = db.transaction('items', 'readwrite');

for (let page = 1; page <= 3; page++) {
  const res = await fetch(`/api/items?changed_since=${since}&page=${page}`);
  const items = await res.json();
  for (const item of items) {
    await tx.store.put(item); // fails on page 2
  }
}
await tx.done;

It fails every time, in every browser, as long as the fetch takes longer than a microtask.

What we ruled out

  • Quota. A QuotaExceededError would carry that name. Storage use was under 20 MB.

  • Concurrent tabs. Two tabs refreshing at once could cause blocked upgrades, but the error appeared with one tab open.

  • The wrapper library. We use the idb package. Removing it and using raw IDBRequest callbacks with the same structure failed the same way.

  • A schema upgrade. Database version and stores were unchanged in the refactor.

Root cause

An IndexedDB transaction stays alive only while it has pending requests or while code is running in the same task that created it or handled one of its request events. Our await fetch() handed control back to the event loop with no IndexedDB requests outstanding. The browser saw an idle transaction and committed it. When the next page arrived, put() was called on a finished transaction.

What is happening under the hood

The IndexedDB spec gives every transaction a state: active, inactive, committing or finished. It is active while the task that created it runs and while its request callbacks run. Between those moments it is inactive. When an inactive transaction has no outstanding requests, the browser automatically commits it, and after that every new request throws TransactionInactiveError.

Promises complicate this. The idb wrapper resolves its promises from request success events, and promise reactions run as microtasks before the browser moves on, so await tx.store.put() keeps the transaction alive. A fetch(), a setTimeout, a postMessage round-trip or any other macrotask does not. The transaction cannot wait for the network, by design: long-lived write locks would block every other tab using the database.

The idb README says it plainly: do not await other things between the start and end of a transaction.

Environment

Component

Version / value

Chrome

142 (desktop and Android)

Firefox

145

Safari

26.1

Wrapper

idb 8.0

App

Vue 3.5 SPA, Vite 7

Data

~4,000 items, ~2 KB each, refreshed every 10 minutes

Minimal reproduction

Raw API, no wrapper, to show it is the platform and not the library:

const req = indexedDB.open('demo', 1);
req.onupgradeneeded = () => req.result.createObjectStore('kv');
req.onsuccess = async () => {
  const tx = req.result.transaction('kv', 'readwrite');
  tx.objectStore('kv').put('a', 1);
  await new Promise((r) => setTimeout(r, 0)); // yields a full task
  try {
    tx.objectStore('kv').put('b', 2);
  } catch (e) {
    console.log(e.name); // TransactionInactiveError
  }
};

Who is affected

  • All browsers. This is specified behaviour, not an engine bug.

  • Code that mixes network, timers, workers or crypto (crypto.subtle returns promises resolved outside the transaction) with IndexedDB writes in one transaction.

  • Code that awaits a non-IndexedDB promise between a read and a dependent write, such as "read the item, call an API, update the item".

The fix

Collect everything that needs the network first, then open a short transaction and do all reads and writes inside it without awaiting anything else.

-const tx = db.transaction('items', 'readwrite');
-for (let page = 1; page <= pages; page++) {
-  const res = await fetch(`/api/items?changed_since=${since}&page=${page}`);
-  const items = await res.json();
-  for (const item of items) await tx.store.put(item);
-}
-await tx.done;
+const changed = [];
+for (let page = 1; page <= pages; page++) {
+  const res = await fetch(`/api/items?changed_since=${since}&page=${page}`);
+  if (!res.ok) throw new Error(`items page ${page}: ${res.status}`);
+  changed.push(...(await res.json()));
+}
+
+const tx = db.transaction(['items', 'meta'], 'readwrite');
+await Promise.all([
+  ...changed.map((item) => tx.objectStore('items').put(item)),
+  tx.objectStore('meta').put({ key: 'lastSync', value: syncStartedAt }),
+]);
+await tx.done;

Two improvements came with it. The lastSync marker now commits in the same transaction as the items, so it can never point past data that was not written. And issuing all put() calls before awaiting them lets the browser pipeline the writes; the refresh went from 1.9 s to 0.6 s.

For "read, compute, write" flows that need async work in the middle, split into two transactions and guard against concurrent changes:

async function applyServerPrice(id: string) {
  const current = await db.get('items', id);              // tx 1 (implicit)
  const price = await fetchPrice(id);                      // network, no tx open
  const tx = db.transaction('items', 'readwrite');         // tx 2
  const latest = await tx.store.get(id);
  if (latest?.version !== current?.version) return tx.done; // changed meanwhile, skip
  await tx.store.put({ ...latest, price, version: latest.version + 1 });
  await tx.done;
}

Alternatives and trade-offs

  • One transaction per page. Simple, but a failure midway leaves partial data unless the marker is written per page. Acceptable when pages are independent.

  • Batching very large sets. For tens of thousands of records, split into transactions of a few thousand writes so one huge transaction does not hold memory or block other tabs.

  • Durability hint. db.transaction(store, 'readwrite', { durability: 'relaxed' }) is honoured by Chromium (other engines may ignore it) and can speed up bulk caches whose loss on a crash is acceptable. Check current support before relying on it.

How to test the fix

We run IndexedDB unit tests in Node with fake-indexeddb, which implements the auto-commit rules:

import 'fake-indexeddb/auto';
import { refreshCatalogue } from './refresh';

test('writes all pages and marker atomically', async () => {
  mockFetchPages([[item(1)], [item(2)], [item(3)]], { delayMs: 20 });
  await refreshCatalogue();
  const db = await openCatalogue();
  expect(await db.count('items')).toBe(3);
  expect((await db.get('meta', 'lastSync'))?.value).toBeDefined();
});
npx vitest run src/cache/refresh.test.ts

The delayed mock is important. With instant mocks, the bug never shows.

Confirming in production

Error tracking for TransactionInactiveError dropped from about 1,100 events a day to zero. We also compare the client cache with the server once per session for a sample of users:

catalogue_cache_mismatch_rate   before: 7.8%   after: 0.02%
catalogue_refresh_ms_p50        before: 1900   after: 610

The remaining mismatches are items changed on the server during the refresh window, which the next refresh fixes.

Regression guard

  • An ESLint rule in our plugin flags await of any call that is not on a transaction object while a variable named tx (or returned by db.transaction) is in scope. It is crude but catches the pattern.

  • The refresh test uses delayed network mocks permanently.

  • Code review checklist item: "Is anything awaited inside this transaction that is not IndexedDB?"

Security implications

None beyond data integrity. A half-written cache showed stale prices, which is a correctness issue rather than a security one, but the same pattern in an offline queue could drop user actions silently. Committing the marker with the data closes that gap. IndexedDB is per-origin and readable by any script on the origin, so do not cache tokens or personal data there without need.

Prevention checklist

  • Do network and other async work before opening the transaction.

  • Inside a transaction, await only IndexedDB operations.

  • Write progress markers in the same transaction as the data they describe.

  • Test with delayed mocks so auto-commit timing is exercised.

References

Add a label

#javascript #indexeddb #async-await #idb #browser-storage
Written by
Isabel Ferreira @isabelferreira

I am a DevOps engineer who has spent years turning hand-built infrastructure into Terraform, and hand-run deployments into pipelines. I work mostly on AWS, with Jenkins, GitHub Actions and a lot of Docker images. Infrastructure code fails differently from application code: state gets locked, a plan wants to destroy something important, a network route that looks right sends nothing. I write up the problems and the migrations that taught me something, step by step, including the parts that went wrong, so you can plan your own changes with fewer surprises.

Advertisement

Comments

0

No comments yet. Be the first to comment!

Sign In to post a comment.