Storage performance
Time localStorage, IndexedDB, OPFS and the Cache API on the main thread and to the disk: batching, durability, workers, quota and eviction.
- 01Tell a store's two costs apartThe time the main thread spends handing data over, which holds up taps, and the time until the data is stored.
- 02Save fast in IndexedDB and OPFSBatch writes into one transaction, pick strict or relaxed, and write files from a worker with a sync access handle.
- 03Pick a store for each job, and plan for spaceKnow what each store is built for, read estimate() and persist() for what they are, and what eviction removes.
Why did Asha's tap wait while the shop saved?
Asha is on the bus again. The Leaf and Kettle has a new button: Keep for offline. It saves the shop's catalogue on her phone, so she can browse with no signal. The catalogue is 1,000 small records, one for each tea the shop sells.
She taps Keep for offline. A moment later, she taps Add on Mint tea. Nothing happens. The cart still says Cart: 0. Almost a third of a second passes before it says Cart: 1.
Ravi built the button. He saved each tea with the Cache API, the store his service worker already uses, as in lesson 25.1. Was that the mistake? Would another store do better? And which store finishes saving first? This lesson times each store, one by one, to find out.
The course recorded Asha's taps in Chrome. Here is her screen with Ravi's first version, and with a second one that uses IndexedDB, the browser's own database:
Each picture is a real frame of her screen. In the top row, nothing changed for 301 ms. Then the cart and the status line under the button changed together. In the bottom row, Cart: 1 came at 87 ms. Here are the same times as code:
// Asha's screen, in ms after she tapped Keep for offline. She tapped Add 10 ms later.const versions = [ { store: "Cache API", cartShown: 300.6, keptShown: 467.7 }, { store: "IndexedDB", cartShown: 87.3, keptShown: 128.7 },];for (const version of versions) { console.log(`${version.store}: Cart: 1 at ${version.cartShown.toFixed(1)} ms, saved at ${version.keptShown.toFixed(1)} ms`);}- Line 1 is a comment. Times are in milliseconds (ms), thousandths of a second. They count from her tap on Keep for offline.
- Lines 3 and 4 hold each version's two moments: when Cart: 1 appeared, and when "Kept for offline" appeared.
- Lines 6 to 8 print one line per version:
Cache API: Cart: 1 at 300.6 ms, saved at 467.7 msandIndexedDB: Cart: 1 at 87.3 ms, saved at 128.7 ms.
So the store matters. With the Cache API, Asha waited 300.6 ms to see her cart change. In lesson 26.1, a tap counted as good when the screen answered within 200 ms. Why it matters: the same button can feel quick or broken, just from where it saves.
Why did her screen freeze? A page has one main thread. It runs the page's code, answers taps and draws each frame, one job at a time. While it's busy handing data to a store, a tap has to wait. The store's own work, writing to the disk, can happen somewhere else.
You hand a coat in at the dry cleaner's. You wait at the counter while the assistant writes your ticket. Then you leave. The cleaning happens in the back, later. A slow ticket keeps you at the counter. A slow cleaning doesn't: you're already gone.
- In real life: You, standing at the counter
- In JavaScript: The page's main thread, which also answers taps
- In real life: The assistant writing your ticket
- In JavaScript: The work the page does when it calls the store, like copying the data
- In real life: The cleaning, in the back room
- In JavaScript: Writing the files to the disk, outside the page
- In real life: Your coat is ready
- In JavaScript: The store says the save is done
Every store has two clocks. One is the time the page's main thread spends handing the data over. A tap that comes then has to wait. The other is the time until the data is stored. Keep the first short, so taps stay quick. Watch the second, because the data isn't safe until it ends.
How the course recorded it
- The page: the tea list from lesson 26.1, with a Keep for offline button. It saves one of two jobs: the catalogue (1,000 records, 111 KB of text) or a photo pack (one file of 2,000,000 bytes).
- Seven ways: localStorage; IndexedDB with one transaction per tea or one for all, each "relaxed" or "strict"; a file written by a worker; and the Cache API.
- The browser: Chrome 157, with no window, on a Mac laptop. It wrote to the laptop's SSD (solid-state drive), at full speed. These are that laptop's numbers, not a phone's.
- Asha's phone: the CPU 4x slower, as in lesson 28.1. Chrome slows only the page's main thread this way, not its workers.
- The taps: mouse clicks, sent through DevTools. Add on Mint tea came 10 ms after Keep for offline, so it always came while the save ran.
- The runs: each way three times, taking turns. The lesson quotes the middle run. After each save, the page loaded again and read the data back.
- HTTPS: the pages came from the laptop over HTTPS, with a certificate Chrome trusted. OPFS, the Cache API and
navigator.storageonly work on secure pages.
localStorage: the page waits for every write
Start with the oldest store. localStorage keeps text under names, like tea-1. Lesson 28.1 timed one write and saw it block. Here is why, and what it costs for a whole catalogue.
When you phone a friend, you wait on the line until they answer. You can't do anything else. When you send a text, you press send and get on with your day. The reply comes later.
- In real life: A phone call: you wait on the line
- In JavaScript: A synchronous call, like
localStorage.setItem() - In real life: A text: you press send and carry on
- In JavaScript: An asynchronous call, like IndexedDB's
put() - In real life: The reply arriving later
- In JavaScript: An event or a promise, like
complete
A synchronous call is the phone call: the next line of code waits until it's done. An asynchronous call is the text. It starts the work and returns at once. The answer comes later, as an event or a promise. localStorage is synchronous. In the HTML Standard's steps, setItem() returns only when the value is in place.
function saveToLocalStorage(teas) { for (const tea of teas) { localStorage.setItem(`tea-${tea.id}`, JSON.stringify(tea)); }}- Line 1 starts a function that takes the 1,000 teas.
- Line 2 goes through them one at a time.
- Line 3 turns each tea into text with
JSON.stringify(). Then it saves the text under the tea's own name:tea-1,tea-2and so on.
Asha's tap on Keep for offline ran this function. Here is what it cost:
// localStorage, with the CPU 4x slower, in ms.const saving = { catalogue: 21.0, photoPack: 15.7 };const addTapWaited = 22.2;console.log(`The catalogue: ${saving.catalogue.toFixed(1)} ms of waiting`);console.log(`The photo pack: ${saving.photoPack.toFixed(1)} ms of waiting`);console.log(`The Add tap waited ${addTapWaited.toFixed(1)} ms`);- Line 2 holds how long each job took. The photo pack became 2,666,668 characters. localStorage only keeps text, so the page first turned the bytes into text (base64). That made them a third bigger.
- Line 3 holds how long the Add tap waited before its code could run.
- Lines 4 to 6 print
The catalogue: 21.0 ms of waiting,The photo pack: 15.7 ms of waitingandThe Add tap waited 22.2 ms.
The whole save ran inside the Keep tap's task: one piece of work the main thread runs without a break. So the Add tap waited 22.2 ms. The photo pack works out at about 6.2 ms per MB of text, a little more than the 5.2 ms lesson 28.1 measured for one 1 MB write. Why it matters: every write pays this wait, and it grows with the size of what you save.
The page waits for copying, not for the disk
Chrome's source shows what happens inside. setItem() changes the page's own copy of the store. Then it sends the change to another part of Chrome, without waiting for an answer. That part writes the disk later.
Reading has a catch of its own. The first time a page touches localStorage, Chrome copies the whole store into the page, and the page waits. The course loaded the page again and read the catalogue back:
// The next page load reads the catalogue back, in ms.const firstGetItem = 0.8;const all1000 = 5.5;console.log(`The first getItem(): ${firstGetItem.toFixed(1)} ms`);console.log(`All 1,000 records: ${all1000.toFixed(1)} ms`);- Line 2 holds the first
getItem(). Line 3 holds reading all 1,000 records and turning them back into objects. - It prints
The first getItem(): 0.8 msandAll 1,000 records: 5.5 ms.
Both were quick here. The store was small, and it had just been written. But that first call copies everything. A big store makes every page load that touches it wait. Why it matters: keep localStorage small, even if you only read a little of it.
Two more limits come from the standards. localStorage exists only on a page's window, not in workers (HTML Standard). So you can't move it off the main thread. And each site gets 5 MiB of it: 5 × 1,024 × 1,024 bytes (Storage Standard).
IndexedDB: one transaction or a thousand
IndexedDB is the browser's database for records. It's asynchronous: you ask, and an event brings the answer. Every write happens inside a transaction: a group of changes that are saved together, or not at all. Saving a transaction is called committing it. The system design lesson IndexedDB shows how it works. Here, we time it.
A lift carries people up a building. Every trip costs the same: the doors open, close, and the lift climbs. Ten people in one trip pay that once. Ten people in ten trips pay it ten times, and the last one waits for all the others.
- In real life: One trip of the lift
- In JavaScript: One transaction, with its own commit
- In real life: The doors opening and closing
- In JavaScript: The fixed cost of each transaction: starting, committing, and its
completeevent - In real life: Everyone going up in one trip
- In JavaScript: Batching: many
put()calls in one transaction
Ravi tried two ways. The first gives each tea its own transaction, and waits for it:
async function saveEachTea(db, teas, durability) { for (const tea of teas) { const tx = db.transaction("teas", "readwrite", { durability }); tx.objectStore("teas").put(tea); await finished(tx); }}- Line 1 starts the function.
durabilityis a choice the next section explains. - Line 3 opens a new transaction for this tea, on the
teasstore, to read and write. - Line 4 puts the tea into it.
- Line 5 waits until it has committed.
finished()is a small helper that waits for the transaction'scompleteevent.
The second puts every tea in one transaction:
function saveAllTeas(db, teas, durability) { const tx = db.transaction("teas", "readwrite", { durability }); const store = tx.objectStore("teas"); for (const tea of teas) store.put(tea); return finished(tx);}- Line 2 opens one transaction.
- Line 4 puts all 1,000 teas into it, without waiting between them.
- Line 5 waits for that one transaction to commit.
// IndexedDB, 1,000 records, relaxed, in ms.const oneByOne = { finished: 899.3, mainThread: 343.4, longestTask: 8.8 };const allAtOnce = { finished: 102.4, mainThread: 52.0, longestTask: 38.9 };for (const [name, save] of Object.entries({ oneByOne, allAtOnce })) { console.log(`${name}: done at ${save.finished.toFixed(1)}, main thread ${save.mainThread.toFixed(1)}, longest task ${save.longestTask.toFixed(1)}`);}- Lines 2 and 3 hold each way's time to finish, its main-thread work, and its longest task, in ms.
- It prints
oneByOne: done at 899.3, main thread 343.4, longest task 8.8andallAtOnce: done at 102.4, main thread 52.0, longest task 38.9.
One transaction finished at 102.4 ms. A thousand took 899.3 ms, about 9 times as long. Why it matters: the cost is per transaction, so put writes that belong together in one.
Asynchronous isn't free
Now look at the main thread. One by one, the page did 343.4 ms of work, in small pieces. Its longest task was 8.8 ms, so the save never kept a tap waiting long. All at once, it did only 52.0 ms. But 38.9 ms of it came in one task.
Why? Each put() copies its record before it returns. The IndexedDB spec says so in its steps: "Let clone be a clone of value". Chrome's trace, its record of everything the browser did, calls that work IDBObjectStore::putRequestSetup. It took 26.2 ms of the tap's task.
Why it matters: an asynchronous store still costs the main thread something for every record you hand it. For a very big batch, use a few transactions, with a break between them. Lesson 27.3 shows how to break up long work.
Try both ways in your own browser. The lab saves 1,000 records and watches the frames:
| Done after | not run |
|---|---|
| Longest gap between frames | not run |
| Frames while it saved | not run |
The lab saves 1,000 small records, the way the course did, then deletes them. Your numbers depend on your device, so compare the three ways with each other.
Strict or relaxed: waiting for the disk
When a transaction commits, its data goes to the operating system. The system keeps it in memory for a moment, then writes it to the disk. Writing it out straight away is called flushing.
You can drop a letter in a postbox and walk away. It goes out with the next collection. Or you can hand it in at the counter and wait for a signed receipt. The receipt takes longer. It only helps if something goes wrong before the collection.
- In real life: Dropping the letter in a postbox
- In JavaScript:
"relaxed":completefires once the operating system has the data - In real life: Waiting at the counter for a receipt
- In JavaScript:
"strict":completefires after the data is flushed to the disk - In real life: Something going wrong before collection
- In JavaScript: A power cut, or the whole computer crashing
The IndexedDB spec calls this choice the durability hint. With "strict", the browser waits until the changes "have been successfully written to a persistent storage medium". With "relaxed", it reports success "as soon as all outstanding changes have been written to the operating system".
You pick it when you open the transaction, as line 2 of saveAllTeas() does. Since Chrome 121, a transaction that doesn't pick gets relaxed, as in Firefox and Safari. The course timed both:
// Time to finish, in ms: relaxed and strict.const oneByOne = { relaxed: 899.3, strict: 1270.5 };const allAtOnce = { relaxed: 102.4, strict: 107.9 };console.log(`One by one: strict took ${(oneByOne.strict - oneByOne.relaxed).toFixed(1)} ms longer`);console.log(`All at once: strict took ${(allAtOnce.strict - allAtOnce.relaxed).toFixed(1)} ms longer`);- Lines 2 and 3 hold each way's time to finish, relaxed and strict.
- It prints
One by one: strict took 371.2 ms longerandAll at once: strict took 5.5 ms longer.
One by one, strict added 371.2 ms: a flush for each of the 1,000 commits. All at once, it added 5.5 ms: one flush. Why it matters: batching makes the safe choice cheap.
On this laptop's SSD, a flush was quick. Chrome's team saw relaxed run 3 to 30 times faster in real apps. The spec warns that flushing "can take significant time and consume battery life on portable devices".
So when do you need strict? Chrome's team gives one example: moving data to a new format. There, you delete the old copy only after the new one is written. The spec suggests relaxed for "ephemeral data such as caches or quickly changing records".
OPFS: a file written by a worker
The origin private file system, or OPFS, gives a site its own folder of files. The JavaScript lesson Cache API & file storage showed how to use it. Its fastest tool is a sync access handle: an object whose read() and write() run synchronously.
The File System Standard gives it only to dedicated workers. A dedicated worker is a script that runs on its own thread, for one page, as in lesson 27.4. A synchronous call there can't hold up a tap.
A busy shop has one assistant at the till. When a delivery comes, she doesn't unpack it herself. She hands the boxes to a helper in the back room, who has his own key to the stockroom. He can take as long as he likes. The queue at the till keeps moving.
- In real life: The assistant at the till
- In JavaScript: The page's main thread
- In real life: Handing the boxes over
- In JavaScript:
postMessage(): copying the teas into the worker's message - In real life: The helper in the back room
- In JavaScript: A dedicated worker
- In real life: His key to the stockroom
- In JavaScript: A sync access handle: only one can hold a file at a time
Here is the worker's part. It writes one file:
async function writeFile(name, bytes) { const root = await navigator.storage.getDirectory(); const file = await root.getFileHandle(name, { create: true }); const handle = await file.createSyncAccessHandle(); handle.truncate(0); handle.write(bytes, { at: 0 }); handle.flush(); handle.close();}- Line 2 gets the site's top folder. Line 3 opens the file, and makes it if it's missing.
- Line 4 asks for a sync access handle. This one call is asynchronous, "despite the Sync in its name", as web.dev puts it.
- Line 5 empties the file. Line 6 writes the bytes at the start.
- Line 7 flushes them to the disk. Line 8 closes the handle.
While the handle is open, it holds an exclusive lock: no other handle can open that file. So close it as soon as you're done. The page sends the teas to the worker with postMessage(). The worker turns them into one file of text and writes it:
// OPFS, written by a worker: the catalogue, in ms.const finished = 48.8;const mainThread = 7.2;const worker = 5.0;console.log(`Done at ${finished.toFixed(1)} ms`);console.log(`Main thread: ${mainThread.toFixed(1)} ms. Worker: ${worker.toFixed(1)} ms.`);- Lines 2 to 4 hold the time to finish, the main thread's work, and the worker's work.
- It prints
Done at 48.8 msandMain thread: 7.2 ms. Worker: 5.0 ms..
The save finished at 48.8 ms. The main thread did 7.2 ms of it: handling the tap, and copying the teas into the message. The worker did 5.0 ms, and was idle the rest of the time. Chrome's slowdown didn't apply to the worker, so its part ran at the laptop's full speed. Why it matters: work in a worker can't hold up a tap.
The Cache API: whole responses, not records
Now back to Ravi's first try. The Cache API stores pairs: a request, and the whole response to it, with its status, headers and body. Lesson 25.1 used it from a service worker. The JavaScript lesson compared it to a pantry of ready meals. Ravi stored each tea as a meal of its own:
function saveToCache(cache, teas) { return Promise.all(teas.map((tea) => cache.put(`/offline/teas/${tea.id}.json`, new Response(JSON.stringify(tea)))));}- Line 2 makes a new
Responsefor each tea, holding its text. It saves each one under its own address:/offline/teas/1.jsonand so on.Promise.all()waits until all 1,000 are saved.
// The Cache API, in ms.const catalogue = { finished: 454.1, longestTask: 252.3 };const photoPack = { finished: 43.7, longestTask: 10.5 };console.log(`1,000 responses: done at ${catalogue.finished.toFixed(1)}, longest task ${catalogue.longestTask.toFixed(1)}`);console.log(`One 2 MB response: done at ${photoPack.finished.toFixed(1)}, longest task ${photoPack.longestTask.toFixed(1)}`);- Line 2 holds the catalogue. Line 3 holds the photo pack, saved as one response.
- It prints
1,000 responses: done at 454.1, longest task 252.3andOne 2 MB response: done at 43.7, longest task 10.5.
The 1,000 responses froze the page. One task ran for 252.3 ms. Chrome's trace puts 211.8 ms of it inside the Cache API's put() calls. One 2 MB response was quick: done at 43.7 ms, with no long task (a task over 50 ms). Why it matters: the Cache API pays for each entry. It's built for whole files, like a page or a photo, not for a thousand small records.
Reading them back was slow too: 308.1 ms on the next load, against 8.2 ms for IndexedDB's getAll().
Here are all seven ways side by side, for the catalogue. Read each row as one way. Lower is better in every column.
| Way | Done after | Main-thread work | Longest task |
|---|---|---|---|
| localStorage | 21.0 ms | 21.0 ms | 30.1 ms |
| IndexedDB, one transaction per tea, relaxed | 899.3 ms | 343.4 ms | 8.8 ms |
| IndexedDB, one transaction per tea, strict | 1270.5 ms | 235.5 ms | 12.5 ms |
| IndexedDB, one transaction for all, relaxed | 102.4 ms | 52.0 ms | 38.9 ms |
| IndexedDB, one transaction for all, strict | 107.9 ms | 54.8 ms | 38.3 ms |
| OPFS, written by a worker | 48.8 ms | 7.2 ms | 8.9 ms |
| Cache API | 454.1 ms | 313.8 ms | 252.3 ms |
The photo pack told a different story. One 2 MB file is one entry in any store:
| Way | Done after | Main-thread work |
|---|---|---|
| localStorage | 15.7 ms | 15.7 ms |
| IndexedDB, one transaction for all, relaxed | 63.2 ms | 8.7 ms |
| IndexedDB, one transaction for all, strict | 52.3 ms | 7.1 ms |
| OPFS, written by a worker | 57.8 ms | 8.8 ms |
| Cache API | 43.7 ms | 5.5 ms |
Every asynchronous store kept the main thread nearly free. localStorage didn't: 15.7 ms, all of it on the main thread. Pick a way to see everything the course recorded for it, with the code it ran:
function saveToLocalStorage(teas) {
for (const tea of teas) {
localStorage.setItem(`tea-${tea.id}`, JSON.stringify(tea));
}
}| Done after | 21.0 ms |
|---|---|
| Main-thread work for the save | 21.0 ms |
| Longest task while it saved | 30.1 ms |
| Cart: 1 on Asha's screen | 84.0 ms |
| "Kept for offline" on her screen | 84.0 ms |
| Reading it back on the next load | 5.5 ms |
The main thread spent 21.0 ms on the save. Its longest task, which a tap would have to wait for, ran 30.1 ms. Times on Asha's screen count from her tap on Keep for offline.
How much room, and when it's cleared
Space is the last cost. The JavaScript lesson compared it to a rented apartment: the quota is its size, and the usage is what's inside. navigator.storage.estimate() gives both, in bytes. The course asked, saved both jobs in all four stores, and asked again:
// What navigator.storage said, in bytes.const before = { usage: 2151, quota: 10737420391 };const after = { usage: 7253674, quota: 10744671914 };console.log(`Stored: ${((after.usage - before.usage) / 1e6).toFixed(1)} MB`);console.log(`Quota minus usage: ${((after.quota - after.usage) / 1024 ** 3).toFixed(1)} GiB`);- Line 2 holds the first answer. The site already used 2,151 bytes: the empty database the page had opened.
- Line 3 holds the answer after saving.
- It prints
Stored: 7.3 MBandQuota minus usage: 10.0 GiB. A GiB is 1,024 × 1,024 × 1,024 bytes, a little more than a GB.
The answer also had usageDetails, a split by store, which only Chromium browsers give. IndexedDB held 2.37 MB. OPFS, called fileSystem, held 2.11 MB. The Cache API held 2.77 MB for the same data. localStorage wasn't counted at all: it has its own 5 MiB limit.
Now the quota. The laptop's disk holds 494.4 GB. Chrome lets one site use 60% of the disk: a pool of 80% for all sites, and 75% of that for one. That's 296.6 GB. But estimate() said the quota was exactly 10 GiB more than the usage.
Chrome's source shows the rule. It reports the usage plus 10 GiB, on any disk of 10 GiB or more. The Storage Standard warns that "revealing available storage space can lead to fingerprinting". That means telling one device apart from another.
Why it matters: the quota from estimate() is a guide, not the limit. Write as if any save can fail. Catch the QuotaExceededError a store throws when the site is full, as web.dev advises.
Eviction, and asking to stay
When a device runs low on space, the browser may delete a site's data to make room. That's called eviction. Data starts out best-effort: the browser may clear it without asking. Chrome and Firefox clear the least recently used site first. They delete all of its data at once, every store together.
Safari also deletes data that scripts made, on sites the user hasn't touched in seven days of browsing, when its tracking prevention is on.
navigator.storage.persist() asks for persistent storage, which the browser won't clear on its own. Chrome answered false in 0.9 ms, without asking anyone. It says yes to sites it thinks are important, for example ones that are installed or bookmarked. The course's brand-new site wasn't. Why it matters: ask once the user has shown they care, and keep a way to fetch the data again.
Ask your own browser about this site:
| usage | not asked |
|---|---|
| quota | not asked |
| persisted() | not asked |
The lab calls estimate() and persisted() for this site. It doesn't call persist().
Which store for which job?
Each job below has a store built for it. The system design lesson Client storage options compares them all. Sort each job into its store:
- A dark-mode setting, read before the first paint
- The last five teas Asha opened
- 1,000 tea records, looked up by id
- An order Asha wrote offline, which must survive a crash
- A 50 MB video draft, edited a piece at a time
- A SQLite database file
- The offline copy of the tea list page
- The shop's CSS and JavaScript files
Sort each piece of data by the store that suits it best.
Common mix-ups
- "IndexedDB is asynchronous, so saving costs the page nothing." No. Each
put()copies its record on the main thread. 1,000 of them in one transaction made a 38.9 ms task. - "localStorage is slow because it waits for the disk." No. Chrome writes the disk later, elsewhere. The page waits for its own copying.
- "Strict durability makes every save much slower." No. It adds one flush per commit. With one transaction, it added 5.5 ms here.
- "The Cache API is a fast store for any data." No. It stores whole responses. A thousand small ones made one 252.3 ms task.
- "estimate().quota is how much a site can store." No. Chrome reports the usage plus 10 GiB. The real limit is 60% of the disk.
- "persist() keeps data safe forever." No. The browser may say no, as Chrome did here. And the user can always clear a site's data.
Practice exercises
Answer first, then use the hints.
Each tea had its own transaction. What does this print?
const oneByOne = { transactions: 1000, finished: 899.3 };
console.log(`${(oneByOne.finished / oneByOne.transactions).toFixed(1)} ms per transaction`);0.9 ms per transaction. Each one paid for starting, committing and its complete event. One transaction for all paid that once.
Both runs gave each tea its own transaction. What does this print?
const relaxed = 899.3;
const strict = 1270.5;
console.log(`${((strict - relaxed) / 1000).toFixed(2)} ms more per commit`);0.37 ms more per commit. Small on this SSD, but paid a thousand times. One transaction pays it once.
Which line makes this save pay for a thousand commits?
async function saveEachTea(db, teas, durability) {
for (const tea of teas) {
const tx = db.transaction("teas", "readwrite", { durability });
tx.objectStore("teas").put(tea);
await finished(tx);
}
}function saveAllTeas(db, teas, durability) {
const tx = db.transaction("teas", "readwrite", { durability });
const store = tx.objectStore("teas");
for (const tea of teas) store.put(tea);
return finished(tx);
}Line 3 opens a new transaction for every tea, so the save pays 1,000 commits. Open one transaction before the loop, put every tea, and wait for that one transaction to finish.
With one strict transaction per tea, how many ms after her tap did "Kept for offline" appear on Asha's screen?
Asha saw the save finish after more than a second. Her cart had changed long before, because the main thread was free between the small transactions.
Open the course's copy of the shop and tap Keep for offline. In DevTools, find the teas store in IndexedDB. What is the name of the tea with id 9?
Mint tea no. 2. The catalogue goes round the eight teas, so the ninth record starts the second round. The record stays until you clear the site's data in the Application panel.
The IndexedDB spec lists three durability hints. Two are "strict" and "relaxed". What is the third?
It tells the browser to use its own usual behaviour for the storage bucket. In Chrome since version 121, that's relaxed.
Check your understanding
For each question, ask yourself which clock it's about: the main thread's, or the time until the data is stored.
Question 1 of 8Why did Asha's Add tap wait on the localStorage version?
Choose an answer to see the explanation.
Question 2 of 8Why did one transaction for all the teas finish much sooner than one transaction per tea?
Choose an answer to see the explanation.
Question 3 of 8IndexedDB is asynchronous. Why did saving all the teas at once still hold the main thread in one long task?
Choose an answer to see the explanation.
Question 4 of 8What does durability: "strict" add to a transaction?
Choose an answer to see the explanation.
Question 5 of 8Where can a page call createSyncAccessHandle()?
Choose an answer to see the explanation.
Question 6 of 8Why did Ravi's Cache API version freeze Asha's screen?
Choose an answer to see the explanation.
Question 7 of 8What does this line print for the estimate Chrome gave after the saves?
Read the code, then predictconst estimate = { usage: 7253674, quota: 10744671914 }; console.log((estimate.quota - estimate.usage) / 1024 ** 3);Choose an answer to see the explanation.
Question 8 of 8When Chrome evicts a best-effort site to free space, what does it delete?
Choose an answer to see the explanation.
Key takeaways
- Every store has two clocks: the main thread's time to hand the data over, and the time until it's stored. Taps feel the first.
- localStorage is synchronous and lives only on the window. Every write waits, and so does a page's first read.
- IndexedDB's put() copies each record on the main thread. Put records that belong together in one transaction.
- Strict flushes every commit to the disk. Batching makes it cheap. Chrome uses relaxed unless you ask.
- OPFS's sync access handle works only in dedicated workers, where it can't hold up a tap.
- The Cache API is for whole responses. A thousand small ones froze the page.
- estimate() is a guide: Chrome reports the usage plus 10 GiB. Eviction clears a whole site, and persist() asks to be spared.
Remember the one-liner.
Time both clocks: keep the main thread's part short, batch the commits, and give each kind of data the store built for it.
Sources
The facts on this page come from these standards, docs and source files:
- Web storage, HTML Standard, WHATWG.
- cached_storage_area.cc: how a page's localStorage loads and writes, Chromium source.
- Storage Standard, WHATWG.
- Indexed Database API 3.0, W3C.
- A change to the default durability mode in IndexedDB, Chrome for Developers.
- File System Standard, WHATWG.
- The origin private file system, web.dev.
- thread_cpu_throttler.cc: which thread DevTools' CPU slowdown slows, Chromium source.
- Storage for the web, web.dev.
- Storage quotas and eviction criteria, MDN.
- StorageManager: estimate() method, MDN.
- StorageManager: persist() method, MDN.
- quota_settings.cc: how much of the disk one site may use, Chromium source.
- quota_manager_impl.cc: the quota estimate() reports, Chromium source.
- Persistent storage, web.dev.
Coming next: How CLS works. Why a page jumps under Asha's finger, and how Chrome scores it.