Every few months someone on the team proposes “just switch the CDN to AVIF” and every few months the same three questions come back. How much smaller is it really? What does it cost the CPU and the heap? And will it survive contact with the long tail of devices we still support?
This post answers those with numbers where I could produce them honestly, and with reasoning where I could not. Then it wires the result into Coil, because a format decision that never reaches your image loader is only a slide in a deck.
What is measured and what is not. File sizes below are measured: I encoded five photographs with libjpeg, libwebp and libavif and tuned each encoder until it hit the same structural similarity score. Decode timings are measured too, but on desktop builds of the codecs, so read them as ratios and nothing more. Memory is computed from first principles, which is all it needs to be. Section 1 ends with a benchmark harness so you can replace my ratios with your own devices.
1. File size, decode time, memory
Bytes: compare at equal quality, never at equal “quality = 80”
A quality slider means something different in every encoder. Setting JPEG to 80 and AVIF to 80 and comparing byte counts tells you about the sliders, not the formats. The fair comparison fixes a perceptual target and lets each encoder find its own setting.
I used SSIM of at least 0.95 against the uncompressed original and binary-searched the quality parameter per format and per image.
Three things stand out:
- AVIF averaged roughly 39% smaller than JPEG, WebP roughly 24% smaller. The portrait and still life images saw AVIF cut the file nearly in half.
- The gap is content dependent. The noisy star field kept AVIF only about 21% below JPEG, because grain is expensive to encode in any codec. Photos with large smooth regions and soft gradients are where AVIF earns its keep.
- Your catalog is not my five images. If your feed is mostly product shots on flat backgrounds, expect something different. Run the same experiment on a few hundred of your own assets before you quote a percentage to anyone.
Decode time: the price of those savings
Smaller files are not free to open. AVIF is built on a video codec, and decoding it generally takes more work per pixel than baseline JPEG.
On the desktop codecs I used, WebP averaged about 1.3 times JPEG and AVIF about 1.4 times, with enormous spread: AVIF ranged from slightly faster than JPEG to roughly twice as slow, depending on the image. Two cautions before you act on this:
- Android’s decoders are not these decoders. The platform may use different libraries and, on some devices, hardware paths. The ratios say “AVIF is not magic and not catastrophic”, nothing more.
- Decode cost is paid once per cache miss, off the main thread. A 1.4x decode penalty buys you a 39% smaller download. On a congested mobile network the transfer saving dwarfs the extra decode milliseconds. On a repeat visit the decoded bitmap often comes straight from the memory cache and the format is irrelevant.
Here is a harness to get real numbers. It uses the Jetpack Microbenchmark rule so warmup, clock locking checks and statistics are handled for you:
@RunWith(AndroidJUnit4::class) @SdkSuppress(minSdkVersion = 28) // ImageDecoder class FormatDecodeBenchmark { @get:Rule val benchmarkRule = BenchmarkRule() private val assets = InstrumentationRegistry.getInstrumentation().context.assets @Test fun jpeg() = decode("sample.jpg") @Test fun webp() = decode("sample.webp") @Test @SdkSuppress(minSdkVersion = 31) // platform AVIF decoding fun avif() = decode("sample.avif") private fun decode(name: String) { val bytes = assets.open(name).use { it.readBytes() } benchmarkRule.measureRepeated { val source = runWithTimingDisabled { ImageDecoder.createSource(ByteBuffer.wrap(bytes)) } val bitmap = ImageDecoder.decodeBitmap(source) { decoder, info, _ -> // Decode at the size you actually render, not the size on disk. decoder.setTargetSize(info.size.width / 2, info.size.height / 2) } runWithTimingDisabled { bitmap.recycle() } } } } Run it on at least one low-end device and one flagship, on a physical phone, not an emulator. Add a fourth case per format that decodes at full size, because that is what a sloppy loader will do in production.
Memory: the format is not what you pay for
This is the most common misconception in the whole debate. Once an image is a Bitmap, it is a grid of pixels, and the grid does not remember whether it came from a JPEG or an AVIF. Memory is dimensions times bytes per pixel.
A 12 megapixel photo is about 46 MiB at the default 4 bytes per pixel, regardless of format. The format changes the transient native buffers during decode, not the bitmap you keep afterwards. So the memory work is about decoding to the size you need:
@RequiresApi(28) fun decodeForSlot(source: ImageDecoder.Source, slotWidth: Int, slotHeight: Int): Bitmap { require(slotWidth > 0 && slotHeight > 0) { "Measure the slot before decoding" } return ImageDecoder.decodeBitmap(source) { decoder, info, _ -> val ratio = maxOf( info.size.width / slotWidth.toFloat(), info.size.height / slotHeight.toFloat(), ).coerceAtLeast(1f) decoder.setTargetSize( (info.size.width / ratio).roundToInt().coerceAtLeast(1), (info.size.height / ratio).roundToInt().coerceAtLeast(1), ) } } Failure modes worth knowing about:
- The wide-gamut surprise. A 10-bit or HDR source can end up in a wider pixel configuration than the 8-bit default. The extreme case in the chart, 8 bytes per pixel, doubles the cost of a normal bitmap. If you start serving higher bit depth AVIFs, log
bitmap.configandbitmap.allocationByteCountin a debug build before you see it in your out-of-memory dashboards. - Decoding at disk size “because the cache will hold it”. The cache holds what you decode. A format that makes the download cheaper makes it tempting to ship larger source images, and a large source decoded without a target size is the fastest route to an out-of-memory crash on a 3 GB device.
- Assuming smaller file means smaller bitmap. It does not. A 40 KB AVIF and a 400 KB JPEG of the same dimensions are the same size in the heap.
2. Library support
Support is where AVIF’s wins get tested against reality. Here is the map.
The short version:
- JPEG is universal and needs no thought.
- WebP is safe for anything you will realistically support. Lossy has been there since API 14, lossless and transparency since API 18, and animation through the platform
ImageDecodersince API 28. - AVIF decodes natively from API 31. Below that you ship your own decoder or you ship something else.
- Encoding is asymmetric.
Bitmap.compresshas a JPEG, PNG and WebP vocabulary but no AVIF entry. Generate AVIF in your build or server pipeline, not on the device.
On the library side, Glide added animated AVIF support through the platform animated decoder on Android 12 and later in 4.15. For Coil, the default path delegates to the platform decoder, so static AVIF on API 31 and up works with no extra wiring, while older releases need a bundled decoder such as the community avif-coder project, which advertises API 24 and up.
Do not assume animated AVIF from that. Coil’s animated decoder ships in coil-gif, but in the source I checked (3.0.0 and the current development branch) it recognizes HEIF sequences by the msf1, hevc or hevx major brand, not AVIF's avis. Expect a typical animated AVIF to need your own decoder factory, and test with your files.
Failure modes that do not appear in a support matrix
- Valid file, wrong pixels. One real-world report against Coil describes AVIF images rendering with a green line on Android 12 and later. The Coil maintainer reproduced the artifact by decoding with
ImageDecoderdirectly, with no Coil involved, and concluded it was a platform decoder problem and advised filing it with the Android graphics team. The lesson is not "avoid AVIF". It is that a decoder that accepts your file has not proven it decoded it correctly, so budget a visual QA pass on real devices and keep a server-side kill switch. - The cache that serves the wrong bytes. A CDN that returns different formats for one URL must send
Vary: Accept. If your cache key ignores that, an AVIF response gets served to a client that cannot decode it. This one bites after a CDN migration, when someone forgets the config. - The bundled decoder tax. Shipping a native AVIF decoder for the pre-31 tail adds native libraries to every APK or split. Weigh that against simply serving WebP to those devices.
- No decoder, no fallback. If the response says
image/avifand nothing can decode it, the user sees a blank slot. You need an explicit retry path, which the next section builds.
The loop those failure modes live in
Most of the problems above sit on one path: client advertises, edge chooses, client decodes, and something must catch a decode that cannot happen.
A negotiation policy you can unit test
Keep the “what can this device decode” logic in one small pure function so you can test it without a device:
enum class WireFormat(val mime: String) { Avif("image/avif"), Webp("image/webp"), Jpeg("image/jpeg"), } object FormatPolicy { /** Best first. JPEG is always the floor. */ fun supported( sdk: Int = Build.VERSION.SDK_INT, hasBundledAvifDecoder: Boolean = false, ): List<WireFormat> = buildList { if (sdk >= Build.VERSION_CODES.S || hasBundledAvifDecoder) add(WireFormat.Avif) add(WireFormat.Webp) add(WireFormat.Jpeg) } fun acceptHeader(formats: List<WireFormat>): String = formats.joinToString(separator = ",") { it.mime } + ",*/*;q=0.5" } Build.VERSION_CODES.S is API 31, which is where platform AVIF decoding begins, so the intent reads clearly at the call site.
3. Loading with Coil
Here is how the pieces connect in Coil 3. The format decision is made on the wire, and Coil’s job is to fetch bytes, find a decoder that claims them, and handle failure gracefully.
Wire it up once, in the Application
class PhotoApp : Application(), SingletonImageLoader.Factory { private val formats = FormatPolicy.supported() private val okHttp: OkHttpClient by lazy { OkHttpClient.Builder() .addInterceptor { chain -> val request = chain.request().newBuilder() .header("Accept", FormatPolicy.acceptHeader(formats)) .build() chain.proceed(request) } .build() } override fun newImageLoader(context: PlatformContext): ImageLoader = ImageLoader.Builder(context) .components { add(OkHttpNetworkFetcherFactory(callFactory = { okHttp })) // Pre-31 AVIF: register a bundled decoder here, gated by API level. // Decoders you add run before Coil's built-in ones, so without // `if (Build.VERSION.SDK_INT < 31)` it also takes over on 31+. // Check the plugin README for the exact factory and package // for your Coil major version. } .memoryCache { MemoryCache.Builder().maxSizePercent(context, percent = 0.20).build() } .diskCache { DiskCache.Builder() .directory(context.cacheDir.resolve("images").toOkioPath()) .maxSizePercent(0.02) .build() } .build() } Note the network module is a separate artifact in Coil 3 (coil-network-okhttp), which is a common "why is my image blank after upgrading" moment.
Put the format in both cache keys
Coil’s disk cache is keyed by the request’s cache key, not by headers. If the same URL can yield different formats depending on Accept, a key that ignores the format can return stale bytes after you change the policy, for instance when you flip a remote flag that stops requesting AVIF. The memory cache has the same problem within a running process: its key ignores Accept too, so it can keep serving an already-decoded AVIF. Make the format part of both keys, and make sure the Accept header follows the same flag as the key:
@Composable fun FeedImage(url: String, modifier: Modifier = Modifier) { val best = remember { FormatPolicy.supported().first() } AsyncImage( model = ImageRequest.Builder(LocalPlatformContext.current) .data(url) .diskCacheKey("$url#${best.name}") .memoryCacheKey("$url#${best.name}") .crossfade(true) .build(), contentDescription = null, contentScale = ContentScale.Crop, modifier = modifier, ) } Coil sizes the decode to the composable’s measured size by default, which is exactly the memory discipline from section 1. Do not override it with Size.ORIGINAL unless you have a reason you can defend.
A real fallback, not a hope
When a decoder fails, the result is an error and the slot stays empty. An interceptor can catch that and retry once with a safer URL:
class FormatFallbackInterceptor( private val fallbackFor: (url: String) -> String?, ) : Interceptor { override suspend fun intercept(chain: Interceptor.Chain): ImageResult { val result = chain.proceed() if (result !is ErrorResult) return result // No connection is not a decode failure; a second request will not help. // Don't filter every IOException: ImageDecoder's DecodeException is one. when (result.throwable) { is UnknownHostException, is ConnectException, is SocketTimeoutException -> return result } val url = chain.request.data as? String ?: return result val safer = fallbackFor(url) ?: return result val retry = chain.request.newBuilder() .data(safer) .diskCacheKey("$safer#fallback") .memoryCacheKey("$safer#fallback") // else it inherits the original's key .build() return chain.withRequest(retry).proceed() } } Register it with .components { add(FormatFallbackInterceptor(::toJpegUrl)) }. The interceptor API has changed between Coil majors (proceed takes the request in 2.x, not in 3.x), so compile against your version rather than pasting blindly.
Failure modes in the loading layer:
- Retry loops. The fallback must produce a URL that cannot itself fall back again. Return
nullfor URLs already marked as fallbacks, or one bad asset becomes an infinite request storm. - Letting a flag outlive its cache. If remote config disables AVIF for a bad batch of devices, the already-cached AVIF bytes stay on disk under the old key. Putting the format in both keys fixes this because the new request misses and refetches.
- Hardware bitmaps and later pixel access. Coil may use hardware-backed bitmaps by default where it is safe. If you later read pixels for palette extraction or blur, request software explicitly for that path with
allowHardware(false). - Decode errors swallowed by
errorplaceholders. Anerrordrawable hides the cause. Attach a listener in debug builds and logErrorResult.throwable, so a format-specific decode failure shows up in your logs rather than only in a user's screenshot.
What I would ship
- Photographic content, API 31 and up: AVIF, generated server-side, with an
Acceptheader andVary: Acceptat the edge. - Photographic content, below API 31: WebP. Skip the bundled AVIF decoder unless the pre-31 audience is large enough to justify the native size.
- UI art, icons, anything with alpha: lossless WebP. The decode cost is predictable and support is universal.
- JPEG: keep it as the floor the pipeline can always fall back to, never as the first choice for new photographic assets.
- Always: decode to the size you render, put the format in the cache keys, keep a server-side switch for bad devices, and measure on your own hardware with the harness above.
The honest summary is that AVIF is a real win on bytes, a modest cost on decode, and neutral on memory, provided you do not let smaller files talk you into decoding bigger images. The risk is not the format. It is the unobserved path between “the CDN sent AVIF” and “the user saw correct pixels”.
Sources
- Coil issue 2419: green line in AVIF images on Android 12+
- avif-coder: AVIF and HEIF decoding for Android (API 24+)
- Glide 4.15.0 release notes: animated AVIF on Android 12+
- Coil documentation: GIF and animated image decoders
- Investigation of platform AVIF encoding: no AVIF entry in Bitmap.CompressFormat
⚡ Stop Guessing What Your Coroutines Are Doing — Learn the Model Underneath
If you write Kotlin for Android or the JVM backend, it’s easy to use launch and async without knowing why your code cancels, leaks or crashes the way it does. I highly recommend "Kotlin Coroutines in Practice: Structured Concurrency, Cancellation, and Flow — Volume 1: Foundations to Flow." It explains the mental model behind coroutines step by step: how a suspend function becomes a state machine, how a Job tree owns every piece of work, why cancellation is cooperative, and how errors travel. It covers everything from your first runBlocking to StateFlow and SharedFlow. Each chapter adds a feature to a running news-reader app and ends with pitfalls, key takeaways and exercises with worked solutions.
- E-book: Available on Google Play
- Kindle Edition: Available on Amazon
- Topmate: Available on Topmate
- Also available in Paperback & Hardcover











