In a mobile art-museum app, what path does one artwork image request take from memory cache to network, and where does coalescing happen?
answer
- two tiers, two different things
- pixels ready to draw versus encoded bytes
- key on URL plus target size
- one in-flight entry per key
- empty the decoded tier first under pressure
basics
~20 sCheck the memory cache of decoded images by URL and target size; on a miss, read the encoded bytes from disk, else fetch them once, sharing any in-flight request; decode downsampled off the UI thread, then fill both tiers.
solid answer
~50 sFirst the memory cache, keyed by URL plus target pixel size, holding decoded pixels ready to draw: a hit is shown immediately, with no placeholder flash. On a miss, the work leaves the UI thread. The disk cache, keyed by URL, holds encoded bytes; a hit skips the network but still pays a decode. Before starting new work, the pipeline checks an in-flight map: a second cell asking for the same URL at the same size joins the running job, and a different size shares the one download and adds only a decode. The bytes are written to disk, decoded downsampled on a bounded worker queue, stored in the memory cache and delivered on the UI thread. When the OS signals memory pressure, the decoded tier is emptied first, because the disk tier can rebuild it.
code
pseudocode · 24 linesfunction load(url, size, consumer): # called on the UI thread
key = url + "@" + size
pixels = memoryCache.get(key)
if pixels != null:
consumer.show(pixels)
return
consumer.showPlaceholder()
job = inFlight.get(key)
if job != null:
job.consumers.add(consumer) # coalesced: no new fetch, no new decode
return
job = newJob(key)
job.consumers.add(consumer)
inFlight.put(key, job)
runInBackground:
bytes = diskCache.get(url)
if bytes == null:
bytes = fetchOncePerUrl(url) # joins a download already running for url
diskCache.put(url, bytes)
pixels = decodeQueue.run(decodeSubsampled(bytes, size))
memoryCache.put(key, pixels)
onUiThread:
inFlight.remove(key)
for c in job.consumers: c.show(pixels)go deeper
Recall the order: memory, then disk, then network. Know that memory holds images ready to draw and disk holds the downloaded files.
Walk the path step by step, say why the two keys differ, and show where the in-flight map lets two requests share one download and one decode.
Cover the races and the edges: who removes the in-flight entry, what happens on a corrupt disk entry, how the decode queue is bounded, and what to release when memory pressure arrives.
Treat the pipeline as one shared component every surface uses, so caches, coalescing and memory-pressure handling are decided once rather than reinvented per screen.
## Two tiers that hold two different things An image pipeline usually has two caches, and the most common mistake is to treat them as one cache in two places. They hold different representations of the same picture: | Tier | Holds | Keyed by | Survives the process ending? | Cost on a hit | |---|---|---|---|---| | **Memory cache** | Decoded pixels at the size a view needs | URL plus target pixel size | No | Almost nothing: draw it | | **Disk cache** | Encoded bytes - the downloaded file, or in some designs a smaller re-encoded copy | URL | Yes, until evicted or purged | A file read plus a decode | | **Network** | The image on the server | URL (and request headers) | - | Latency, data, then a decode | The memory tier exists to make scrolling back instant; it is lost whenever the app's process ends, including when the system ends it in the background. The disk tier exists to avoid the network; reading from it is slower than memory and unpredictable, so it happens on a background thread. Because the memory tier holds decoded images, the **same URL can have several memory entries**, one per target size - a grid thumbnail and a detail-page image are different entries over one disk entry. ## The path of one request, step by step 1. **Memory lookup, on the UI thread.** The cell asks for an artwork's URL at its pixel size. A hit is shown in the same frame, so a cell scrolled back into view never flashes a placeholder. 2. **Placeholder and hand-off.** On a miss the cell shows its placeholder and the request moves to background work. 3. **In-flight check.** If a job for the same key is already running, the new requester attaches to it and nothing new starts. 4. **Disk lookup.** If the encoded bytes are on disk, skip the network. 5. **Network fetch.** Otherwise download the bytes - once per URL, however many sizes are waiting - and write them to disk. 6. **Decode.** A bounded decode queue turns the bytes into pixels subsampled to the target size. 7. **Fill and deliver.** Store the result in the memory cache, remove the in-flight entry, and deliver to every attached requester on the UI thread. ## Coalescing: one fetch, one decode **Coalescing** means that identical requests share work instead of repeating it. It matters in a museum grid because the same artwork can appear twice on one screen (a featured row and the grid), and because fast scrolling re-requests images that are still loading. - **Decode jobs coalesce by URL plus size.** Two cells wanting the same artwork at 360 pixels share one decode and one result. - **Downloads coalesce by URL alone.** A 360-pixel cell and a full-width header share one download and one disk entry, then run two decodes. - **The in-flight map holds requesters, not just a flag.** Each job keeps a list of waiting consumers, so one cell leaving does not cancel the work another still needs. - **The map lives where it is safe to touch.** Keeping it on one thread, or behind one lock, avoids two jobs starting for the same key in a race. This is the image pipeline's own map. A general networking layer's rules for deduplicating ordinary API calls are a separate decision. ## Threads and concurrency - **Disk reads, downloads and decodes all run off the UI thread.** Only the memory hit and the final hand-over run on it. - **The decode queue is bounded.** Decoding is CPU- and memory-heavy, so a small number run at once; how many is a measured choice per device class, not a fixed figure. - **Visible requests go first.** Work for on-screen cells is ahead of work for cells prepared ahead of the viewport. ## When the OS signals memory pressure Both platforms tell a running app when memory is low and ask it to give memory back; one platform's guidance names images that already have an on-disk copy, and so can be reloaded later, as what to let go. For this pipeline: - **Empty or shrink the decoded tier first**, keeping at most what is on screen, because every entry can be rebuilt from the disk tier without the network. - **Pause or slow the decode queue** so new large allocations do not land during the pressure. - **Leave the disk tier alone.** It does not occupy memory, and keeping it makes the rebuild cheap. How large each tier should be on a given phone, and what it evicts in ordinary use, is the cache-sizing question; this one is what an image cache holds and the order a request walks through it.
- Two cells show the same artwork at different sizes; what is shared and what is not?They share the download and the disk entry, both keyed by URL, so the bytes cross the network once. They do not share the decode or the memory entry, which are keyed by URL plus target size: each size is decoded from the same bytes. A pipeline may decide to serve a slightly larger cached decode to a slightly smaller view, but never a small one to a large view.
- Why serve a memory-cache hit synchronously but a disk hit asynchronously?A memory hit is ready pixels: showing it in the same frame means a cell scrolled back into view never flashes its placeholder. A disk hit needs a file read, whose time is unpredictable, and then a decode, which is CPU-heavy. Doing either on the UI thread stalls scrolling, so both go to background work and the cell shows its placeholder briefly.
- What should the pipeline do if a decode fails because the bytes on disk are corrupt?Treat the disk entry as bad: delete it, refetch the bytes from the network once, and decode again. If the fresh bytes also fail, deliver an error state to the waiting cells and remember the failure for a while, so a fast scroll does not keep refetching the same broken image.
- A disk-cache hit can be drawn directly, without decoding it again.
- Key the memory cache by URL alone, whatever size the view needs.
- Two cells asking for the same image should each start their own download.
- Under memory pressure, clear the disk cache first because it is the largest.
- Reading the disk cache on the UI thread is fine because local files are fast.