Design an image loading library
Why it matters
- Decoding images at full size is one of the most common causes of
OutOfMemoryErrorand scroll jank in Android apps. - "Design an image loading library" (Coil, Glide, Picasso) is a classic mobile system design interview question because it touches memory, disk, network, threading, and lifecycle at once.
- Interviewers use it to test your knowledge of bitmap memory, caching layers, and request cancellation in scrolling lists.
- Knowing how Coil and Glide work inside helps you configure them well and debug them when images flicker, reload, or use too much memory.
The simple explanation
- A restaurant kitchen.
- The pantry is the Disk Cache (large, slow access).
- The fridge is the Memory Cache (medium, fast access).
- The chef's cutting board is the Bitmap in memory (immediate use).
- If the cutting board is too small, the chef runs out of space and crashes.
How does an image loading library work on Android? A request for a URL at a target size checks a memory cache of decoded bitmaps first, then a disk cache of downloaded bytes, and only then the network. Bytes are decoded on a background thread, downsampled to the view size, put in the memory cache and shown. Requests for the same key share one load, and requests for views that scroll off screen or leave composition are cancelled. Coil and Glide both follow this shape.
- Memory cache: an LRU cache of decoded
Bitmapobjects, sized in bytes as a fraction of the app's memory budget (ActivityManager.getMemoryClass()orRuntime.getRuntime().maxMemory()), smaller on low-RAM devices. The key includes the size and transformations, because a 200 px thumbnail and a full-screen image are different bitmaps. - Disk cache: stores the downloaded, still-compressed bytes (JPEG, PNG, WebP) so a restart does not re-download. Glide can also cache the transformed, resized result.
- Decoding pipeline: never decode a 4000x4000 photo into a 200x200 view. Read the dimensions first with
inJustDecodeBounds, then decode withBitmapFactory.Options.inSampleSize(a power of two), or letImageDecoder(API 28+) scale to a target size.
| Layer | Data type | Speed | Persistence |
|---|---|---|---|
| Memory cache | Decoded Bitmap | Fastest, no decode | Lost when the process dies |
| Disk cache | Compressed file bytes | Needs a read and a decode | Survives restarts, can be evicted |
| Network | Response body stream | Slowest, costs data | None |
To avoid leaks and wasted work, each request is tied to its target: Coil cancels a request when its View is detached or its Lifecycle is destroyed, and Compose's AsyncImage cancels when it leaves composition. When a list cell is recycled for a new URL, the old request must be cancelled so a late result does not land in the wrong cell.
Notes
- Downsample to the target view size while decoding (
inJustDecodeBoundsplusinSampleSize, orImageDecodertarget size). A 4000x3000 ARGB_8888 bitmap takes about 48 MB; at 500x375 it takes about 0.75 MB. - Use
android.util.LruCachewithsizeOfreturningbitmap.allocationByteCount, so the limit is in bytes, not entries. - Deduplicate in-flight requests: keep a map of key to
Deferredso two cells asking for the same image share one download and decode. - Cancel requests when the target view is detached, recycled, or leaves composition.
- Do network and disk I/O on an I/O dispatcher and decode on a background dispatcher; inject the dispatchers so tests can control them.
Bitmap.Config.HARDWARE(API 26+) keeps pixels only in graphics memory, which saves memory and upload time, but the pixels cannot be read or drawn on a softwareCanvas. Coil uses hardware bitmaps by default where allowed.- Respond to memory pressure through
ComponentCallbacks2.onTrimMemoryby trimming the memory cache. CatchingOutOfMemoryErroris not a strategy. - Bitmap pooling (reusing bitmaps through
inBitmap) is how Glide reduces allocation churn. Coil dropped pooling in version 2, since bitmap pixels live in native memory from Android 8.0. Mention it only where it applies.
Code example
The core of a small loader: a byte-sized memory cache, in-flight deduplication, and downsampled decoding. The network and disk layers sit behind fetchBytes.
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.util.LruCache
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import kotlinx.coroutines.withContext
class MiniImageLoader(
private val fetchBytes: suspend (url: String) -> ByteArray, // disk cache, then network
private val decodeDispatcher: CoroutineDispatcher, // inject Dispatchers.Default
maxMemoryCacheBytes: Int, // for example maxMemory() / 8
) {
private val memoryCache = object : LruCache<String, Bitmap>(maxMemoryCacheBytes) {
override fun sizeOf(key: String, value: Bitmap): Int = value.allocationByteCount
}
private val scope = CoroutineScope(SupervisorJob() + decodeDispatcher)
private val inFlight = HashMap<String, Deferred<Bitmap>>()
// Call from the main thread; suspends until the bitmap is ready
suspend fun load(url: String, reqWidth: Int, reqHeight: Int): Bitmap {
val key = "$url@${reqWidth}x$reqHeight"
memoryCache.get(key)?.let { return it }
val deferred = inFlight.getOrPut(key) {
scope.async {
val bytes = fetchBytes(url)
decodeSampled(url, bytes, reqWidth, reqHeight).also { memoryCache.put(key, it) }
}
}
try {
return deferred.await()
} finally {
if (deferred.isCompleted && inFlight[key] === deferred) inFlight.remove(key)
}
}
private suspend fun decodeSampled(url: String, bytes: ByteArray, reqWidth: Int, reqHeight: Int): Bitmap =
withContext(decodeDispatcher) {
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds) // reads the header only
val options = BitmapFactory.Options().apply {
inSampleSize = sampleSize(bounds.outWidth, bounds.outHeight, reqWidth, reqHeight)
}
BitmapFactory.decodeByteArray(bytes, 0, bytes.size, options)
?: throw IllegalArgumentException("Cannot decode $url")
}
// Largest power of two that keeps both sides at or above the requested size
private fun sampleSize(width: Int, height: Int, reqWidth: Int, reqHeight: Int): Int {
var sample = 1
while (width / (sample * 2) >= reqWidth && height / (sample * 2) >= reqHeight) sample *= 2
return sample
}
}sizeOfreturns bytes, so the cache limit means "this many bytes of bitmaps", whatever their size.- The key includes the requested size: the same URL at thumbnail size and full-screen size are different cache entries.
inFlightmakes a second caller for the same keyawait()the first load instead of starting another one.loadis called from the main thread and the map is only touched there, so a plainHashMapis safe; a failed load is removed so the next call retries.- When the caller's coroutine is cancelled (the view was detached), its
await()stops. A real library also cancels the shared load once no caller is waiting, which is what Coil and Glide do.
Run the idea in plain Kotlin
// A byte-sized LRU cache: LinkedHashMap with accessOrder = true moves an entry to the end on every get
class ByteLruCache(private val maxBytes: Int) {
private val map = LinkedHashMap<String, Int>(16, 0.75f, true)
var sizeBytes = 0
private set
fun get(key: String): Int? = map[key]
fun put(key: String, bytes: Int) {
map.put(key, bytes)?.let { sizeBytes -= it }
sizeBytes += bytes
while (sizeBytes > maxBytes) {
val eldest = map.entries.iterator().next() // least recently used
map.remove(eldest.key)
sizeBytes -= eldest.value
println(" evicted " + eldest.key)
}
}
}
// Same rule as BitmapFactory: largest power of two that keeps both sides >= the target
fun sampleSize(w: Int, h: Int, reqW: Int, reqH: Int): Int {
var s = 1
while (w / (s * 2) >= reqW && h / (s * 2) >= reqH) s *= 2
return s
}
fun main() {
val s = sampleSize(4000, 3000, 500, 375)
val full = 4000 * 3000 * 4
val sampled = (4000 / s) * (3000 / s) * 4
println("inSampleSize=" + s + ", bytes " + full + " -> " + sampled)
val cache = ByteLruCache(maxBytes = 100)
cache.put("a", 40)
cache.put("b", 40)
println("get a -> " + cache.get("a")) // a becomes most recently used
println("put c (40)")
cache.put("c", 40) // evicts b, not a
println("get b -> " + cache.get("b"))
println("size=" + cache.sizeBytes)
}Expected output:
inSampleSize=8, bytes 48000000 -> 750000
get a -> 40
put c (40)
evicted b
get b -> null
size=80
In production
- Users reported dropped frames when scrolling a large image grid, and cells briefly showing another item's image.
- A hand-written loader decoded bitmaps on the main thread, and callbacks for recycled cells still set their image when they finished late.
- Moved decoding to a background dispatcher and downsampled to the cell size, so each decode is smaller and faster.
- Cancelled the previous request when a cell is bound to a new URL, and checked before setting the bitmap that the cell still wants that URL. In the end the team replaced the hand-written loader with Coil, which does both.
- The app crashed with
OutOfMemoryErrorafter users opened and closed image-heavy screens many times. - LeakCanary showed destroyed activities kept alive by pending image callbacks that held a strong reference to an
ImageView, and the bitmap cache was a plainHashMapthat never evicted.
- Tied each request to the view's lifecycle so it is cancelled when the view is detached or the screen is destroyed, which drops the reference.
- Replaced the
HashMapwith anLruCachesized in bytes as a fraction ofActivityManager.getMemoryClass(), and trimmed it inonTrimMemory.
Common mistakes
- Loading full-resolution bitmaps. A single camera photo can take tens of megabytes when decoded, so a grid of them quickly runs out of memory. Downsample to the target view size with
inSampleSizeorImageDecoder. - Ignoring the lifecycle. A callback that outlives its screen leaks the view and the activity behind it, or sets an image on a cell that now shows something else. Cancel requests when the view is detached or recycled.
- Using a simple HashMap for caching. The cache grows until the app crashes. Use
LruCachewithsizeOfin bytes. - Caching by URL only. A thumbnail and a full-size version of the same URL then overwrite each other, or a small bitmap gets stretched. Put the size and transformations in the memory cache key.
- Decoding on the Main thread. Blocks the UI thread, causing skipped frames and ANRs. Always decode on a background thread.
- Not deduplicating requests. If the same image is requested multiple times simultaneously, you waste bandwidth and CPU. Use a request map to join pending requests.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“How would you prevent an OutOfMemoryError when loading many images?”
“What happens if a user scrolls very fast through a list of images?”
“How do you decide the size of your memory cache?”
“How would you handle a situation where the same image URL is requested multiple times at once?”
Quiz
Which property of BitmapFactory.Options is used to reduce memory usage by loading a smaller version of an image?
What is the primary purpose of an LruCache in an image library?
If you are getting OutOfMemoryError while scrolling a list, what is the most likely cause?
Which layer of the cache is persistent across app restarts?
0 of 4 answered
Mini task
Task: Build a byte-sized LRU cache with deduplication
- Create a class
SimpleImageCache(maxBytes: Int)backed byLinkedHashMap<String, Int>(16, 0.75f, true), where the key isurl@WIDTHxHEIGHTand the value is the decoded size in bytes. - Implement
get(key): Int?, which also marks the entry as recently used (access order does this for you). - Implement
put(key, bytes)that evicts the least recently used entries until the total fits inmaxBytes. - Add
suspend fun load(url: String, w: Int, h: Int): Intthat checks the cache, then calls a fakefetch(adelay(100)that counts calls), and storesw * h * 4bytes. - Keep a
MutableMap<String, Deferred<Int>>of in-flight loads so two concurrentloadcalls for the same key share one fetch.
Done condition: reading an entry before inserting a new one protects it from eviction, and launching two load calls for the same key at once makes the fake fetch run only once.