Skip to content

    Frontend System Design

    IndexedDB, Storage Quotas and Eviction

    How IndexedDB keeps structured data, how versions and transactions protect it, and how quotas can refuse a write or evict a whole origin, with a runnable lab.

    By Published 13 min read

    • frontend-system-design
    • indexeddb
    • storage
    • quotas
    Share

    Standard lessonintermediateTypeScript labFrontend System Design

    Before this: Browser Storage: Cookies, Web Storage, IndexedDB and the Cache API

    What you'll learn: By the end of this lesson you will be able to say what IndexedDB stores and how (object stores, keys, structured clone), explain why a database has a version and what an upgrade may change, explain why a transaction commits all its changes or none, describe how a browser budgets storage per origin, separate a refused write from an evicted origin, and design an application cache that survives both.

    Think of a rented storage unit in a large building. You may fill it with boxes, but the building limits each tenant's space, and a tenant who overfills is refused at the door. When the whole building runs short, the manager may clear out the unit of the tenant who visited longest ago, and clears the whole unit, not one box. A tenant with a guaranteed unit is skipped.

    The running example is an order desk for field sales: a catalogue that can be downloaded again, and order drafts that exist only on the device until sent. The lab's sizes are made up.

    The core idea

    1. IndexedDB is a small transactional database in the browser. It stores structured values under keys, asynchronously, with a schema version and all-or-nothing transactions.
    2. Storage is a budget, and the browser owns it. Space is limited per origin, a write can be refused, and under pressure the browser may delete an origin's data.
    3. Design for both failures. A refused write is an error you can handle. An evicted origin is silence: the data is gone, so the application must notice and rebuild, and must not keep its only copy of something precious there.

    Three illustrations run through the lesson: a minimal example (a stored value), a realistic example (a bounded cache) and a failure example (an evicted origin).

    IndexedDB in one page

    MDN describes IndexedDB as a transactional database system that is JavaScript-based and object-oriented: it stores objects indexed by a key, and any object the structured clone algorithm supports can be stored. Its operations are asynchronous so they do not block the application, and it follows the same-origin policy. It is also available in Web Workers.

    A database has a name and a version. It holds object stores (like tables) of records found by a key, usually taken from a property of the value. All reading and writing happens inside a transaction. Unlike Web Storage, values are not limited to strings and calls do not block the thread.

    Figure 1. Where IndexedDB sits

    A page or worker reads and writes IndexedDB inside transactions, and the origin's storage budget limits what it can holdPage or worker to IndexedDB (transactions); IndexedDB to Origin budget (counts against)ONE ORIGINPage or worker: your codePage or workeryour codeIndexedDB: stores, keys, versionsIndexedDBstores, keys,versionsOrigin budget: quota, evictionOrigin budgetquota, evictiontransactionscounts against

    How to read this: the application talks only to IndexedDB, asynchronously. Whatever it stores counts against a budget that belongs to the origin as a whole, shared with every other storage API the origin uses.

    Minimal example: what a stored value looks like

    IndexedDB copies values with the structured clone algorithm, not JSON. MDN lists Date, Map and Set among the supported types, and says a Function cannot be duplicated: attempting it throws a DataCloneError. The lab's first section shows it: a record with a Date, a Set and a Map comes back with its types intact, the same record sent through JSON turns the Date into a string and the Set into {}, and an object that holds a function is refused. Anything with behaviour must become plain data first.

    Versions and upgrades

    A database's version "determines the database schema", the object stores and their structure. If the database does not exist, or you open it with a higher version, the browser fires upgradeneeded, and that handler is "the only place where you can alter the structure of the database" (MDN). It runs in a versionchange transaction.

    Two rules follow. A lower version is refused: opening with a version below the stored one fails with a VersionError, as when an old tab meets a database a newer build upgraded. And an upgrade is a transaction: if it fails it is rolled back, and the W3C specification sets the connection's version back to the previous one. Changing an existing store (for example its key path) means deleting and recreating it, which deletes its data unless you copy it first.

    Figure 2. What opening a database with a version does

    flowchart TD accTitle: Opening an IndexedDB database with a version accDescr: The requested version is compared with the stored version. A lower requested version fails with a VersionError. An equal version opens the database as it is. A higher version, or no database yet, runs the upgrade transaction, the only place the schema may change. If the upgrade finishes, the new version is stored. If it throws or aborts, it is rolled back and the previous version stays. O["open(name, version)"] --> C{"Requested version
    vs stored version"} C -->|"lower"| E["VersionError"] C -->|"equal"| S["Open as it is"] C -->|"higher, or no database"| U["Upgrade transaction:
    the only place the schema changes"] U --> K{"Did the upgrade
    finish?"} K -->|"yes"| N["New version stored,
    database open"] K -->|"no"| R["Rolled back:
    previous version stays"]

    How to read this: the version number is a promise about the shape of the data. Opening with a version is how a build checks that promise, and the upgrade is where you migrate old data to the new shape.

    MDN also describes a blocked event while other connections stay open, so a connection should close itself on versionchange. The lab does not model that.

    Transactions: all or nothing

    Every read and write happens in a transaction with a mode: readonly (the default), readwrite or versionchange. MDN states that "the default behavior of an error is to abort the transaction in which it occurred", and that aborting rolls back all the changes. A transaction also lives only while it is being used: it is tied to the event loop, so awaiting something unrelated (a network call) between requests lets it become inactive and commit without you. Keep transactions short.

    Figure 3. One transaction that cannot fit

    sequenceDiagram accTitle: A transaction that exceeds the quota accDescr: The application opens a readwrite transaction, writes a small record, then writes a large record. When the transaction tries to commit, the origin's quota would be exceeded, so the browser aborts it with QuotaExceededError. Neither record is stored, and the earlier data is untouched. participant A as Application participant T as Transaction participant O as Origin storage A->>T: open readwrite A->>T: put small record A->>T: put large record T->>O: commit: does it fit? O-->>T: no, quota exceeded T-->>A: aborted, QuotaExceededError Note over A,O: neither record remains, earlier data is untouched

    How to read this: the application never sees half a write. In the lab the check happens at commit, a simplification: a browser may refuse earlier or later, but exceeded quota is documented as one of the reasons a transaction aborts.

    MDN notes that in Firefox 40 and later complete can fire before the data has been flushed to disk.

    Quotas and eviction: a budget the browser owns

    MDN's quota article states that quotas and eviction apply to an entire origin and cover Web Storage, IndexedDB, the Cache API and the Origin Private File System together. There is no single number: at the time of writing it describes, for example, up to 60% of the total disk per origin for Chromium browsers, and the smaller of 10% of the disk and a 10 GiB group limit for Firefox in best-effort mode. Check the current page before relying on any of them. You cannot read the real limit anyway: navigator.storage.estimate() returns usage and quota, but MDN says the values are imprecise and the quota is a conservative approximation that can vary between origins. Use it to inform the user, never as a guarantee.

    When a write does not fit, it "fails with a QuotaExceededError", and MDN recommends a try and catch and freeing space before storing new data.

    Eviction is a different event. By default data is best-effort: it stays while the origin is under quota, the device has space and the user does not delete it. MDN lists the triggers: the device is short of space (storage pressure), all browser data exceeds what the browser is willing to use, and, only in Safari, origins not used regularly. Browsers use a least recently used policy, one origin after another, and the deletion is whole: "all of its data, not parts of it, is deleted at the same time", to avoid inconsistency. An origin granted persistent storage is skipped.

    Figure 4. Storage pressure, and who is deleted

    Under storage pressure the browser deletes the least recently used best-effort origin entirely and skips a persistent oneStorage pressure to Origin A (skipped); Storage pressure to Origin B (kept for now); Storage pressure to Origin C (deleted whole)BROWSER STORAGEStorage pressure: space runs shortStoragepressurespace runs shortOrigin A: persistentOrigin ApersistentOrigin B: best-effort, recentOrigin Bbest-effort,recentOrigin C: best-effort, oldest useOrigin Cbest-effort,oldest useskippedkept for nowdeleted whole

    How to read this: recency of use, not size or importance, decides the order. All of origin C goes at once: its IndexedDB data, its cache entries and anything else it stored.

    An application can ask for persistence with navigator.storage.persist(), which returns a promise of a boolean. MDN says the browser "may or may not honor the request": Firefox asks the user, while Safari and most Chromium browsers decide from the user's history with the site. MDN also notes that for regular visitors data is "very rarely deleted by the browser". That is exactly why eviction bugs reach production: they are rare, and nothing on the happy path exercises them.

    Realistic example: a bounded cache with protected drafts

    The order desk keeps two kinds of records. The catalogue can be fetched again, so it is a cache: bounded, safe to evict. A draft order exists nowhere else, so it is protected until the server has it. The lab's RecordCache expresses this:

    • A byte budget of its own, with the least recently used unpinned record dropped first when a new record would not fit.
    • Pinned records (drafts) that the cache never evicts. If pinned records alone exceed the budget, the write is refused with a reason instead of silently dropping a draft.
    • A retry on QuotaExceededError: free one more unpinned record and run the transaction again. A failed transaction changed nothing, so the retry starts clean.

    The cache counts the payload, the browser everything stored, so the app's budget is a policy and the quota a fact: hence the retry.

    Failure example: the empty database

    Eviction raises no error. The app starts, opens the database and finds version 0, as if the user had never visited. The lab's section 4 shows it: after the origin is evicted, reopening runs the upgrade from version 0 and the store is empty. Code that handled QuotaExceededError perfectly is useless here. What helps is detecting absence: a start-up check for a marker record or a last-sync time, and a rebuild path that refetches the catalogue and tells the user which drafts were lost.

    Trade-offs

    Choice Gain Cost
    Everything in IndexedDB, no budget Simple One large cache can cause quota errors or make the origin the eviction victim
    Bounded cache, LRU, pinned records Predictable size, drafts survive cache pressure More code; the budget only approximates the browser's counting
    Request persist() Survives storage pressure when granted The browser may refuse, and some prompt the user
    Send drafts to the server on save Short loss window Needs network and conflict handling

    Build it: a model of IndexedDB and a quota

    Goal. Run a model through five situations: what structured clone keeps, how versions and upgrades behave, how a transaction commits or rolls back, how a browser evicts an origin whole, and how an app-level cache protects drafts.

    Setup. The lab is in the course's example workspace (Node 26.13.1, pnpm). It is pure logic: no browser, no real IndexedDB.

    cd examples/frontend
    pnpm install
    cd labs/indexeddb-quota-model
    pnpm test           # 34 tests
    node src/demo.ts

    Steps.

    1. Run the tests, then the demo, and compare it with the output below.
    2. In section 2, the upgrade to version 3 deletes a store and throws; the database stays at version 2 with its data.
    3. In section 4, the oldest-used origin (mail.example) survives because it is persistent; another is deleted whole.
    4. In section 5, the pinned draft survives every eviction, and the quota retry frees exactly one record.

    Expected output, captured from a real run (Node 26.13.1, 2026-12-01):

    IndexedDB and storage quotas: what is stored, what can be refused, what can vanish
    
    === 1. What a value looks like after it is stored: structured clone, not JSON
    structured clone: createdAt is a Date: true, tags is a Set of 2, sizes is a Map of 1, note kept as undefined: true
    through JSON:     keys left: createdAt, tags, sizes; createdAt is a string; tags is {}
    storing an object that holds a function: DataCloneError
    
    === 2. Versions: the schema changes only in an upgrade, and an old build cannot open a newer database
    upgrade 0 -> 1: create "products"
    upgrade 1 -> 2: add "drafts", keep "products"
    version 2, stores: products, drafts, products kept: 1
    opening version 1 again: VersionError
    upgrade to 3 deletes "products" then throws: Error; the database is still version 2 with stores products, drafts
    
    === 3. Transactions: all of the changes or none of them
    commit three products:           ok; stored: 3
    write p4, then abort():          AbortError; stored: 3
    write p5, then add a duplicate:  ConstraintError; stored: 3 (p5 was rolled back too)
    write in a readonly transaction: ReadOnlyError
    two writes that together exceed the quota: QuotaExceededError; stored: 3 (neither write remains)
    estimate: {"usage":42,"quota":200}
    
    === 4. The browser's budget: an origin can be evicted whole, a persistent one is skipped
    mail.example  used in this order: 1, usage 116
    news.example  used in this order: 2, usage 116
    shop.example  used in this order: 3, usage 116
    shop.example is used again, so the least recently used origin is mail.example
    mail.example asks to be persistent: true
    an origin with no engagement asks:  false
    total usage 348 against a limit of 300
    under pressure the browser deleted: news.example
    mail.example  databases left: 1, usage 116, persistent: true
    news.example  databases left: 0, usage 0, persistent: false
    shop.example  databases left: 1, usage 116, persistent: false
    news.example reopens: upgrade from version 0, as if it had never been there
    news.example items after eviction: 0
    
    === 5. What the app does itself: a byte budget, least recently used first, pinned records stay
    budget of 200 payload bytes, each record 60
    after a, b, c:        ["a","b","c"] (180 bytes)
    read a (now newest):  least recently used is b
    put d:                {"ok":true,"evicted":["b"]} -> ["a","c","d"]
    put draft (pinned):   {"ok":true,"evicted":["c"]} -> ["a","d","draft"]
    put e:                {"ok":true,"evicted":["a"]} -> ["d","draft","e"]
    put big (150):        {"ok":false,"reason":"pinned-over-budget","evicted":[]} -> ["d","draft","e"] (the draft is never evicted)
    pin draft2 (60):      {"ok":true,"evicted":["d"]}
    pin draft3 (60):      {"ok":true,"evicted":["e"]} -> ["draft","draft2","draft3"]
    
    budget of 1000 but the origin's quota is only 330 (stored size counts keys and field names too)
    after a, b, c:        ["a","b","c"], usage 315 of 330
    put d:                {"ok":true,"evicted":["a"]} -> ["b","c","d"], usage 315
    put huge (400):       {"ok":false,"reason":"quota","evicted":[]} -> ["b","c","d"]

    What the lab does not show. No browser: it never touches window.indexedDB or a real StorageManager. Real IndexedDB reports failures as events, has indexes, cursors and the blocked and versionchange handshake between tabs, none of which is modelled. Every size and limit is made up, estimate() here is exact where real browsers approximate it, the rule that grants persist() is invented, and "least recently used" uses a counter, not time.

    In practice: an order desk that lost its drafts

    NOTE

    This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.

    The situation

    A field-sales app lets representatives browse a product catalogue and write order drafts offline, then send them when they have a connection. Both live in one IndexedDB database. The catalogue is downloaded again whenever the app starts online. Drafts are deleted after a successful send.

    Starting architecture

    Figure 5. Starting point: everything in one best-effort database

    Starting architecture: catalogue and unsent drafts share one best-effort IndexedDB database with no budgetOrder desk to IndexedDB (reads, writes); IndexedDB to Order API (sync later)Order desk: browser appOrder deskbrowser appIndexedDB: catalogue + draftsIndexedDBcatalogue +draftsOrder API: sends draftsOrder APIsends draftsreads, writessync later

    How to read this: the only copy of an unsent draft lives in storage the browser may clear, and nothing limits how much of it the catalogue uses.

    Options considered

    Option What it fixes What it costs Risk
    Bounded cache, pinned drafts, request persist() The cache cannot crowd out drafts Cache policy to write and test The browser may still refuse
    Also send each draft on save Short loss window A draft endpoint Offline drafts stay local

    The decision

    Field Decision record
    Context Unsent drafts are the only copy of the user's work, in storage the browser may delete.
    Decision Budget the catalogue with LRU eviction, pin drafts, request persistent storage after the first draft and show the result, send drafts on save when online, and detect an empty database on start-up.
    Consequences, good The cache cannot crowd out drafts, a refused write degrades gracefully, and a loss is visible.
    Consequences, bad More code, an approximate budget, and a prompt in some browsers.
    Revisit when The server can hold drafts at all times, or the catalogue outgrows the budget.

    Rollout and verification

    1. Test the failure paths first: a write over quota, a pinned record that does not fit, an upgrade that throws, an origin that reopens empty.
    2. Ship the budget and the pin, and record the persist() result and estimate() values so the real distribution is known.
    3. Add the start-up check, and test it by deleting the site's data by hand.

    The 2 a.m. failure

    A few representatives on older phones open the app after a long gap and find an empty catalogue and no drafts. Error tracking shows nothing, because nothing failed: the origin was deleted while the phone was short of space, and the app opened a new empty database (illustrative).

    First three checks: (1) did the app start at database version 0; (2) was persistence requested and what did it return; (3) had the drafts reached the server. Mitigation: refetch the catalogue and tell the user that unsent drafts on this device are gone, with the time of the last successful send. Follow-up: send drafts on save, record the persist() result, and warn when estimate() shows most of the quota used.

    Architect's notes

    • Treat IndexedDB as a cache with a good memory, not a database of record. Anything the user cannot recreate belongs on a server too.
    • Budget on purpose: decide what may be evicted, what must not be, and what happens when pinned data alone does not fit.
    • Handle QuotaExceededError as a normal outcome, and detect absence with a marker checked at start-up.

    Common mistakes

    • Assuming a value comes back unchanged when it holds a function or a class instance.
    • Treating estimate() as exact, or as a promise that a write will fit.
    • Keeping the only copy of precious data in best-effort storage.
    • Handling the quota error but not the empty database after eviction.

    Key takeaways

    • IndexedDB stores structured values by key, asynchronously and in transactions; structured clone keeps Date, Map and Set and rejects functions.
    • The schema changes only in the upgrade; a lower version is a VersionError; a failed upgrade is rolled back.
    • A transaction commits all its changes or none; an error or abort() rolls back, and quota exhaustion aborts it.
    • Storage is per origin; the limit is the browser's and estimate() only approximates it.
    • Under pressure the browser deletes the least recently used best-effort origin whole; a persistent one is skipped, if the browser granted it.
    • Design for a refused write (handle, free space, retry) and an empty database (detect, rebuild, tell the user).

    Practice exercises

    Exercise 1 — Starter (45 min): Change one quota in src/demo.ts, predict which transaction then fails, and run it.

    Exercise 2 — Intermediate (2 hours): Add a version 3 upgrade to the shop database that migrates price strings to a cents number inside the upgrade transaction, with tests for databases written by version 1 and by version 2.

    Exercise 3 — Advanced (half day): Make RecordCache.put refuse a record larger than the whole quota without attempting the write, and say whether that helps with a refused write or an evicted origin.

    In this course:

    The lessons on browser storage options and on cookies and Web Storage cover the other stores.

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments