skip to content

Client Media Pipelines

Getting pictures and video onto a phone and back off it: decodes sized to the view, server-made variants, resumable uploads, feed video preload. Interviewers probe the memory and data each costs.

on this pageshow

explore

questions

20

In a mobile art-museum app, why do small artwork JPEGs in a grid crash older phones with out-of-memory, and what fixes it?

level: juniorimportance: must knowfreq 58%

answer

  1. what the decoder actually allocates
  2. width x height x bytes per pixel
  3. read the dimensions before the pixels
  4. decode to the view's pixels, not the file's
  5. decode off the UI thread

basics

~20 s

Memory follows pixels, not file size: a 4000 x 3000 photo decodes to about 48 MB at four bytes a pixel, however small the JPEG. Read the dimensions first; decode downsampled to the cell's pixels, off the UI thread.

solid answer

~50 s

A JPEG is compressed; to draw it, the decoder expands it into a pixel buffer of `width x height x bytes per pixel`. At the common four bytes a pixel, a 4000 x 3000 artwork photo needs about 48 MB however small its file, so fifteen visible cells decoded whole ask for roughly 720 MB and an older phone's per-app memory limit ends the app. The fix lives in the decode step: read the width and height from the file's header without allocating pixels, work out the cell's size in pixels (its layout size times the screen density), and ask the decoder for a subsampled image near that size - about 360 x 360 pixels, roughly 0.5 MB. Decode off the UI thread and cache the result at that size. Asking the server for a smaller variant helps as well, but the decode rule must hold whatever bytes arrive.

code

pseudocode · 8 lines
pseudocode
function decodeForView(file, viewWidthUnits, viewHeightUnits, density):
  header = readHeader(file)              # width and height only, no pixels
  targetW = viewWidthUnits * density
  targetH = viewHeightUnits * density
  factor = 1
  while header.width / (factor * 2) >= targetW and header.height / (factor * 2) >= targetH:
    factor = factor * 2
  return decodeSubsampled(file, factor)  # e.g. 4000 x 3000 with a 360 target -> 500 x 375

go deeper

for a junior

Remember the formula: width times height times four bytes. Say that a small file can still be a huge decoded image, and that the fix is decoding to the view's pixel size.

for a middle

Explain the steps: read the header without pixels, convert the view's layout size to pixels with the screen density, subsample during decode, and decode on a background thread.

for a senior

Do the arithmetic for a full screen of cells against an older phone's budget, point out that the peak allocation is what ends the app, and treat the decode as the guard even when the server sends variants.

for a principal

Frame it as a team rule: no decode larger than its view, enforced by a debug check and by peak-memory tests on the oldest supported phone, so every new surface inherits the guard.

## Why the file size misleads A JPEG, PNG, WebP or HEIC file is **compressed**: it stores a recipe for the picture, not the picture. Before anything can be drawn, the platform's image decoder expands that recipe into a **decoded image** - a buffer holding every pixel's colour. Its size depends only on the pixel dimensions and the pixel format: `decoded bytes = width x height x bytes per pixel` The common pixel format stores red, green, blue and alpha at one byte each, so **four bytes per pixel**. A 4000 x 3000 photograph is 12 million pixels, about **48 MB** decoded - whether its file weighs 300 KB or 6 MB. One platform's own guidance gives the same arithmetic: a 2048 x 1536 image takes about 12 MB decoded whole and about 0.75 MB when subsampled to roughly 512 x 384. ## The arithmetic for the museum grid Assume a three-column grid on a phone about 1,080 pixels wide, so each cell is about 360 x 360 pixels, and about fifteen cells on screen (both are this scenario's assumptions). | Decode choice | Pixels per image | Memory per image | Fifteen visible cells | |---|---|---|---| | Full 4000 x 3000 decode | 12,000,000 | ~48 MB | ~720 MB | | Power-of-two subsample to 500 x 375 | 187,500 | ~0.75 MB | ~11 MB | | Exact 360 x 360 target | 129,600 | ~0.52 MB | ~7.8 MB | The first row explains the crash. Every app has a memory limit that depends on the device; when the app passes it, the system ends the app, and an older phone's limit is far below 720 MB. Scrolling makes it worse: cells off screen may still hold their decodes in the memory cache, and several decodes can be in flight at once. ## Decode to the view, not the file The fix is to make the decode itself produce a small image, so the full-size buffer never exists: 1. **Read the header first.** Image formats record width and height near the start of the file, and decoders can report them without allocating the pixel buffer. 2. **Compute the target in pixels.** Take the view's layout size and multiply by the screen's density: a 120-unit cell on a 3x screen needs 360 pixels, not 120. 3. **Ask for a subsampled decode.** Many decoders shrink by power-of-two steps while decoding. Choosing the largest step that keeps both sides at or above the target, a 4000 x 3000 file with a 360-pixel target comes out at 500 x 375 - a little larger than the cell rather than smaller, which keeps it sharp. 4. **Decode off the UI thread.** Decoding is CPU-heavy work; on the UI thread it stalls scrolling. Hand the result back to the UI thread only to display it. 5. **Cache at the decoded size.** The memory cache stores the 0.75 MB result, keyed by the image's URL and the target size, so a second visit does not repeat the decode. ## What downsampling after the fact does not fix - **Scaling in the view changes only the drawing.** A view set to scale-to-fit still holds the full 48 MB buffer behind it. - **Decoding full size, then resizing, still peaks at 48 MB.** The peak allocation is what ends the app, and two or three such decodes in parallel are enough on an older phone. - **A bigger memory cache makes it worse.** It keeps more oversized buffers alive; the cure is smaller entries, not more room. - **Trusting the server is not a guard.** A smaller server variant reduces download size and decode time, but a wrong URL, an old cached response or a user-shared original can still arrive full size. ## Where this sits in the design Decoding to the view's size is the first rule of a client image pipeline, and interviewers use it to check whether a candidate thinks in pixels or in files. It pairs with two neighbouring decisions that belong elsewhere: which image sizes and formats the server offers and how the client asks for them, and how a scrolling list decides which rows to prepare ahead of the viewport. Whatever those decide, the decode step is the last line of defence: - **It reads the dimensions** before committing any memory. - **It refuses to build a buffer larger than the view needs**, in pixels, at the current density. - **It keeps the expensive work off the thread that draws the screen.** - **It caches what it produced**, at the size it produced it. A useful habit in a design round is to state the arithmetic out loud - pixels, times four, times the number of images alive at once - and compare it with a stated memory budget for the oldest supported phone. The number usually makes the argument for you.

  • Why not decode each artwork at full size once and keep only a scaled-down copy?
    Because the full decode still allocates the 48 MB buffer before the copy exists. Peak memory, not steady-state memory, is what ends the app, and with two or three decodes running in parallel an older phone passes its limit during the resize. Subsampling inside the decode means the large buffer never exists, and it also saves the CPU time of producing pixels that are thrown away.
  • The visitor rotates to landscape and the grid cells grow; what happens to the cached decodes?
    The memory cache is keyed by URL and target size, so a larger cell is a new key and needs a new decode. The bytes are still in the disk cache, so no download is repeated, only the decode. A pipeline may choose to reuse an entry within a small size tolerance to avoid churn, but it should not serve a much smaller decode to a much larger cell, which looks blurry.
  • How would you catch an oversized decode before a release ships?
    In debug builds, compare each decoded image's pixel size with its view's pixel size and log or flag any image more than an agreed factor larger - twice the view is a reasonable threshold to start from, as an assumption. Then measure peak memory while scrolling the grid on the oldest phone you support, because that device's limit is the one that matters.

  • A 300 KB JPEG costs about 300 KB of memory once it is on screen.
  • Setting the view to scale-to-fit shrinks the decoded image's memory.
  • The client can decode whatever arrives, because sizing images is the server's job.
  • Decoding on the UI thread is fine because the image files are small.
  • An out-of-memory crash in an image grid means the memory cache should be larger.
open as a page

In a fashion catalogue app's two-column product grid, how should the app work out which image size to request for each photo?

level: juniorimportance: must knowfreq 45%

basics

~20 s

Multiply the cell's layout size by the screen's density to get its size in pixels, then request the smallest server-made variant at least that wide. Never fetch the original: it wastes cellular data and decodes far larger than the cell.

open as a page

Why must a wedding-photography app keep its upload queue on disk, and what should each queued photo or video record?

level: juniorimportance: must knowfreq 46%

basics

~20 s

Because the OS may end a backgrounded app at any time, taking its memory with it. Each entry records the file's path, size and content hash, its state (waiting, uploading, committed, failed) and the server's upload address.

open as a page

In a mobile art-museum app, what path does one artwork image request take from memory cache to network, and where does coalescing happen?

level: middleimportance: must knowfreq 54%

basics

~20 s

Check 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.

open as a page

For a fashion catalogue app's photos, should the server offer fixed size buckets or any requested width, and how does each affect CDN hit rate?

level: middleimportance: must knowfreq 42%

basics

~20 s

Offer a short list of size buckets and have the app round up to the next one. Any-width resizing scatters each photo across many cache keys, so most requests miss, and an open resize endpoint invites abuse.

open as a page

When a wedding-photography app's 2 GB video upload drops at 80 %, why resume from the server's reported offset rather than its own byte count?

level: middleimportance: must knowfreq 53%

basics

~20 s

Bytes the phone sent are not bytes the server stored: some were buffered or in flight when the link died. The client asks the server how much it holds, then sends from that offset, reading the same unchanged file.

open as a page

In a children's educational-video app's vertical feed, why reuse a pool of video players instead of one per clip, and how would you size it?

level: middleimportance: must knowfreq 42%

basics

~20 s

Each player holds a decoder, buffers and a surface, and a phone runs only a few hardware decoders at once, so one per clip exhausts both. Reuse a small pool, typically playing, next and previous, capped by a measured memory budget.

open as a page

In a children's educational-video app's clip feed, how many upcoming clips would you preload, how much of each, and what cancels that on a flick?

level: middleimportance: must knowfreq 40%

basics

~20 s

Preload the opening seconds of the next two or three clips ahead and one behind, nearest first. A fast flick pauses new preloads and cancels requests for clips leaving that window, keeping bytes already in a capped disk cache.

open as a page

In a children's educational-video app's vertical feed of short clips, when should a clip start playing by itself, and when should it not?

level: juniorimportance: should knowfreq 34%

basics

~20 s

Autoplay only the one clip that is mostly on screen once scrolling settles, muted, and pause it when it leaves. Skip autoplay when a data-saving, battery-saving or reduce-motion setting, or a parent's choice, says no.

open as a page

In a mobile art-museum app on weak signal, what should an artwork's detail page show while its large image loads?

level: middleimportance: should knowfreq 42%

basics

~20 s

Show the grid's already-decoded thumbnail at once, in a frame of the final aspect ratio, then swap in the large image. A progressive JPEG can sharpen in passes on slow links; a failure shows retry, never an endless spinner.

open as a page

In a fashion catalogue app's photo grid, what should paint before the photos arrive, and what must the product API response carry for it?

level: middleimportance: should knowfreq 40%

basics

~20 s

Paint each cell from the product data already fetched: the photo's aspect ratio plus a dominant colour or a tiny encoded blur. In the gallery, show the grid's cached variant first, then swap in the full-screen one.

open as a page

Should a wedding-photography app compress or transcode photos and video on the phone before uploading, and when must it send the untouched originals?

level: middleimportance: should knowfreq 41%

basics

~20 s

Compress only uploads meant for viewing: it saves data and time but costs battery, heat and disk, and a lossy re-encode cannot be undone. A studio's deliverables are its originals, so send those untouched, perhaps after a preview.

open as a page

In a mobile art-museum app's fast-scrolling grid, cells briefly show the wrong painting before the right one appears; what causes it, and how should the image pipeline prevent it?

level: seniorimportance: should knowfreq 48%

basics

~20 s

A recycled cell gets a new artwork while its old request still runs, and the late result lands in it. On rebind, clear the image and detach the old request; at delivery, drop results whose key no longer matches.

open as a page

Which image format should a fashion catalogue app's photos arrive in, and how is it negotiated when two-year-old builds on older OS releases are still installed?

level: seniorimportance: should knowfreq 38%

basics

~20 s

The app tells the server which formats this device decodes; the server picks the best of those and falls back to JPEG. Caches must see the choice, via Vary or the URL, so one phone's AVIF never reaches another.

open as a page

A photographer swipes the wedding app away mid-upload and reopens it next morning; what did the OS cancel, and how should the queue resume with expired upload URLs?

level: seniorimportance: should knowfreq 44%

basics

~20 s

On one platform a user force-quit cancels every transfer handed to the OS, and nothing relaunches the app for them. Next launch, the app reads its saved queue, gets fresh upload URLs, asks each upload's server offset and resumes.

open as a page

How should a wedding-photography app order, parallelise and retry 600 queued photos and a 2 GB clip on a weak venue signal?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Favourites and small photos go first, the 2 GB clip last, with only a few uploads in flight on a thin link. Lost connections and server errors resume from the server's offset after backoff; refused files are never retried.

open as a page

In a children's educational-video app where parents download whole episodes before a flight, how should the download queue work so episodes finish even if the app is closed?

level: seniorimportance: should knowfreq 36%

basics

~20 s

Persist a queue entry per episode with its chosen storage quality, progress and state; hand transfers to the OS's background-transfer service; resume from bytes on disk; and reconcile on every launch, since a user force-quit can cancel transfers.

open as a page

As the lead for a fashion catalogue app's image delivery, how would you define the size, format and quality contract shared by every screen and every installed build?

level: principalimportance: should knowfreq 25%

basics

~20 s

One server-owned image descriptor for every screen: a width ladder, formats with a JPEG fallback, quality by density, and placeholder data. Grow it without app releases, never break old builds, and steer it by bytes, hit rate and decode failures.

open as a page

In a mobile art-museum app, how do you let a visitor zoom a 20,000 x 15,000-pixel painting down to its brushstrokes without running out of memory?

level: seniorimportance: nice to knowfreq 33%

basics

~20 s

Decoded whole the painting needs about 1.2 GB, so never decode it whole. Show a screen-sized overview, then decode only the tiles on screen at the resolution the zoom needs, from server-cut tiles or a region decoder.

open as a page

In a children's educational-video app, a downloaded episode's licence expires during a flight; how should offline licences, renewal and the download cap be designed?

level: seniorimportance: nice to knowfreq 31%

basics

~20 s

Fetch an offline licence with each download, store its expiry, renew near-expiry licences when online and warn parents before trips. A lapsed episode shows the child a friendly 'needs internet' card; deleting one releases its slot under the owner's cap.

open as a page