Mobile Design Rounds
Case studyAndroidiOS15 min read

Design an image loading library (Android and iOS): caches, decoding and cancelling

Last reviewed . Drafted with AI assistance. Checked against official documentation where noted (how this is checked). Part of: The five-step method · Staff-level guide.

Build it. The database schema, API, code and platform limits for an image loading library are on a separate page: Build it: an image loading library on Android and iOS (20 min read).

How to read this. This page is a 45-minute round (the length I assume), in the order I would spend it. The code, HTTP caching and Swift version are in the build guide. The follow-up questions are my reconstruction of challenges that public prep material reports (offline, retries, stale data, battery, rollout), not transcripts of real rounds.

TL;DR. A loader spends memory only on pixels the screen shows. Each cache key (the label of a saved image) uses source, size and transforms, never the URL alone. Identical requests share one download (coalescing). It stops when its last waiter (a caller still waiting) leaves. I decode smaller than the file. The target (the view) decides if a late result is wanted. A download is canceled only when no caller waits for it. I would adopt Coil or Glide on Android and Nuke or Kingfisher on iOS. On iOS, ImageIO does the downsampling and a canceled Task or a reused cell does the cancelling.

Patterns in this round.

  • Facade and adapter (a request object and one loader hide caches, decoding and cancelling)
  • Coalescing (identical requests share one download)
  • Scoped owner (one loader is shared by every screen)
  • Layered cache (memory, then disk, then network, with keys made of source, size and transforms)

More in design patterns in mobile rounds.

Free: one follow-up round a week. A short interview question with a weak and a strong answer, by email. You also get the cheat sheet.

1. Scope and constraints (minutes 0 to 4)

In short: Small scope, four phone behaviors, everything else for later.

A prompt I would expect: "Design an image loading library for our apps. Other teams will use it to show pictures in lists." I ask five questions, each with a default:

  • Library or one app's loader? A library.
  • Sources? HTTPS URLs.
  • Tied to views? Yes, one call for each ImageView or Compose image.
  • Formats? JPEG, PNG and WebP.
  • Offline? Seen images still show.
In scopeOut of scopeLeft for later
Load into a view or Compose targetVideo thumbnailsAnimated GIF and WebP
Placeholder, error image, cancel, invalidateImage editingSigned or private URLs
Memory cache and disk cacheUploadPrefetch driven by a feed
Decode sized to the slot

Four phone behaviors matter here:

What the phone doesRequirement at riskDeep dive
Recycles rows as the user scrolls (reuses row views)A row never shows the image of another rowRecycling (4.1)
Gives the app a small memory budget that can changeBounded memory, no out-of-memory kills (the system ends the app)Decode and memory (4.2)
Ends the app process without warningNo corrupt cache entry after the process endsFailures (5)
Runs on a battery and a data planNo duplicate downloads, no wasted workCache key (2), recycling (4.1)

Your decision. Scope question: "Animated images, signed URLs (links with an expiring code) and feed prefetch (loading images early) too." Which do you keep?

First idea, and why it fails. Say yes to all three. Then time runs out on frames, tokens and prefetch. The key and the decode are never drawn.

What I would say. None yet. Each one changes the core: decode, the cache key, or who starts requests. I reject taking them on silently. Each returns as a follow-up.

Say this. "Static images over HTTPS, two cache tiers, sized decode, cancellation. Animated formats, signed URLs and feed prefetch wait for later. Tell me if you want one earlier."

The follow-up question I expect:

"The feed team needs prefetch next quarter."

I build the core first. Prefetch returns as follow-up 3.

45-minute plan

MinutesStepShown by the endCut if behind
0 to 4Scope and constraintsIn and out list, phone behaviorsFewer questions
4 to 14Data and contractsRequest object, cache key, two tiersThe numbers
14 to 22Client structureOne app-wide loader, who owns whatOne line per layer
22 to 40Make the hard part workRecycling and coalescing, then decode and memoryMemory in three sentences
40 to 45Break it, ship it, roll it backTop failures, the flag (an off switch), what I would watchTwo failures and the flag

2. Data and contracts (minutes 4 to 14)

In short: Key by source, size and transforms, so one URL never gives the wrong pixels.

Your decision. What identifies a cached image: the URL, the URL plus a version, or everything that changes the output pixels?

First idea, and why it fails. Use the URL as the key. It fails when the app shows one URL at two sizes.

  • For example, the app caches a 100 px thumbnail. Then the hero asks for that URL and gets a blurry copy.
  • Or a small slot holds a huge bitmap.
  • A rounded version and a plain version collide in the same way.

What I would say. The memory key is source, width, height and transforms. Glide's caching page lists the same parts: model, size, transformation, options and an optional signature (Glide: caching).

The disk cache may key more loosely. It stores original bytes and decodes again per size, trading CPU for disk. I reject the URL alone.

The follow-up question I expect:

"The server replaces an avatar at the same URL."

The cache serves old pixels until it evicts them. I want a content hash in the URL or a signature in the key, not file deletion. With hashed URLs, the new URL is the invalidation.

The contract fits in four lines:

  • A request is an immutable value object (it never changes): source, size, transforms, placeholder, error image and target.
  • enqueue returns a handle. Call cancel() on it when the row is recycled (sketch).
  • execute waits without blocking a thread and returns a typed result. It is for callers without a view and for tests.
  • trimMemory(level): the host app forwards system memory signals and owns the memory budget.

Arithmetic only where it changes a choice. Every input is my assumption:

AssumptionArithmeticWhat it settles
A 2048x1536 image at 4 bytes a pixel2048 x 1536 x 4 is about 12 MB. At sample size 4 (4 times smaller each way) it is 512 x 384 x 4, about 0.75 MBDecode to the target size, not the file size
A 32 MB memory cache, 360 px square thumbnails, 1080x810 heroesA thumbnail is about 0.5 MB, so about 64 fit. A hero is about 3.5 MB, so about 9 fitLimit the cache by bytes, not by number of entries
Eight decodes at once during a fling (a fast scroll)Full size: 8 x 12 MB is 96 MB. Downsampled: 8 x 0.75 MB is 6 MBCap parallel decodes, downsample

3. Client structure (minutes 14 to 22)

In short: One app-wide loader owns both caches and the shared downloads.

Your decision. Who owns the loading work and the caches? A screen or its ViewModel (the object that holds a screen's state)? A loader per feature? Or one injected loader (made once and handed to the code that needs it)?

First idea, and why it fails. The screen owns it: each fragment or ViewModel starts its own loads. But the data layer guide says work tied to a screen is canceled when the user leaves it (data layer). So a download dies with its screen, even when the next screen wants the same image.

What I would say. Use one injected loader for the app's whole life. It owns both caches and the scope (where background tasks run) for shared downloads. A request belongs to its target, which cancels it on detach.

ViewModels only expose URLs. The UI layer calls enqueue. The UI layer page says to keep logic that uses UI types such as Context in the UI, not in the ViewModel. I reject a loader per feature, and a service, since nothing here runs without a screen.

The follow-up question I expect:

"Screen A leaves while screen B wants the same image."

The download runs in the injected scope, as the data layer guide shows for work that outlives the screen. It stops when its last waiter leaves.

requestcheckmissfirstmisshitbytesstoreView targetCompose / UIImageViewImageLoaderrequest + keyMemory cachedecoded, byte-boundedIn-flight mapkey to shared jobDecode + transformdownsample, off mainDisk cacheencoded bytes, LRUNetworkconditional requestsView targetCompose / UIImageViewrequestImageLoaderrequest + keycheckMemory cachedecoded, byte-boundedmissIn-flight mapkey to shared jobDecode + transformdownsample, off mainhitDisk cacheencoded bytes, LRUmissNetworkconditional requests

More links

  • In-flight map to Disk cache: first
  • Network to Decode + transform: bytes
  • Decode + transform to Memory cache: store
Image loader pipeline: memory cache, then an in-flight map that coalesces identical requests, then disk cache, then network; decoded bitmaps return to the memory cache.

The loader sits at the edge of the UI layer, with its own network and disk code as data sources. This placement is my inference from the UI layer and data layer pages. Two rules:

  • The host owns lifecycle and memory budget. The library takes both as inputs.
  • Callers depend on an interface, so tests can swap in a fake fetcher.
Row 1Row 2Row 201 Memory cachea decoded bitmap is delivered at oncemiss2 Join: one shared downloadthe other rows wait for the same jobfirst caller only3 Disk cacheencoded bytes: a hit only needs a decodemiss4 Network
Four steps, in order: memory, join, disk, network. Identical requests are joined into one shared download, so twenty rows cost one download.

4. Make the hard part work (minutes 22 to 40)

In short: Cancel old requests, share identical downloads, decode only what the slot needs.

4.1 Recycling and coalescing (minutes 22 to 33)

Your decision. Row 3 asked for an image. The user scrolled, and the view now shows row 40. Row 3's response arrives. What happens to it?

First idea, and why it fails. The callback captured the view, so it sets the bitmap on that view. But the view was rebound, so row 40 shows the picture of row 3. Canceling nothing is worse: a fling loads images for rows no one will see.

What I would say. A target holds one current request, so a rebind or recycle detaches the old one from the view.

  • If other rows wait for the same download, it continues. The result skips the old view but goes into the cache.
  • If that row was the only waiter, the download is canceled.
  • If the bytes have already arrived, they go into the cache. I reject throwing away a finished result.

Say this. "Each target holds its current request. A finished request delivers its picture only if it is still current. Otherwise the bitmap goes into the cache. Identical requests share one download, keyed like the cache. It is canceled only when its last waiter leaves. On iOS, the cell cancels in prepareForReuse, and a SwiftUI row cancels with .task(id:)."

The follow-up question I expect:

"Twenty rows ask for the same avatar, and one scrolls away."

One download and one decode serve all twenty rows. The download counts its waiters, so canceling one row leaves the other nineteen loading.

  • A failed fetch fails only the callers on that key.
  • I found no Coil or Glide page that confirms this joining of running requests, so it is my design.

The follow-up after that: "The signed URL expired before the image loaded. Or the bytes arrive cut off."

  • An expired signature is not a permanent rejection. Servers differ in the status code, so I would check what the CDN returns. I do not write a negative entry for it.
  • I ask the host app for a fresh URL once, then fetch again. The key uses the stable part of the URL, so the cache still matches.
  • A renamed file can still be too short. If the server sends a length, I compare it before the rename.
  • If a decode fails, I remove that cache entry and show the error image. I retry once, not in a loop.

If I am interrupted mid-answer, I answer first, then say where I was:

Say this. "Yes, if a result still arrives, it goes into the cache, so scrolling back can cost nothing. Back to where I was: twenty rows asking for one avatar share one download, and one scrolls away."

Target viewshows row 3now row 40Memory cachescroll backcosts nothingNetworkrow 3 is slow131 Row 3 asks for its image.2 The view is reused for row 40: one request.3 A late result fills the cache, not the view.
A row that scrolled away cancels its old request. A late picture never reaches the reused view, but it still fills the cache.

4.2 Decode and memory (minutes 33 to 40)

Your decision. A 4000 by 3000 photo (example sizes) must fit a 360 px slot. Decode and scale, or sample while decoding? And what happens when the system wants memory back?

First idea, and why it fails. Decode the full image, then scale it down. A decoded bitmap costs width times height times bytes per pixel, whatever the file size. Section 2: eight parallel full decodes pass the whole cache.

What I would say. Sample while decoding (decode at a half, quarter or eighth of the size) and limit the cache by bytes. I reject decode-then-scale. I also reject weak or soft references for the cache. The cache bitmaps guide says they are not recommended.

The load large bitmaps guide shows the pattern: read the bounds (the image size) before decoding. The main thread draws the screen, so decode runs elsewhere. A trim signal is a system request to free memory.

Say this. "I read the bounds first, then decode at a power-of-two sample size, off the main thread, with a cap on parallel decodes. The cache is sized in bytes. On a trim signal, I evict everything once the app is a background candidate, and I halve the cache when the UI is hidden. On iOS I use ImageIO with a max pixel size, and I drop most of the cache on a memory warning."

The follow-up question I expect:

"What does the host forward on a memory signal?"

Only two trim levels are not deprecated: background candidate and UI hidden. Since API 34, apps are not notified of the other five (AOSP source).

  • Newer Android versions also add app memory limits that depend on device RAM (behavior changes).
  • My suggestion, not documented advice: log the app exit reason next to the out-of-memory metric. The build guide has the detail.

4.3 Where iOS changes the design

Same pipeline. Swift sketch: build guide.

  • The downsample uses ImageIO (Apple's image decoding framework) with a maximum pixel size, not UIImage. The app never builds the full-size bitmap. Size in pixels, not points.
  • The memory signal is one warning with no level. The NSCache cost limit is not strict, so I set one and still clear on warning.
  • To handle reuse, cancel in prepareForReuse (the method that runs when a cell is reused), and check the request token before assigning.
  • In a collection view with prefetching, also cancel in cancelPrefetchingForItemsAt.
  • In SwiftUI, load in .task(id: url). SwiftUI cancels the task when the id changes or the row goes away.
  • AsyncImage is fine for a simple screen. It gives you no control over cache size, decode size or shared downloads. A list-heavy app should use a loader.
  • On iOS 15 and later, UIImage.preparingThumbnail(of:) is a short way to get a downsampled image. ImageIO gives more control.
  • HTTP caching on iOS comes from URLCache. Your decoded-image cache sits on top of it.

5. Break it, ship it, roll it back (minutes 40 to 45)

In short: Name the failures. Ship behind a flag. Keep the old loader until the new one is proven.

FailureUser seesData holdsRecovery
Out-of-order deliveryThe right image on every rowCache entry for the late resultThe view drops the result. The cache keeps it if the bytes arrive
Twenty rows, one imageOne download, and all rows fillOne shared download and a waiter countThe last waiter cancels the download
Low storage or evictionPlaceholder, then a reloadByte-limited cachesTrim on host signals. If disk writes fail, serve uncached
Process dies mid-writeImage reloads, no broken pictureA temp file, renamed when the write succeedsThe app never reads the partial file
Signed URL expired, or bytes cut offPlaceholder, then the image or an error imageStable key, no negative entry for expiryOne fresh URL from the host. Drop an entry that fails to decode
A private image returns 401Placeholder, then the imageNo negative entry for the 401Refresh the login once, then load again
Permanent rejectionError image, tap to retryA short-lived negative entry (a failure note)Retry on tap. No retry for a 404
Old app version meets new server contractOld builds keep workingKeys that include the size parameterThe CDN (content delivery network) keeps answering old URL shapes

Rows without a source link are my design choices. Sources are in Further reading.

At release:

  • A Play staged rollout (release to a growing share of users) can be halted. That stops new users receiving the build, but users who already have it keep it (Play help).
  • The new loader ships behind a remote flag (a server setting that turns it off). That is the only rollback that reaches installed apps. The old loader stays in the app during the migration.
  • A flag cannot undo a new on-disk cache format once files are rewritten. My rule: version the cache folder and rebuild from the network instead of migrating.

Say this. "I cannot pull back a bad build that users already installed, so the rollback is the flag plus a fixed build. I would watch time to first pixel, hit rates, peak bitmap memory and out-of-memory kills. I left out animated formats, signed URLs and feed prefetch."

6. Follow-ups that change a constraint

In short: Six practice prompts, hardest last.

Not claims about what interviewers ask. Each changes a constraint.

  1. A fling through ten thousand images in a few seconds. Strong: cancel everything scrolled past, cap parallel decodes and downloads, give visible loads priority, and let the byte-limited cache evict. Weak: "a bigger cache."
  2. Add animated GIF and WebP. Strong: decode frame by frame into a drawable, never a list of full bitmaps. Pause off screen. Ship it as an optional module. Weak: decoding every frame up front.
  3. The feed wants to prefetch. Strong: prefetch is a request with no target, and it has lower priority than visible loads. Skip it on cellular data or in data saver mode. Cancel it when scrolled past. See the news feed case. Weak: prefetching fifty images with no conditions.
  4. Image URLs carry an expiring signature, and some images are private. Strong: key on the stable part of the URL plus a version, and keep the token out. Give each user a separate cache space for private images and clear it on logout. This is my advice, not a library guarantee. Weak: using the full URL as the key, shared across accounts.
  5. After release, out-of-memory kills rise for some users. Strong: switch the flag to the old loader, halt the staged rollout, compare peak bitmap memory with the control group, and ship a fix. Weak: "roll back the release."
  6. The CDN changes its resize parameter. Strong: old versions stay in the field, so the CDN answers both shapes. Weak: assuming that everyone updates.

7. What changes by level

In short: Staff level adds build versus adopt and a rollout plan.

These levels are my own reading, drawn from vendor and prep material (courses and books), not any company's rubric.

  • Mid-level: two cache tiers, background decode, placeholder and error image, and canceling loads for recycled views. I want to hear: "A late result must not land on a reused row."
  • Senior: keys with size and transforms, coalescing with waiter counting, downsampling, trim handling and bounded concurrency. I want to hear: "The key changes whenever the output pixels would change."
  • Staff: the library as a product: stable API, memory budgets, metrics, flags, build versus adopt and a migration plan (staff guide).

As I read it, the levels differ in who raises the problem: the interviewer, the candidate, or the candidate with a rollout plan.

Common weak answers. Ten minutes on CDN architecture when the question was about the phone. Only the happy path. Naming Glide or Coil without saying what breaks otherwise. A cache keyed by URL only. No flag to turn the loader off. They come from public prep material, not a dataset.

Staff answer: the decision and the rollout

Decision: adopt, do not build. Use Coil or Glide on Android and Nuke or Kingfisher on iOS, behind a thin internal wrapper. The wrapper owns cache budgets, key rules and metrics.

The READMEs list these features, and none explain how they work:

  • Coil: downsampling and automatic cancellation.
  • Nuke: caches plus request coalescing.
  • Kingfisher: a hybrid cache and cancelable downloads.

Alternative: write our own, and own every hard case here.

Revisit trigger: a measured need that the wrapper cannot express, such as a custom key rule. Another trigger is a screen where the library's cost shows in profiles. For the build-versus-adopt pattern, see the native vs cross-platform decision guide.

Rollout: ship the wrapper first. Move one team's screens at a time behind the section 5 flag. Keep the old path until a screen runs cleanly for a full release cycle.

Guardrail: the crash-free rate and out-of-memory kills must not get worse than in the control group.

What I read and what is my view: the library descriptions were read from the project READMEs. The migration order, metrics, guardrails and level signals are my opinion.

Test yourself

In short: Seven questions from this case. Answer each one out loud first, then open the answer.

1. Why is the URL alone a bad cache key?

The same URL can be shown at two sizes or with different transforms. A cached 100 px thumbnail would come back blurry in a hero slot. The memory key is source, width, height and transforms.

2. The server replaces an avatar at the same URL. How do users get the new one?

Put a content hash in the URL, or a signature in the key. Then the new URL is the invalidation. Without that, the cache serves old pixels until it evicts them.

3. Row 3 asked for an image, the view now shows row 40, and row 3's answer arrives. What happens?

A target holds one current request, so a rebind detaches the old one. A late result is never set on the view. If the download still finishes, for example because another row waited for it, its bytes go into the cache. If row 3 was the only waiter, the download is canceled.

4. Twenty rows ask for the same avatar and one scrolls away. What happens?

One download and one decode serve all twenty. The download counts its waiters, so canceling one row leaves the other nineteen loading. This joining is my design, not a documented library behavior.

5. Why not decode the full image and then scale it?

A decoded bitmap costs width times height times bytes per pixel, whatever the file size. A 2048 by 1536 image is about 12 MB, and eight at once is 96 MB. Decode at a smaller sample size, off the main thread, and limit the cache by bytes.

6. Why one app-wide loader and not one for each screen?

Work tied to a screen is canceled when the user leaves it. A download would die with its screen even when the next screen wants the same image. One injected loader owns both caches and the scope for shared downloads.

7. On iOS, how do you stop a reused cell from showing the wrong image?

I cancel the request in prepareForReuse and check the request token before I assign the image. With prefetching I also cancel in cancelPrefetchingForItemsAt. In SwiftUI I load in .task(id: url), which cancels when the id changes or the row goes away.

Further reading (official docs)

Words on this page (16)
Bitmap
A picture in memory that is ready to draw. A big bitmap uses much memory.
Cache key
The label of a saved item. Two requests with the same key share one saved copy.
CDN
Content delivery network. Servers close to users that keep copies of your files.
Crash-free rate
The share of sessions that end without a crash.
Decode
To turn an image file into pixels that the screen can draw. It takes time and memory.
Downsampling
Loading an image at a smaller size than the file. This uses much less memory.
Hash
A short code made from the bytes of a file. Apps compare the codes to see if two files are the same.
Host app
The app that contains an SDK. You write the SDK, and another team writes the host app.
Main thread
The thread that draws the screen. If slow work runs on it, the screen freezes.
Prefetch
Loading data before the user asks for it. It makes scrolling smooth, but it can waste data.
Remote flag
A setting that the server can change. It can turn a feature on or off without a new release.
Request coalescing
Joining duplicate requests into one. All callers share the same download.
Rollback
Going back to the old behavior after a problem. A build on a user's phone cannot be taken back, so teams use a kill switch.
Staged rollout
A release to a growing share of users, not to everyone at once. It limits the harm of a bad release.
Stale data
Saved data that may be out of date. The app should show how old it is, or refresh it.
ViewModel
A class that holds the state of one screen. It survives a screen rotation.

Read the whole glossary

Verification notes (last reviewed 14 Oct 2026)
  • I read 11 official pages: the Android UI-layer and data-layer guides, the bitmap guides, Glide's caching page, the ComponentCallbacks2 source, the Android 17 behavior changes, the Play staged-rollout help and the Nuke and Kingfisher READMEs.
  • Documented: the memory arithmetic for bitmaps, the key parts that Glide lists, weak and soft references being not recommended, and which trim levels are not deprecated.
  • Documented: halting a Play staged rollout leaves the build on devices that already have it.
  • From READMEs only: Coil lists downsampling and cancelling, Nuke lists caches and coalescing, Kingfisher lists a hybrid cache and cancelable downloads. The READMEs do not explain how they work.
  • My design, not from docs: sharing one download between rows with a waiter count, the rule on late results, the rollout plan and the level advice.
  • My suggestions: sizing the cache from the device memory class, and logging the app exit reason next to the out-of-memory metric.
  • Not verified: that Coil or Glide join running requests the way I describe, the Apple phased release page, and the loader's place in Android's layers (my inference).
  • The follow-up questions are my reconstruction of challenges that public prep material reports. They are not transcripts of real rounds.

Questions or corrections?

Add them to the discussion thread for this case on GitHub. To post, you need a free GitHub account. What you write there is public and follows GitHub's terms. Good answers are added to this page.

Keep reading

Get the free one-page cheat sheet

One page: the five steps, a 45-minute time plan and two checklists. Print it or keep it on your phone.

We email you the cheat sheet after you confirm your address. You can also open it now from the Start here page. You also get a short email each week with a follow-up round, and a note when a new case is published. Unsubscribe any time. Privacy.