Sub topic 10
Generating image variants and modern formats
This chapter assumes you know how uploads reach object storage and how an event can trigger a worker after an upload completes. It covers what that worker does with an image: it makes smaller copies (variants) in modern formats.
Why variants exist
Users upload a 4000 px photo from a phone. A profile page needs 200 px. If you serve the original, you waste bandwidth and slow the page. The fix is to generate a small set of variants once, after upload, and serve those.
A good set is small and fixed. For example:
thumb: 200 px wide, for lists.w800: 800 px wide, for article pages.w1600: 1600 px wide, for full-screen views.
Fixed widths keep the cache hit rate high. If clients could request any width, every request would be a possible cache miss and a possible resize job.
The processing flow
The worker reads the original from a private location. It never trusts the upload and never overwrites it.
A worker in Python
This example uses Pillow. The WebP encoder is built into Pillow. AVIF needs Pillow 11.3 or newer, or the pillow-avif-plugin package on older versions.
import hashlib
import io
from PIL import Image, ImageOps
WIDTHS = [200, 800, 1600]
def make_variants(original: bytes) -> dict[str, bytes]:
image = Image.open(io.BytesIO(original))
image = ImageOps.exif_transpose(image) # apply the rotation flag
image = image.convert("RGB") # also drops EXIF, since it is not re-saved
variants = {}
for width in WIDTHS:
if width >= image.width:
continue # never upscale
height = round(image.height * width / image.width)
resized = image.resize((width, height), Image.LANCZOS)
buffer = io.BytesIO()
resized.save(buffer, format="WEBP", quality=80)
data = buffer.getvalue()
digest = hashlib.sha256(data).hexdigest()[:6]
variants[f"media/{digest}/w{width}.webp"] = data
return variantsThree details matter here.
- Orientation. Phones store rotation in EXIF metadata instead of rotating the pixels. Call
exif_transposebefore you discard metadata, or photos appear sideways. - Metadata. Pillow does not copy EXIF into the saved file unless you ask it to. That removes GPS coordinates and camera details, which is usually what you want for user photos.
- Hashed keys. The key contains a hash of the output bytes. A changed image gets a new URL, so the CDN can cache each URL for a year, as described in the CDN chapter.
Choosing formats
| Format | Size vs JPEG | Support | Encoding cost |
|---|---|---|---|
| JPEG | baseline | universal | low |
| WebP | about 25% smaller | all current browsers | low |
| AVIF | often 30–50% smaller | current browsers, newer than WebP | high |
Sizes depend on the image and the quality setting, so measure on your own content. AVIF encoding is slow, which is another reason to do it in the background and not during the request.
Serve the formats with the HTML picture element so the browser picks the first one it supports. Keep a JPEG or WebP fallback. Alternatively, a CDN can choose a format from the Accept header, but then you must add Vary: Accept or a format-aware cache key. Otherwise a cache may return AVIF to a browser that cannot read it.
Common errors
- Decompression bombs. A small file can decode to billions of pixels. Set
Image.MAX_IMAGE_PIXELSand reject anything above it before resizing. - Reprocessing loops. If the worker writes into the bucket that triggers it, each output starts another job. Write to a separate bucket or prefix, and filter the event by prefix.
- Non-idempotent jobs. Events can be delivered twice. Hashed keys make a repeat run harmless, because it writes the same objects.
- Processing before the scan. Only decode files that have passed validation and quarantine.
Exercise
A worker is triggered by every object created in the uploads bucket and writes its resized images back to the same bucket. What goes wrong, and how do you fix it?
Show answer
Each variant it writes creates a new event, which starts another job, which writes more objects, so the pipeline loops and costs grow. Write variants to a different bucket or prefix, and restrict the trigger to the prefix that holds originals.
Exercise
Why call exif_transpose before dropping metadata?
Show answer
The camera's rotation lives in the EXIF orientation flag, not in the pixels. If you strip EXIF first, the flag is lost and the image displays rotated incorrectly.