skip to content

Caching & Local Storage

A mobile app keeps data in memory, on disk and in a local store, and must decide what to evict, when to refetch and how to upgrade the schema. Interviewers probe it in nearly every mobile design.

on this pageshow

explore

questions

21

In a mobile city-guide app, what are the memory and disk caches each for, and in what order is a venue looked up?

level: juniorimportance: must knowfreq 52%

answer

  1. what each tier survives
  2. the screens in use right now
  3. a relaunch with no network
  4. cheapest tier asked first
  5. a disk hit moves up a tier

basics

~20 s

The memory tier holds parsed data for the screens in use and dies with the process; the disk tier survives relaunches but the OS may purge it. Lookups try memory, then disk, then network, copying hits upward.

solid answer

~50 s

Memory is the fast tier: parsed venue objects for the screens the user has open or just left, served with no I/O or parsing, but gone when the process ends. Disk is the tier that survives a relaunch: serialized venue pages, search results and hours, so a cold start or a dead zone still shows something; a hit costs a read and a parse, and if it lives in the OS's purgeable cache folder the OS may delete it when storage is low, so nothing there may be the only copy. A lookup goes **memory, then disk, then network**: a disk hit is parsed and promoted into memory, and a network response goes into memory for the screen and is written to disk in the background. Each tier has its own byte budget; whether a hit is fresh enough to show is a separate staleness policy.

code

pseudocode · 15 lines
pseudocode
function get_venue(id):
    entry = memory_tier.get(id)
    if entry exists:
        return entry
    bytes = disk_tier.read(id)            # may be missing: the OS can purge it
    if bytes exists:
        entry = parse(bytes)
        if entry is valid:
            memory_tier.put(id, entry)    # promotion
            return entry
        disk_tier.remove(id)              # corrupt or old format: treat as a miss
    entry = network.fetch_venue(id)       # fails when offline: the screen shows its offline state
    memory_tier.put(id, entry)
    in background: disk_tier.write(id, serialize(entry))
    return entry

go deeper

for a junior

Recall the two tiers by what they survive: memory dies with the process, disk survives a relaunch but can be purged by the OS. Then recite the lookup order: memory, disk, network.

for a middle

Explain the cost of each hit: memory skips I/O and parsing, disk costs both, a miss costs the radio. Show how a disk hit is promoted and how a response fills both tiers.

for a senior

Show judgment about what may live in a disposable tier at all: nothing the user created, nothing the product promises offline unless it is kept outside the purgeable folder, and a separate budget per tier.

for a principal

Treat the tiers as a cost ladder tuned per kind of data across a team's apps: which data earns memory, which earns disk, and which should never be cached on a shared device.

A mobile app that shows venue pages, search results and saved lists keeps copies of that data so it does not have to ask the network every time. On a phone those copies live in two **tiers** in front of the network, and each tier exists because of something the other cannot do. ## Why a phone keeps two tiers The **memory tier** is a map inside the app's own process: parsed venue objects ready to bind to a screen. A hit costs no I/O and no parsing, which is what makes going back to the venue the user just left feel instant. Its weakness is that it lives and dies with the process. When the OS ends the app in the background, which both native platforms do routinely to reclaim memory, the memory tier is gone, so it never helps a cold start. The **disk tier** is files, or rows in a small database, holding the serialized form of the same data. It survives the process ending, so a relaunch in a basement café still has something to show. A hit costs a file read and a parse: slower than memory, but far faster and cheaper than the radio. Its weakness is that it is disposable by design. When it sits in the OS's **purgeable cache folder**, as a cache normally should, the OS may delete it when storage runs low, so nothing there may ever be the only copy of anything. The **network** is the origin. It is the slowest tier, costs battery and data, and may be missing altogether. | Tier | Holds | Survives | Cost of a hit | Who can empty it | |---|---|---|---|---| | Memory | parsed objects for the screens in use | nothing beyond the process | almost none | the app's eviction; the process ending | | Disk | serialized entries for recent and likely screens | relaunch and process death | a file read plus a parse | the app's eviction; the OS when storage is low | | Network | the source data | not applicable | latency, radio time, data | not applicable | ## The lookup path A read walks the tiers from the cheapest to the most expensive: 1. Ask the **memory tier**. On a hit, return the object. 2. On a miss, ask the **disk tier**. A missing or unreadable file is simply a miss, never an error. On a hit, parse it, put the parsed object into the memory tier (**promotion**) and return it. 3. On a miss there too, ask the **network**. Put the response into the memory tier for the screen, and write it to the disk tier in the background so the next relaunch can use it. 4. If the network is unavailable, the screen shows its offline state instead of an endless spinner. Writing to disk off the main thread is safe precisely because the disk tier is a cache: if the process dies before the write lands, the next launch misses and refetches, and nothing is lost. Data the user created is a different matter and never belongs in this path at all. ## Each tier has its own budget The tiers differ in size by an order of magnitude or more, so each gets its own byte ceiling and evicts on its own. A venue evicted from memory is usually still on disk; a venue evicted from disk is gone until the network brings it back. Once the app has been used for a while, the disk tier holds many more entries than the memory tier. Sizing those ceilings from the device's budget, and choosing what each throws out first, is the next question an interviewer asks. ## What goes wrong when the tiers are confused - **Treating the disk tier as permanent**, and keeping the only copy of a saved list there, loses that list the day the OS purges the folder. - **Treating the memory tier as if it survived a background kill** produces an empty screen after a relaunch, where a disk hit would have shown the last known venue page. - **Skipping the memory tier** makes every back-navigation pay a file read and a parse, which a 2 GB phone shows as a visible delay. - **Seeing caches as an offline feature only** misses their main job while online: speed, battery and data. - **Deleting the disk copy after promotion** throws away the one tier that would have survived the next kill. ## What this question leaves to other parts of the design - Whether a cached entry is still **fresh** enough to show, and when to revalidate it, is a separate staleness policy decided per screen; a disk hit is not automatically stale. - Image caches, decoding and downsampling have their own pipeline and their own budget. - What deserves the **persistent store** rather than a disposable cache is a store-choice question; the short version is that anything the user made goes there. In an interview, the graded answer names both tiers by what they survive, walks the lookup order with promotion, and says out loud that the disk tier can vanish.

  • Why not skip the memory tier and read venue pages from disk every time?
    Every screen visit would pay a file read and a parse, so going back to the venue the user just left costs a visible delay on a slow 2 GB phone. The memory tier exists to make that return instant. Skipping the disk tier instead would lose everything at each relaunch, so the cold start would wait for the network.
  • Should a network response be shown before it has been written to disk?
    Yes. Show it once it is parsed and write it to disk off the main thread. The disk write is a cache fill, not a durability step: if the process dies first, the next launch misses and refetches. Data the user created is different; it belongs in the persistent store, never in a cache write that may not land.

Papers on your desk, a filing cabinet in the room, and an archive across town: the desk is cleared when you leave, the cabinet is still there tomorrow unless the building manager empties it to free space, and the archive always has the original but takes a trip.

  • The disk cache is permanent, so a saved list can live only there.
  • The memory cache is still there after the OS kills the app in the background.
  • Reading from disk costs about the same as reading from memory on a modern phone.
  • Caches only matter offline, so an online app barely needs them.
  • Once an entry is promoted to memory, its disk copy can be deleted.
open as a page

In a mobile sports app, a fan opens a league table cached an hour ago in a crowded stadium: what should the screen show, and when?

level: juniorimportance: must knowfreq 56%

basics

~20 s

Show the cached table at once and refetch it in the background (stale-while-revalidate). Fresh rows replace old ones in place without moving the scroll; if the refetch fails, the cached table stays, labelled with its age, with a retry.

open as a page

In a mobile language-learning app, which data deserves the persistent store, and which can live in a disposable cache?

level: juniorimportance: must knowfreq 52%

basics

~20 s

Persist anything that is the only copy (grades, progress, streaks, settings) or that the user needs offline (downloaded lessons, the course list); cache only what exists for speed and can be re-fetched with nothing lost.

open as a page

On a 2 GB phone, how would you size a city-guide app's memory and disk caches, and what would each evict first?

level: middleimportance: must knowfreq 50%

basics

~20 s

Size each tier from a stated device budget: memory as a share of the app's memory budget, disk as an app-set ceiling cut when storage is low. Bound both in bytes; evict least recently used, and age out untouched entries.

open as a page

In a mobile sports fixtures-and-results app, how would you set different staleness rules for the fixture list, the league table and a match screen?

level: middleimportance: must knowfreq 54%

basics

~20 s

Give each screen its own freshness window and ceiling from how fast its data changes and what a wrong value costs: fixtures hours, tables minutes, a live match seconds. Tighten windows by match state, and revalidate conditionally.

open as a page

In an offline language-learning app, which store kind would you choose for flashcards, progress, settings and lesson audio, and why?

level: middleimportance: must knowfreq 58%

basics

~10 s

Choose by each data's queries and size: cards and progress in an embedded relational database indexed by due date, settings in a key-value store, and audio as files that a database row points to.

open as a page

In a health-diary app's on-device database, how does a user who jumps from a three-year-old build reach the current schema safely?

level: middleimportance: must knowfreq 44%

basics

~20 s

The database stores its own schema version. At open the app compares it with the build's version and runs each single-step migration in order, 3 to 4, 4 to 5 and on, each committed with its version bump.

open as a page

In a health-diary app whose entries exist only on the phone, what should happen when an on-device schema migration fails or finds no path?

level: seniorimportance: must knowfreq 38%

basics

~20 s

The failed step's transaction rolls back, leaving the file at its last good version. The app never wipes device-only entries: it stops the crash loop, explains, offers an export and waits for a fix. Only restorable data may be rebuilt destructively.

open as a page

In a health-diary app, when an update changes the local data's shape, which on-device data must be migrated and which may simply be dropped?

level: juniorimportance: should knowfreq 35%

basics

~20 s

Data that exists only on the phone (diary entries, unsent edits, the user's settings) must be migrated. Copies the server or the app bundle can rebuild, like a downloaded reference list, may be dropped and refetched.

open as a page

When the OS signals memory pressure, what should a city-guide app's in-memory cache release first, and what should it keep?

level: middleimportance: should knowfreq 42%

basics

~20 s

Release every cached entry no visible screen is using, starting with those that have a disk copy, pause prefetching, and lower the tier's ceiling for a while. Keep what visible screens hold; dropping it frees nothing.

open as a page

In an offline language-learning app, should the local database store each server response whole or normalize it into records, and why?

level: middleimportance: should knowfreq 48%

basics

~20 s

Normalize data that screens query or the device edits into records keyed by stable ids, so one write updates every screen observing it; store whole only what is read whole, replaced whole and never edited on the device.

open as a page

In a city-guide app's caches on a shared family tablet, one person's recently viewed venues appear after another signs in: how should the caches be partitioned and wiped?

level: seniorimportance: should knowfreq 45%

basics

~10 s

Partition every cache tier by account, including the response cache and search history; drop responses that land after a switch; on logout make that account's partition unreachable at once, then delete it.

open as a page

In a city-guide app whose disk cache lives in the OS's purgeable cache folder, what must the design guarantee for the morning the folder is found empty?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Every disk-cache read must be optional: a missing file is a miss, the cache's index and byte total are rebuilt rather than trusted, and nothing the user made, or the app promised offline, lives only in that folder.

open as a page

In a mobile sports app, after a fan follows a team, which cached entries must change, and how do you keep every screen consistent?

level: seniorimportance: should knowfreq 50%

basics

~20 s

Patch entries the device can compute, such as the followed-teams list and the follow button, at once; mark server-derived ones, such as the home fixtures, stale when the server acknowledges the follow, and discard any response requested before it.

open as a page

In a mobile sports app, when a fixture's kick-off time changes, should the server push the new data or only a signal that marks it stale?

level: seniorimportance: should knowfreq 46%

basics

~20 s

Usually a signal: the fixture's id and revision. The app marks dependent entries stale, refetches visible ones now and others when next shown, and keeps expiry because a signal can be delayed or never processed.

open as a page

In an offline language-learning app with 20,000 flashcards, the due-today screen gets slower as the deck grows; what is happening, and what fixes it?

level: seniorimportance: should knowfreq 44%

basics

~20 s

Without a matching index the query scans and sorts every card, and the observing screen repeats that after each grade; a composite index on deck and due time turns it into a short, already ordered range read.

open as a page

In an offline language-learning app, finishing a lesson updates its progress, the streak and fifty card due dates; how should the local store write them?

level: seniorimportance: should knowfreq 45%

basics

~20 s

Compute the changes first, then write them in one short transaction in one store, guarded by a unique completion id; a kill leaves all or none of it, and observing screens see one consistent change.

open as a page

In a health-diary app, an on-device migration must split a free-text dose field across three years of entries, taking 40 seconds on old phones; how do you run it?

level: seniorimportance: should knowfreq 31%

basics

~20 s

Split it: a fast schema step adds the new columns at open, then a resumable backfill converts rows in transactional batches with a committed progress marker while readers handle both shapes. Block with progress only if old rows cannot be shown.

open as a page

In a mobile sports app, a new release changes the shape of cached league-table entries: how do you stop it reading incompatible ones?

level: middleimportance: nice to knowfreq 36%

basics

~20 s

Put a data-shape version in each cache key or namespace and bump it when decoding changes incompatibly, so old entries read as misses and are refetched. Treat undecodable entries as misses, and delete stored entity tags with their bodies.

open as a page

In an offline language-learning app, lesson packs carry about 60 MB of audio each; how should the app store them and handle a nearly full phone?

level: seniorimportance: nice to knowfreq 36%

basics

~20 s

Keep audio as files in the app's persistent private storage with a database row per pack, mark a pack ready only after its file is complete, check free space before downloading, and let the learner see and remove downloads.

open as a page

In a health-diary app, what should an older build do when it opens an on-device database already migrated by a newer build, as after a rolled-back release?

level: seniorimportance: nice to knowfreq 22%

basics

~20 s

It must not migrate down or delete anything. Seeing a stored version above the highest it knows, it leaves the file untouched and asks for the current build, unless the newer build marked the file safe for older code.

open as a page