Images account for ~50% of the average web page's weight. A single unoptimized hero image can exceed the total payload of all scripts, styles, and fonts combined. Optimizing images is the single highest-ROI performance intervention a frontend team can make — it directly improves LCP, reduces bandwidth costs, and speeds up time-to-interactive on slow networks.
System DesignRADIO FrameworkFrontendX Engineering
What Are We Building?
A comprehensive image optimization system that covers the entire delivery chain: from the source image on disk to the pixels rendered on the user's screen. This is not a single component but a set of interlocking strategies — format selection, responsive resolution switching, CDN transformation, lazy loading, placeholder techniques, and caching policies.
The system must handle every image use case on a modern web app: hero banners (LCP-critical), thumbnails (many per page), user uploads (unpredictable dimensions), icons (SVG vs PNG), and background images (CSS vs <img>). Each use case demands a different optimization strategy, and the system must adapt automatically without requiring manual intervention from developers.
The design follows the RADIO framework: Requirements → Architecture → Data Model → Interface → Optimization. Each section builds on the previous one, moving from what we need to how we deliver it.
Figure 1 — Image format decision tree. Start from the source format, choose lossy or lossless, then pick a modern container. The recommendation is WebP with an AVIF fallback via the <picture> element.
1 · Requirements (R)
Before choosing formats or writing CDN configs, we must define the surface area of the problem. Image optimization touches every page, every user role, and every device class. These are the questions I would ask in a system design interview — and the answers that drive the architecture.
Functional requirements
Automatic format selection: Serve the smallest possible format the browser supports — AVIF where supported, WebP as the default, JPEG/PNG as universal fallback.
Responsive resolution switching: Deliver images at the correct resolution for the user's viewport width and device pixel ratio (DPR). A 400×300 thumbnail should never download a 4000×3000 source.
Lazy loading: Images below the fold must not block initial page render. They should load when they enter (or are about to enter) the viewport.
Placeholder strategies: While the full image loads, the user should see something — a solid color, a blurry preview, or a skeleton — to reduce perceived latency.
CDN-based transformation: Resizing, format conversion, and compression should happen at the CDN edge, not on the origin server. The origin stores one master copy; the CDN generates all variants on demand.
Cache optimization: Images are the most cacheable resource on the web. The system must set aggressive cache headers with content-based hashing for immutability.
Non-functional requirements
Performance target: LCP image must load within 2.5s on 3G. Total image weight per page should be under 500 KB for a content page and under 1 MB for a media-heavy page.
No layout shift: Every image must reserve its space before loading. CLS contribution must be zero for images with known dimensions.
Accessibility: All images must have alt text. Decorative images must be hidden from screen readers with aria-hidden.
Bandwidth savings: At least 40-60% reduction in image payload compared to unoptimized JPEGs, measured at equivalent perceptual quality (SSIM).
Developer experience: Drop-in usage — importing an Image component should be simpler than using a native <img>. No manual format negotiation or srcset construction.
Key Insight
The bandwidth savings target drives most architectural decisions. Modern formats (AVIF, WebP) save 30-50% over JPEG at the same quality, responsive sizing saves another 30-60% for viewport-bound images, and lazy loading defers 100% of below-the-fold image bytes. Together, the three strategies can reduce total image payload by 80-90% vs a naive implementation.
2 · Architecture (A)
The architecture splits image delivery into three tiers: the origin, the CDN transformation layer, and the client rendering layer. Each tier has a distinct responsibility, and the interfaces between them are well-defined contracts.
Figure 2 — Responsive image delivery pipeline. A CDN transforms the origin into multiple renditions; the srcset and sizes attributes let the browser pick the best fit. Aggressive caching headers minimize repeat downloads.
Tier 1: Origin Storage
The origin stores exactly one copy of each image at the highest available quality. This is the source of truth. Never store multiple resolution variants — that is the CDN's job. The origin can be object storage (S3, R2), a DAM (Cloudinary, imgix), or a simple file system behind a reverse proxy.
The only preprocessing done at the origin: stripping EXIF metadata (removes 10-50 KB of camera data per photo) and orienting the image correctly based on the EXIF orientation tag. Everything else — resize, format conversion, compression — is deferred to the CDN.
Tier 2: CDN Image Pipeline
The CDN (Cloudflare, Cloudinary, imgix, Akamai) receives the origin image and applies transformation rules based on URL parameters or configuration. This is where the heavy lifting happens:
Format detection: Parse the Accept header to determine which formats the browser supports (image/avif, image/webp). Serve the most efficient supported format.
Dynamic resizing: Generate renditions at requested widths. Cache each variant with a content-hash key so the same variant is never generated twice.
Quality optimization: Apply perceptual quality tuning per format. AVIF may need Q50 to match the visual fidelity of JPEG Q85, saving additional bytes.
Responsive image generation: When a page requests multiple widths via srcset, the CDN generates all variants in parallel and caches each independently.
Tip
The key principle is "compute once, cache forever." Every variant should be cached at the edge with a content-based hash in the URL. If a variant is requested a second time, the CDN serves it from edge cache in single-digit milliseconds — no origin request needed.
Tier 3: Client Rendering
On the client, a thin Image component wraps the native <img> or <picture> element. This component is responsible for:
Generating the correct srcset and sizes attributes from a single source URL + width prop.
Wrapping the image in a <picture> element when format negotiation is needed (AVIF + WebP + JPEG fallback).
Applying lazy loading via native loading="lazy" or IntersectionObserver for custom rootMargin control.
Managing placeholder state and transition animations (blur-up, fade-in).
Origin uploads master image
Single high-quality source stored in S3/R2 with EXIF stripped and correct orientation.
CDN transforms on first request
Format detection via Accept header, dynamic resize to requested width, quality optimization, content-hash cache key.
Variant cached at CDN edge
Cache-Control: public, max-age=31536000, immutable. ETag for revalidation. Subsequent requests served from edge in <10ms.
Page HTML references variants via srcset
Server-rendered <img> with srcset, sizes, picture element for format fallback, and loading=lazy.
LQIP placeholder shown immediately, full image fades in on load. Zero CLS due to explicit width/height.
3 · Data Model (D)
Images on the web are defined by more than their pixel data. A complete image data model includes the source identifier, format metadata, dimension variants, and caching state — all of which drive the optimization pipeline.
Image entity
example.typescript
interface ImageEntity {
id: string; // UUID or content-hash
publicId: string; // CDN/public identifier
originUrl: string; // Source URL (S3/R2)
// Source metadata
width: number; // Original width (px)
height: number; // Original height (px)
format: ImageFormat; // Original format
fileSize: number; // Original file size (bytes)
blurHash?: string; // Compact LQIP representation
dominantColor?: string; // Hex color for solid placeholder
// Content metadata
alt: string; // Required for accessibility
caption?: string; // Optional display caption
credit?: string; // Photographer/attribution
focalPoint?: { x: number; y: number }; // Crop gravity hint
}
type ImageFormat =
| "jpeg" | "png" | "gif" | "webp"
| "avif" | "heic" | "svg" | "jxl";
Rendition — a single variant
Each CDN-generated variant is described by a rendition record. The rendition's URL is content-hashed for immutability and long-lived caching:
example.typescript
interface ImageRendition {
url: string; // Content-hashed URL (immutable)
width: number; // Rendered width (px)
height: number; // Rendered height (px)
format: ImageFormat; // Actual format served
fileSize: number; // Bytes over the wire
quality: number; // Compression quality (1-100)
dpr: number; // Device pixel ratio
hash: string; // Content hash for cache key
}
// Example URL structure:
// https://cdn.example.com/images/{hash}/w_800,q_80,f_avif
srcset — the responsive contract
The srcset attribute is a list of rendition descriptors. Each entry pairs a URL with either a pixel width descriptor (400w) or a DPR descriptor (2x). The browser picks the best match for the current layout and screen.
example.typescript
// srcset descriptor model
interface SrcsetEntry {
url: string;
descriptor: WidthDescriptor | DprDescriptor;
}
type WidthDescriptor = { kind: "w"; value: number }; // e.g. 800w
type DprDescriptor = { kind: "x"; value: number }; // e.g. 2x
// sizes attribute — tells the browser how wide the image will be
// at different breakpoints
interface SizesAttribute {
conditions: MediaCondition[];
defaultSize: string; // e.g. "100vw" or "33vw"
}
interface MediaCondition {
mediaQuery: string; // e.g. "(max-width: 600px)"
size: string; // e.g. "100vw" or "300px"
}
Cache data model
The CDN cache is keyed by a composite hash of the image identifier and the transformation parameters. This ensures that two requests for the same variant hit the same cache entry:
example.typescript
// Cache key = f(publicId, width, height, format, quality, crop)
// Example: "mountain-sunset/w_800/f_avif/q_80"
//
// This key is hashed into the CDN's edge cache namespace.
// With immutable cache headers (max-age=31536000),
// the variant is served from the nearest edge POP in <5ms.
//
// Cache invalidation: never. Each variant is content-addressed.
// To update an image, upload a new source → new hash → new URL.
// Old URLs continue serving the previous variant — no stale cache.
Note
BlurHash is the recommended placeholder data model. It encodes the image's color distribution into a 20-30 character string that renders as a blurred placeholder. Unlike base64 inline images, BlurHash is trivially small and can be embedded in server-rendered HTML without inflating the page size. ThumbHash is a newer alternative that improves encoding quality for thumbnails.
4 · Interface (I)
The interface is the contract between the development team and the image optimization system. A well-designed API makes optimization automatic — developers should not need to think about formats, srcset, or cache headers.
The Image component API
The primary interface is a React Image component that abstracts all optimization logic behind simple props. The consumer passes a source identifier and desired display size; the component generates formats, renditions, and lazy loading automatically.
When format negotiation is needed (serving AVIF to supported browsers while falling back to WebP or JPEG), the component wraps the image in a <picture> element. The browser picks the first <source> whose type attribute matches a supported MIME type.
The CDN exposes a URL-based transformation API. Parameters are encoded in the URL path or query string. The CDN parses these, applies the transformations, and caches the result.
For Next.js apps, the built-in next/image component handles most of this out of the box — but it must be configured correctly. The config sets remote patterns, device sizes, and format preferences:
Next.js's built-in image optimizer runs on the server, not the CDN edge. For high-traffic applications, offload image transformation to a dedicated CDN service (Cloudinary, imgix, Cloudflare Images) to avoid consuming server CPU on resize operations. Configure loader or unoptimized accordingly.
5 · Optimization (O) — Deep Dive
This is where the RADIO framework delivers its payoff. The requirements, architecture, data model, and interface all exist to enable these optimization strategies. Let's examine each one in depth.
5.1 Format selection — choosing the right codec
Format selection is the highest-impact optimization decision. The right format depends on the image content type (photo, illustration, screenshot, UI element), the quality requirements, and the browser support matrix.
JPEG: The universal baseline. Excellent for photographs with smooth gradients. Lossy compression with tunable quality (Q80-Q95 recommended). No alpha channel. ~120 KB for a 1600×1200 photo at Q85.
WebP: The modern default. Supports both lossy and lossless compression plus alpha channel. ~43% smaller than JPEG at equivalent quality. Supported in all modern browsers since 2020. Lossy for photos (Q80-Q85), lossless for UI elements with sharp edges.
AVIF: The next-generation format using the AV1 codec. ~50% smaller than JPEG at equivalent quality. Supports HDR, wide color gamut, and alpha channel. Encoding is CPU-intensive (5-10× slower than WebP), making it best suited for CDN-based transformation. Decoding is fast and hardware-accelerated on modern devices.
JPEG XL: The most advanced format — lossy and lossless in one container, excellent compression efficiency, and lossless transcoding from legacy JPEG (no re-compression artifacts). Currently supported in Chrome and Edge behind a flag, not yet universal.
SVG: The only vector format. Use for icons, illustrations, and logos. Scales infinitely, generally under 2 KB per icon. Animatable. Must be carefully sanitized to prevent XSS via embedded scripts.
Figure 4 — Compression quality vs file size tradeoff. Modern formats like AVIF and WebP achieve dramatically smaller file sizes at equivalent perceptual quality. Choose the format based on content type and target quality.
5.2 Responsive images — srcset and sizes
Without responsive images, a user on a 375px-wide phone downloads the same 1600px-wide image as a user on a Retina iMac. The srcset and sizes attributes solve this by letting the browser choose the best variant.
The key insight: sizes tells the browser how wide the image will be rendered in CSS pixels at each viewport breakpoint. The browser combines this with the device's DPR to select the smallest srcset entry that meets the quality requirement:
example.typescript
// Browser selection logic (simplified)
function selectSrcsetEntry(
srcset: SrcsetEntry[],
viewportWidth: number, // CSS pixels
dpr: number, // devicePixelRatio
sizes: string, // e.g. "100vw"
): string {
// 1. Parse sizes to get the effective display width
const displayWidth = evaluateSizes(sizes, viewportWidth);
// 2. Calculate the pixel budget needed for this screen
const neededPixels = displayWidth * dpr;
// 3. Pick the smallest srcset entry >= neededPixels
const candidates = srcset
.filter(e => e.width >= neededPixels)
.sort((a, b) => a.width - b.width);
return candidates[0]?.url ?? srcset[srcset.length - 1]?.url;
}
The practical recommendation: generate 5-8 renditions per image at widths of 400, 800, 1200, 1600, 2000, and 2400 pixels. This covers every common viewport width from phone to 5K display, at both 1× and 2× DPR.
5.3 Lazy loading strategies
Lazy loading defers the download of images that are not immediately visible. There are three main approaches, each with different tradeoffs:
Figure 3 — Loading strategy timeline comparison. Eager images block early rendering. Native lazy and IntersectionObserver defer loading until the image nears the viewport. Progressive JPEG and LQIP show intermediate quality to reduce perceived wait time.
Native lazy (loading="lazy"): The simplest approach. The browser handles all detection and loading. Supported in Chrome, Firefox, Safari 15.4+, and Edge. Zero JavaScript overhead. The browser decides the threshold, which varies by browser (Chrome uses a ~3000px preload distance on fast connections).
IntersectionObserver: More control over the loading threshold via rootMargin. Useful when you want to start loading images well before they enter the viewport (e.g., 500px threshold for a fast-scrolling feed).
Eager loading for critical images: The LCP image must never be lazy-loaded. Mark it with fetchpriority="high" and loading="eager" (or omit the loading attribute, which defaults to eager).
Native loading="lazy" is the right default for most images. Only reach for IntersectionObserver when you need custom rootMargin (e.g., a 500px preload zone for a feed) or when you need to synchronize the load with other animations. Do not build your own lazy loading for basic cases — the browser implementation is better optimized and more battery-efficient.
5.4 Placeholder strategies — LQIP, BlurHash, and dominant color
While an image loads, the user sees either a blank space or a placeholder. Good placeholders reduce perceived latency and prevent layout shift. There are four common approaches:
Dominant color: Extract the most common color from the image and set it as the background color of the container. Simple, zero extra bytes, but provides no shape information. Good for solid-background product photos.
BlurHash: A compact (20-30 char) base83-encoded string that renders as a blurred version of the image. The client decodes it to a small canvas and blurs it. ~10-15 lines of decoding code. Provides recognizable shapes and colors at ~200 bytes.
LQIP (Low-Quality Image Placeholder): A tiny 20-40px-wide version of the image, heavily compressed and base64-encoded as a data URL. Inlined in the HTML, blurred with CSS filter: blur(12px). Higher quality than BlurHash but larger (1-2 KB base64 per image).
SQIP (SVG-based): A tiny SVG that approximates the image shape using primitive shapes. Vector-based, so scales perfectly. More complex to generate server-side.
For most applications, BlurHash offers the best size-to-quality tradeoff. It's what Mastodon, Wolt, and Unsplash use. Generate BlurHashes at upload time (server-side) and store them in the database alongside the image metadata. The client decodes them synchronously with zero network overhead.
5.5 Caching strategy
Images are the most cacheable resource on the web. They are static, immutable (when content-addressed), and account for the majority of page weight. The caching strategy has three layers:
cache-headers.tstypescript
// Cloudflare Workers: optimal image cachingexport default { async fetch(req: Request): Promise<Response> { const url = new URL(req.url); const path = url.pathname; // Only apply to image paths if (!/.(jpg|jpeg|png|gif|webp|avif|svg|ico)$/i.test(path)) { return fetch(req); } const response = await fetch(req); // Clone so we can modify headers const headers = new Headers(response.headers); // Long-lived cache for versioned assets if (path.includes("/_next/") || path.includes("/static/")) { headers.set("Cache-Control", "public, max-age=31536000, immutable"); } else { // Short cache for dynamic uploads, with revalidation headers.set("Cache-Control", "public, max-age=3600, stale-while-revalidate=86400"); } // Enable CDN cache at the edge headers.set("CDN-Cache-Control", "public, max-age=86400"); headers.set("Cloudflare-CDN-Cache-Control", "public, max-age=86400"); // Save bandwidth with conditional requests if (response.headers.get("ETag") || response.headers.get("Last-Modified")) { headers.set("Vary", "Accept, Accept-Encoding"); } return new Response(response.body, { status: response.status, headers, }); },};
Layer 1 — CDN edge cache: The CDN caches each image variant at hundreds of edge locations worldwide. When a user in Tokyo requests an image, it should be served from a Tokyo edge POP, not the origin in us-east-1. Cache keys include theAccept header so the CDN can serve different formats to different browsers.
Layer 2 — Browser cache: With Cache-Control: public, max-age=31536000, immutable, the browser caches the image for one year without revalidation. After the first visit, the image loads from disk cache in sub-millisecond time.
Layer 3 — Service worker cache: For offline-first apps, a service worker can cache images in the Cache Storage API. This enables offline image viewing and instant loads on repeat visits. Use a cache-first strategy with periodic background sync.
5.6 Critical image optimization (LCP)
The Largest Contentful Paint (LCP) image is the single most important image on the page. Optimizing it requires special treatment beyond the standard pipeline:
critical-image.htmlhtml
// Preload critical images in <head><link rel="preload" href="hero-1600w.webp" as="image" imagesrcset=" hero-400w.webp 400w, hero-800w.webp 800w, hero-1600w.webp 1600w " imagesizes="100vw" fetchpriority="high"/><!-- Priority hint on the img itself --><img src="hero-800w.webp" srcset="... sizes="100vw" alt="Hero banner" fetchpriority="high" decoding="sync"/>
Preload the LCP image: Add a <link rel="preload"> tag in the<head>. This tells the browser to start downloading the image before it parses the CSS that references it.
Use fetchpriority="high": This hint tells the browser to prioritize this image over other resources in the same priority bucket. It is respected by Chrome and Edge.
Use decoding="sync": For the LCP image, set decoding="sync" to decode the image immediately rather than deferring to the decode queue.
Serve the correct size preemptively: The preload link should include imagesrcset and imagesizes attributes so the browser downloads the right variant during the preload phase.
Never lazy-load the LCP image: Ensure loading is not set to "lazy". The default eager loading is correct.
Tradeoff table
Strategy
Pros
Cons
Format: WebP
Broad support, ~43% smaller than JPEG, lossy+lossless+alpha
Not as compact as AVIF, slightly slower encode than JPEG
Saves 30-60% on viewport-bound images, browser-native
Complex to generate manually, needs CDN or build-time step
Native lazy loading
Zero JS, browser-optimized, universally supported
No control over threshold, browser-dependent preload distance
LQIP / BlurHash
Great UX, reduces perceived latency, small payload
Extra server-side processing (BlurHash), ~1-2 KB per image (LQIP)
Immutable cache (content hash)
Never invalidate, 100% cache hit rate, zero revalidation traffic
Requires build-time hashing, stale images if not purged
CDN edge transformation
Zero origin CPU cost per request, global edge caching
Vendor dependency, cold-start latency on first request per variant
6 · Testing Strategy
Image optimization touches rendering, network, storage, and accessibility. Testing must cover each layer:
Automated visual regression
Use Percy or Chromatic to compare screenshots before and after optimization changes. The test should verify that WebP and AVIF conversion does not introduce artifacts visible to the human eye. Set SSIM (Structural Similarity Index) thresholds — anything above 0.98 is visually lossless.
Performance budget assertions
Integrate Lighthouse CI into CI/CD. Assert that:
Total image weight per page < 500 KB (content pages)
LCP image loaded within 2.5s on simulated 3G
No images lack explicit width and height (zero CLS)
All images have alt text (axe-core assertion)
No offscreen images are loaded eagerly (verify via network log analysis)
Format delivery tests
Write integration tests that verify the correct format is served for each browser user-agent. Mock the Accept header and assert that the response Content-Type matches the expected format:
Monitor CDN cache hit ratio per image variant. A cache ratio below 90% for images with immutable headers indicates a misconfiguration — likely the cache key is including a request-specific header (like Authorization) that varies per user and prevents caching. The target is >99% cache hit rate for image requests.
Accessibility audit
Run axe-core or WAVE against every page that contains images. The audit must verify:
Every <img> has non-empty alt (informative) or alt="" (decorative).
Decorative images have aria-hidden="true" and role="presentation".
SVGs in the DOM have role="img" and a title via <title> element.
7 · Key Takeaways
Image optimization is the highest-ROI performance work. Images account for ~50% of page weight. Modern format selection + responsive sizing + lazy loading together save 80-90% of image bytes with no perceptible quality loss.
WebP is the default, AVIF is the goal. Serve WebP to all modern browsers (98%+ support) and AVIF to those that support it (~80% support). Use the <picture> element for progressive enhancement. JPEG is the universal fallback — always include it.
srcset + sizes are non-negotiable. Without responsive images, every user downloads the largest variant regardless of screen size. Generate 5-8 renditions and let the browser pick the right one. The CDN transformation pipeline makes this automatic.
Native lazy loading is the right default. Use loading="lazy" for all non-critical images. Only reach for IntersectionObserver when you need custom rootMargin or synchronized loading. Never lazy-load the LCP image.
Content-hash URLs enable immutable caching. A content-addressed URL with max-age=31536000, immutable means the image is fetched from the network exactly once per variant. All subsequent loads hit the browser cache or CDN edge.
Placeholders reduce perceived latency. BlurHash or LQIP renders something meaningful while the full image loads. Combined with explicit dimensions (zero CLS), the user experiences the page as fast even if images take time to arrive.
The RADIO framework works for infrastructure systems too. Requirements scoped the problem to bandwidth and LCP targets. Architecture split the system into origin, CDN, and client tiers. The data model codified images as entities with renditions. The interface abstracted complexity behind a simple Image component. Optimization delivered the concrete strategies that compose into a complete system.
Image optimization is not a one-time task — it is a system that must be maintained as new formats emerge (JPEG XL, next-gen codecs), as browser support shifts, and as content evolves. The architecture described here is designed to absorb those changes without rewriting the delivery pipeline. Adopting a new format means adding a new <source> type element and updating the CDN transformation config — the rest of the system stays the same.