AI Image API ETag Caching: Private Asset Revalidation

Nov 19, 2026·8 min read

Your dashboard displays the same generated product image every time a developer opens a job. The application downloads it repeatedly, even though the saved asset has not changed. AI image API ETag caching lets your delivery service answer a conditional request without resending the image body, while still checking whether the requester may access that asset.

An entity tag, or ETag, is an HTTP validator identifying a selected representation of a resource. It is not a generation identifier, a billing receipt, or an access token. This guide explains application-owned delivery after ingestion from the GenRelay image API; it does not assert that a generation endpoint accepts caching headers or returns the validators shown here.

Where should ETag caching sit in an image pipeline?

Place ETag creation after image validation and final encoding, then store the validator beside an immutable representation. A representation is the exact version selected for delivery: a particular format, size, encoding, and processing policy.

A useful sequence is:

  1. Submit the generation request using the documented model integration.
  2. Retrieve the completed result and validate its decoded image structure.
  3. Apply orientation, privacy, resizing, and encoding policies.
  4. Save the final bytes under an application-owned object identifier.
  5. Compute and persist an ETag for those bytes.
  6. Authorize each delivery request before evaluating its conditional headers.

Do not compute a strong ETag from the prompt. Identical prompts can produce different images. Likewise, a provider job identifier cannot identify both the original PNG and a resized JPEG if their bytes differ. The image content hash guide explains byte identity separately from visual similarity.

For a small service, a quoted SHA-256 digest is a practical strong validator when computed over the actual response bytes. SHA-256 is a cryptographic hash function producing a fixed-size digest. It does not encrypt the image or make an identifier secret. Avoid exposing cross-tenant deduplication information through public asset lookup endpoints.

How should a server handle If-None-Match?

For authorized GET and HEAD requests, return 304 when any supplied If-None-Match validator matches the current representation using weak comparison. A 304 Not Modified response tells a client to reuse its stored body; it contains no image body itself.

Weak comparison ignores the W/ prefix when comparing validators. Strong comparison requires both tags to be strong and exactly equal. GET cache revalidation uses the former, even if your server emits a strong tag. This differs from operations such as validating an If-Range entity tag.

The wildcard * matches an existing selected representation. A missing asset is not made existent by a conditional header. Perform asset resolution and authorization first; an expired session must not obtain a 304 merely because the browser remembers yesterday's ETag.

The following standard-library example parses the quoted tag syntax rather than splitting blindly on commas. Commas can appear inside an opaque tag. Its application policy is to ignore malformed or oversized conditional fields and send the ordinary authorized response. That sacrifices bandwidth savings without granting access or exposing data.

import hashlib
import re

TAG_LIST = re.compile(
    r'\s*(W/)?"([\x21\x23-\x7e\x80-\xff]*)"\s*(,|$)'
)

def etag_for(body):
    return '"' + hashlib.sha256(body).hexdigest() + '"'

def matches_if_none_match(value, current):
    if not value or len(value) > 8192:
        return False
    if value.strip() == '*':
        return True
    tags = []
    position = 0
    while position < len(value):
        match = TAG_LIST.match(value, position)
        if match is None:
            return False
        tags.append('"' + match.group(2) + '"')
        position = match.end()
        if match.group(3) == ',':
            if not value[position:].strip():
                return False
        else:
            break
    return current in tags

This function expects a current strong tag generated by etag_for. It is not a general HTTP precondition library. A production framework may already provide a standards-aware parser; use that parser rather than introducing another implementation unnecessarily. When an HTTP stack combines repeated header fields, enforce an aggregate header-size limit at that boundary too.

Which headers belong on 200, 304, and HEAD responses?

Return consistent ETag and cache-policy metadata on 200 and 304, but omit the image body and Content-Length from this example's 304 responses. HEAD returns the headers an ordinary GET would produce, without sending its body.

Cache-Control: private, no-cache permits storage in a private cache but requires revalidation before reuse. Here, private means shared caches should not store the response. It does not mean encrypted, inaccessible to local users, or automatically deleted at logout. no-cache does not mean no storage; use no-store when your product's sensitivity policy prohibits caching.

This executable response planner assumes the caller has already loaded a validated, immutable byte string. A response planner selects status, headers, and body; your web framework still performs the actual network response. The authorization boolean is deliberately explicit so the order can be tested.

def plan_image_response(body, media_type, authorized,
                        method='GET', if_none_match=None):
    if not authorized:
        return 403, {'Cache-Control': 'no-store'}, b''
    if method not in ('GET', 'HEAD'):
        return 405, {'Allow': 'GET, HEAD'}, b''

    tag = etag_for(body)
    headers = {
        'ETag': tag,
        'Cache-Control': 'private, no-cache',
        'X-Content-Type-Options': 'nosniff',
    }
    if matches_if_none_match(if_none_match, tag):
        return 304, headers, b''

    headers['Content-Type'] = media_type
    headers['Content-Length'] = str(len(body))
    return 200, headers, b'' if method == 'HEAD' else body

Treat media_type as trusted validation output, not a value copied from a client query. Limit supported types and never label an HTML error document as an image. For large objects, persist the validator during ingestion instead of hashing and loading the whole image for each request. Stream from controlled storage after the conditional decision.

This deliberately narrow example implements If-None-Match for GET and HEAD only. If you accept additional preconditions such as If-Match, use a complete HTTP precondition implementation with the correct evaluation order. Do not quietly claim support for headers your handler ignores.

How do variants, transformations, and authorization affect validators?

Each distinct delivered byte representation needs a validator that remains consistent with the bytes actually sent. Resizing, changing compression, stripping metadata, or converting PNG to WebP creates another representation, even when the result looks similar.

Use explicit immutable variant URLs when possible, for example an opaque asset identifier plus a stored variant identifier. If the same URL selects formats using Accept, send Vary: Accept and ensure your cache keys distinguish those representations. Vary tells caches which request headers influenced representation selection; it is not an authorization mechanism.

Disable unplanned CDN transformations on a strong-validator route, or ensure that the transforming layer generates validators for its own output. A compression layer must also preserve coherent representation metadata. The origin's byte digest cannot truthfully remain a strong validator for arbitrary transformed bytes.

For private assets, look up ownership using the authenticated principal and stored asset record, not an untrusted tenant query parameter. Apply identical permission checks before 200, HEAD, or 304 responses. Choose a consistent 403 or 404 policy for unauthorized requests to avoid exposing whether another tenant owns an identifier.

Signed URLs are a different access mechanism. Their expiration and cache policy must be designed together; a cached copy can remain locally available after a link expires. See the signed image URL guide for that boundary. Revalidation alone does not erase previously downloaded media.

Does a 304 response reduce image-generation spending?

A 304 reduces transferred response bytes, not the price of an image that has already been generated. Keep the generation workflow separate from the download workflow so reloading an image never implicitly submits another generation request.

Using the supplied GenRelay rates for this November 19, 2026 example, 1,000 Nano Banana Pro images at 1K or 2K cost $30 in generation charges; at 4K they cost $42. One thousand Nano Banana 2 images at 1K cost $20, while GPT-Image-2 at $0.014 per image costs $14. These are unit-price calculations, not quality comparisons or end-to-end cost estimates.

If each saved image is opened ten times, successful cache revalidation does not change those generation totals. Storage, request processing, and delivery may have separate infrastructure costs. A conditional request still reaches some server or cache, and the first successful download still transfers the body.

Measure authorized 200 responses, 304 responses, transferred bytes, and validation failures separately. Do not log signed URLs, credentials, image contents, or full private request headers. Investigate an unexpectedly high 200 rate as a cache-policy issue before considering another paid generation.

What should developers ask before enabling ETag caching?

Resolve storage sensitivity, representation identity, and authorization behavior before enabling private browser caching. These frequently asked questions expose errors that a happy-path download test misses.

Can an ETag be used instead of an API key?

No. An ETag identifies a representation; it does not authenticate a caller or authorize a tenant. Evaluate access independently on every conditional request.

Does no-cache prevent the browser from saving an image?

No. It allows storage while requiring revalidation before reuse. Select no-store for a policy that prohibits HTTP cache storage, while recognizing that users can still intentionally download visible media.

Should a resized image keep the original image's ETag?

Not as a strong validator when its bytes changed. Generate and store a validator for the final resized representation, and use distinct variant identifiers or correct content negotiation.

What happens if If-None-Match contains an invalid tag list?

This example ignores that malformed condition and returns the ordinary authorized response. Document this policy, enforce request-header limits, and use your framework's parser when available.

Can HEAD return 304?

Yes. An authorized conditional HEAD request can receive 304 when its validator matches. An unconditional HEAD response uses the ordinary representation headers but does not send the image body.

Related posts

Join our DiscordAI Image API ETag Caching: Private Asset Revalidation — GenRelay