In IndexedDB, you can ensure atomicity across multiple object stores by using a
single transaction that spans all the stores you want to access or modify.
What Is Atomicity in IndexedDB?
Atomicity means:
All operations within a transaction either succeed together or
fail together — the database is never left in a partial state.
How to Ensure Atomic Operations Across Multiple Stores
Step-by-Step:
const db = await openIndexedDB(); // Assume this opens your DB
const tx = db.transaction(["users", "notes"], "readwrite");
const userStore = tx.objectStore("users");
const noteStore = tx.objectStore("notes");
// Add a user
userStore.put({ id: "u1", name: "Alice" });
// Add a note for that user
noteStore.put({ id: "n1", userId: "u1", content: "My note" });
// Commit is automatic if no error occurs
tx.oncomplete = () => {
console.log("Transaction committed successfully.");
};
tx.onerror = () => {
console.error("Transaction failed and was rolled back:", tx.error);
};
If any operation inside the transaction fails, all changes are rolled back automatically.
Key Rules for Atomic Transactions
Rule
Explanation
Use the same transaction
All operations must be within the same IDBTransaction instance
Use readwrite mode
Required if you're writing to the stores
Add all needed stores in one go
transaction(["users", "notes"]) — you cannot add stores after
Don’t do async delays inside it
IndexedDB transactions auto-close if you yield to the event loop
Pitfall: No await or setTimeout Inside Transactions
const tx = db.transaction(["users", "notes"], "readwrite");
// Don't do this
await fetch("/something");
noteStore.put(...); // Will throw TransactionInactiveError
Transactions auto-close as soon as the JavaScript thread yields.
✅ Instead, prepare all async data before starting the transaction.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
In IndexedDB, you can ensure atomicity across multiple object stores by using a single transaction that spans all the stores you want to access or modify.
What Is Atomicity in IndexedDB?
Atomicity means:
How to Ensure Atomic Operations Across Multiple Stores
Step-by-Step:
Key Rules for Atomic Transactions
IDBTransactioninstancereadwritemodetransaction(["users", "notes"])— you cannot add stores afterPitfall: No
awaitorsetTimeoutInside TransactionsTransactions auto-close as soon as the JavaScript thread yields.
✅ Instead, prepare all async data before starting the transaction.
Good Pattern with Error Handling
Summary
transaction([...])callreadwritemode.oncomplete,.onerror,.onabort