JsonCut

Missing media in bulk renders: a fallback chain that holds

Broken URLs, grey bands and error pages reach production when a render trusts a dimension check. A per-slot fallback contract for missing media.

Abstract geometric illustration for Missing media in bulk renders: a fallback chain that holds

A render that cannot find an image still produces a file, and the file still looks finished. Here is a practical contract for catching broken media before the queue and for degrading each slot in a way that stays visible, consistent and auditable.

The slot that received nothing

Most render failures are not render failures. The template renders exactly what it was asked to render: an <img> whose source resolved to somebody's 404 page, a signed URL that expired between data export and queue time, a WebP that arrived at 60% of its bytes. The job completes, the file exists, the API returns a 200. Nothing in the pipeline is technically wrong, and a fifth of the cards in the contact sheet carry the same grey rectangle.

That asymmetry is worth designing against. Overflowing text is visible inside the file; missing media is visible only as an absence, and absence has no error code by default. A media slot therefore needs two things that pure templates rarely have: a pre-flight check that treats a file as untrusted input, and a per-slot decision about what to ship when the check fails.

Abstract dark artwork with soft violet, red and blue gradient blobs behind a fine grid

Four ways a slot fails, and only one is a 404

Teams usually equate "missing media" with a broken URL. In practice the image is often present, healthy-looking and still unusable.

What arrivedWhat the renderer seesTypical outcome
HTTP 404 or 410Empty response bodyTransparent hole, or a broken-image glyph
Login or error page with status 200HTML where an image was expectedUndecodable file, sometimes rendered as text
Truncated or half-uploaded fileCorrect header, incomplete pixel dataGrey bands, smeared bottom third
Valid image, wrong format or channelsCMYK JPEG, 8-bit alpha, 20 MB fileColour shift, black box, timeout
Valid image, wrong subjectA crop of the wrong productNo error anywhere, only a wrong offer

Only the first row is easy. The second surprises teams because the status code says success: an authentication proxy answers with a friendly HTML page, the downloader stores it as product.jpg. Browsers decide how to treat a response by the media type in Content-Type, not by the file extension, so a mislabelled error page can travel into an image pipeline as a perfectly decodable text document. Sending X-Content-Type-Options: nosniff removes the guessing for clients that honour it.

A dimension check is not a decode check

The usual guard reads the image header and compares width and height against the slot. That guard is cheaper than a full decode and much weaker than it looks. I measured it with Pillow 13.0.0 on a generated 1600 × 900 JPEG at quality 85, cutting the file at fixed percentages of its 114,780 bytes.

Bytes keptHeader reportsStrict decodeLenient decodeMean deviation from original (top / mid / bottom band)
1,147 (1%)1600 × 900failsfull size87.7 / 127.0 / 127.0
11,478 (10%)1600 × 900failsfull size87.7 / 127.0 / 127.0
28,695 (25%)1600 × 900failsfull size34.4 / 127.0 / 127.0
57,390 (50%)1600 × 900failsfull size3.3 / 64.4 / 127.0
86,085 (75%)1600 × 900failsfull size3.3 / 3.6 / 93.3
113,632 (99%)1600 × 900failsfull size3.3 / 3.6 / 3.5

Three things follow. The header survives almost anything: 1,147 bytes are enough to report the correct dimensions, so a size check passes on a file with no usable pixels. Strictness has a cost: the 99% file deviates by 3.5 levels out of 255 and is visually indistinguishable, yet Pillow's default mode rejects it — a pipeline that accepts only strict decodes discards good assets as broken. And leniency hides the damage: with truncated images allowed, the decoder returns a full-size picture and fills the missing region with flat grey, 127 levels away, at a band standard deviation of exactly 0.0 where intact areas measured 26 to 33.

Format changes the failure mode again, so a single detection strategy does not cover every asset:

FormatFull sizeSize readable at 1% of bytesBehaviour when truncated
JPEG, quality 85114,780 ByesHeader intact, pixels missing, grey bands bottom-up
PNG8,993 Byes, from 89 BHeader intact, strict decode fails at every cut
WebP11,400 BnoContainer unreadable, no dimensions at all

The practical consequence: validate what you will actually trust. If the renderer decodes leniently, the pre-flight check cannot share that leniency, or every truncated file will pass both. Decode strictly in the validator and hand the result to the renderer, instead of letting the renderer be the validator.

Decide the blast radius before the first failure

Not every slot deserves the same response. A missing brand logo makes a card unusable; a missing decorative icon makes it slightly emptier. Write that down per slot, so the fallback is a property of the template rather than a decision somebody makes at 23:40 during a campaign.

SlotMissing or invalidWhat shipsLayout effectRow status
Brand logoBlockingMonogram tile in brand colourSame box, containedRejected, reported
Product photoDegradableNeutral product silhouette tileSame box, containedRendered, flagged
AvatarDegradableInitials on a tinted fieldSame circleRendered, flagged
Full-bleed backgroundDegradableGradient from brand paletteCovered, croppedRendered, flagged
QR codeBlockingNothingSlot collapsedRejected, reported
Decorative iconOptionalLayer hiddenSlot collapsedRendered, no flag

Two rows earn their strictness. A placeholder logo is worse than no card, because it misrepresents the brand on every impression. A placeholder QR code is worse than a blank space, because it looks scannable and sends people nowhere. Everything else can degrade, provided the degradation is visible and recorded.

This is the same per-row thinking that keeps a single bad record from stopping a batch, applied one level down: rows are already validated against the pinned template version before queueing, and invalid rows are reported without blocking valid ones. Media validation belongs in that gate, with one difference: a broken asset is a property of the row's data, not of its shape.

A four-tier fallback chain

A chain beats a single default because each tier has a different cost and a different meaning.

TierSourceConditionVisible to the viewer
1Exactly the requested assetFetched, sniffed, decoded, dimensions and size passReal content
2Brand variant of the same slotPrimary invalid, approved alternate existsReal, slightly generic content
3Neutral placeholderNo approved alternateClearly a placeholder
4Text-only layout variantPlaceholder would mislead, or the slot has no boxNo image, copy reflows

Tier 2 is the one teams forget and the cheapest to build. Most catalogues already contain a category image, a brand-kit logo and a stock avatar; a template that knows its own alternates survives a CDN outage without a single grey box. The rule that keeps the chain honest: a valid tier-1 asset is never replaced by a tier-2 variant for aesthetic reasons, and a tier-3 placeholder is never promoted into a hero slot.

Tier 4 exists because an honest layout without an image is sometimes better than a large placeholder square. A text-heavy announcement card usually reads better with the image slot collapsed than with a grey tile where a product should be.

Placeholders that look designed, not broken

The default placeholder in most systems is a grey rectangle, which is indistinguishable from a render bug. That ambiguity costs twice: viewers read it as failure, and operators learn to ignore grey areas in contact sheets because they might be intentional.

Three rules keep a placeholder legible. Give it a shape from the design system — a rounded tile, a monogram, a silhouette — so it reads as deliberate. Give it the slot's exact geometry, so nothing reflows. And give it a searchable name, such as ph_product_v3, so a manifest tells you which placeholder appeared in which output.

Placeholder styleGood forAvoid when
Monogram tileLogos, brands, initialsThe monogram could be mistaken for a real mark
Silhouette tileProducts, people, objectsThe product's shape is the message (fashion, food)
Palette gradientBackgrounds, texture, full-bleedIt would compete with the headline contrast
Labelled blockInternal or review rendersAnything customer-facing

A placeholder also needs alt text, and the right one. "Image unavailable" is honest; "Product photo" is not, because it describes content that is not there. The rules for alt text that survives a template pipeline apply unchanged: the field belongs to the template, not to whatever the data source left blank.

Pre-flight: six checks worth the milliseconds

The validator does not need to be clever. It needs to be stricter than the renderer and cheaper than a failed batch.

SIGNATURES = (
    (b"\xff\xd8\xff", "image/jpeg"),
    (b"\x89PNG\r\n\x1a\n", "image/png"),
)

def preflight(url, timeout=6):
    response = requests.get(url, timeout=timeout, stream=True)
    head = response.raw.read(16)
    if response.status_code != 200 or len(head) < 12:
        return "missing"
    kind = next((mime for sig, mime in SIGNATURES if head.startswith(sig)), None)
    if head[:4] == b"RIFF":
        kind = "image/webp" if head[8:12] == b"WEBP" else None
    if kind is None:
        return "not-an-image"
    declared = response.headers.get("Content-Type", "").split(";")[0].strip()
    if declared and declared.replace("image/jpg", "image/jpeg") != kind:
        return "type-mismatch"
    return "ok"

Six checks, in order of cost: status code, a byte floor, magic bytes, declared type, decodability, dimensions. The first four decide whether a download is worth starting; the last two need the body.

CheckCatchesCost
Status is 200404, 410, redirects to loginOne request
Byte floor, e.g. 2 KBEmpty and stub files, first-chunk-only uploadsFree
Magic bytes match a known imageHTML error pages, PDFs, zip files16 bytes
Declared type agreesProxies that relabel contentHeader only
Strict decode succeedsTruncation, corruption, unsupported codecsCPU, bounded by timeout
Dimensions inside the slot's rangeWrong asset, thumbnail upscalesAfter decode

The remaining knobs cause incidents rather than bugs: a six-second timeout, at most three redirects, and a cap on decoded pixels rather than bytes. A 40 MB PNG that decodes to 12,000 × 12,000 pixels is small on disk and fatal in memory. The declared-type check must also tolerate the common image/jpg alias, or it rejects good assets.

Keep the frame from reflowing

A fallback that changes the layout has created a second design. The placeholder must occupy the same box as the asset it replaces, with the same fit rule: cover for backgrounds and avatars, contain on a tinted field for logos and products. If the template letterboxes a logo to protect it from cropping, the placeholder inherits that behaviour — a wide monogram tile in a square slot has the same problem a wide logo has.

The fit rule and the asset's own aspect ratio are separate contracts, and confusing them is how a fallback ends up cropped differently from the real thing. Aspect-ratio handling per placement deserves its own decision, made once, so switching tiers never changes the composition.

One geometric detail matters in practice: placeholder tiles look right only if their internal padding scales with the box. A monogram tuned for a 240 px square looks cramped at 96 px and lost at 720 px. Two or three size classes, chosen by slot width, are enough.

Record the decision, not just the file

A render that used a fallback is not the same product as one that used the real asset, even if both PNGs look plausible. The difference has to survive the queue, or nobody can answer how many cards shipped without a product photo last Tuesday.

FieldExampleWhy it is there
media_statusok / fallback / missingSortable, alertable truth
media_sourcecdn / brand-variant / placeholderWhich tier actually ran
media_formatimage/webpSniffed, never copied from the extension
media_bytes289596Size floor, comparable over time
fallback_reasonhttp_404 / truncated / timeoutAggregates into the fix list
placeholder_idph_product_v3Reproducible, searchable in renders

These fields belong next to the naming and retention contract for the output itself: a filename tells you which template version and inputs produced a file, and the manifest tells you whether one of those inputs was a stand-in.

Watch the fallback rate, not the failure count

Hard failures are easy to alert on because they are exceptions. Placeholder rates are the more useful signal, and a percentage rather than an error: if 0.4% of product cards ship a placeholder on a normal day, a jump to 6% is a supplier problem, a CDN change or an expired credential — and it never appears in an error dashboard.

Three numbers are enough to start: fallback rate per slot per day, the top five hosts behind fallback_reason, and the share of rows rejected for blocking slots. Review the contact sheet of one fallback-heavy day rather than all of them; a grid of ten cards shows whether placeholders read as design or as damage — the judgement metrics cannot make.

Checklist before the next bulk run

  • Every media slot has a written policy: blocking, degradable or optional.
  • Validation happens strictly before the renderer sees the file.
  • Magic bytes are checked, not the file extension or the label alone.
  • Truncated files are detected by decode, with a timeout and a pixel cap.
  • Placeholders share the slot's box, fit rule and padding classes.
  • Every fallback is recorded with tier, reason and placeholder id.
  • Fallback rate is tracked per slot, with an alert threshold.

None of this prevents a broken URL. It decides, in advance and once, whether a broken URL produces a rejected row, an honest placeholder or a grey rectangle that nobody notices until a customer does.

Sources

JSONCut, "Typed templates and bulk rendering" — https://jsoncut.com/docs/templates/ (retrieved 2026-12-03) JSONCut, "Variables and reusable templates" — https://jsoncut.com/docs/create/variables-and-templates/ (retrieved 2026-12-03) MDN Web Docs, "Media types (MIME types)" — https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/MIME_types (retrieved 2026-12-03) MDN Web Docs, "X-Content-Type-Options header" — https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/X-Content-Type-Options (retrieved 2026-12-03) Own measurement: Pillow 13.0.0, generated 1600 × 900 JPEG (quality 85, 114,780 B), PNG and WebP, truncated at 1–99% of bytes, strict and lenient decode, per-band mean absolute deviation (2026-12-03)

Your next post is one sentence away.Start free, no editing skills needed.