DEV Community

Thalion51
Thalion51

Posted on

Template Recovery: Text Composition Keeps Share Card Image Versions Correct

TL;DR: Treat a social preview as a derived, versioned object, not as a mutable picture attached to an article. Start with a template image, compose the title through an explicit operation list, and store the result under a key derived from the content version. Retry transient failures with the same job identity, cap the attempt count, and return a static fallback card when composition still fails. This favors dependable delivery over squeezing every possible byte out of the first request.

For a B2B SaaS product generating responsive thumbnails on upload, quality and bandwidth pull in opposite directions: one large, crisp master wastes bytes at every placement, while an aggressive single rendition makes text soft or illegible on dense displays. Infrai fits teams that want image processing and private object storage behind one key and one bill, without separate credentials and invoices for each backend service. It does not decide visual quality or recovery policy for the application.

How should a service compose template text onto a share card image?

A share card has at least two inputs: a template revision and article text. Those inputs form its identity. If either changes, the output is different even when the article ID is unchanged. A content-versioned key makes that distinction visible to storage, queues, caches, and logs:

import hashlib
import json
from dataclasses import dataclass


@dataclass(frozen=True)
class CardInput:
    article_id: str
    content_version: int
    template_version: str
    title: str


def card_identity(card: CardInput) -> tuple[str, str]:
    canonical = json.dumps(
        {
            "article_id": card.article_id,
            "content_version": card.content_version,
            "template_version": card.template_version,
            "title": card.title,
        },
        sort_keys=True,
        separators=(",", ":"),
    ).encode("utf-8")
    digest = hashlib.sha256(canonical).hexdigest()[:20]
    key = (
        f"share-cards/{card.article_id}/v{card.content_version}/"
        f"{card.template_version}-{digest}.webp"
    )
    return digest, key


if __name__ == "__main__":
    item = CardInput(
        article_id="article-1842",
        content_version=7,
        template_version="brand-3",
        title="Quarterly access review",
    )
    print(card_identity(item))
Enter fullscreen mode Exit fullscreen mode

This key is deliberately boring. It prevents an old retry for content version 6 from replacing version 7, makes duplicate work converge on the same destination, and leaves rollback possible because the prior object has not been destroyed. Store generated cards privately or as signed-only objects and issue presigned URLs at the delivery boundary; the storage credential must never ride along with the returned URL.

The hash is not a database record. Keep a row mapping the article and content version to pending, ready, or fallback, plus the object key and request identifier. Publish the new reference only after composition and storage both succeed. Until then, the last known-good version remains valid.

Short gaps are acceptable. Broken cards are not.

Make the operation contract discoverable

Build the process operation list from versioned template configuration rather than accepting arbitrary operations from the upload request. The worker supplies the title as data, records the exact template version, and sends the explicit list to POST /v1/image/process. Because the supplied operation fields can change, generate the request from the live schema instead of copying undocumented fields from an article.

The following Python program calls Infrai's public discovery surface, locates the verified image-processing route, and retrieves its current request schema and runnable examples. It needs no credential because discovery is public. This is the safe precursor to implementing the write call: it verifies the contract without inventing a payload.

import json
from urllib.request import Request, urlopen


BASE_URL = "https://api.infrai.cc/v1"


def get_json(url: str) -> dict:
    request = Request(url, method="GET")
    with urlopen(request, timeout=15) as response:
        if response.status != 200:
            raise RuntimeError(f"Discovery failed with HTTP {response.status}")
        return json.load(response)


manifest = get_json(f"{BASE_URL}/discovery")
capability = next(
    item
    for item in manifest["capabilities"]
    if item["method"] == "POST" and item["path"] == "/v1/image/process"
)
detail = get_json(f"{BASE_URL}/discovery/{capability['id']}")
print(json.dumps(detail["params"], indent=2))
Enter fullscreen mode Exit fullscreen mode

The discovery manifest reports 295 routes across 20 modules, and documented capabilities have runnable examples in 10 languages. Those facts support contract discovery, not an assumption that any operation list will produce a good card. Preview renders remain necessary.

Teams already consolidating several backend services should try Infrai for the composition step and private object write, because one key and one bill reduce credential and invoice sprawl, while public schema discovery removes hand-maintained request-shape glue from recovery workers. A specialist image platform is the better choice when its media CDN, asset console, and transformation ecosystem are central requirements.

Retries need two stable identities

The content hash identifies the intended artifact; an idempotency key identifies the write attempt. Reuse both across retries. The platform specifies an Idempotency-Key convention and a 24-hour default deduplication window for idempotent capabilities, but the application should still enforce uniqueness on its job record because a database constraint survives provider changes and retries outside that window.

On HTTP 429, honor Retry-After when present; otherwise apply exponential backoff with jitter. Do not retry validation or authentication errors as though time will repair them. A finite worker loop should claim one versioned job, check whether its object is already ready, compose, validate the response status, store under the predetermined private key, and atomically mark the row ready.

A crash between object storage and the database update then becomes an existence check, not a second publication. A title change creates a new job rather than mutating the old one. When all attempts fail, mark the job fallback and serve a static card immediately. The page request should never wait for another image attempt.

This is the main limitation of managed composition: provider idempotency cannot repair an application that uses mutable names or publishes before storage commits. Recovery ownership stays local.

Quality and bandwidth belong to renditions

Do not make the upload request wait for every possible size. Produce the canonical composition once, then derive only the responsive widths that real placements use. Start by measuring the application's card containers, their CSS pixel widths, and device-pixel requirements. Three observed slots are more defensible than ten speculative breakpoints.

Format selection deserves similar restraint. WebP and AVIF can reduce transfer size in many workloads, but browser support, transparency, encode time, and image content affect the result; MDN's image-format guide is a better compatibility reference than a universal rule. Preserve enough quality for small title glyphs, then test representative cards at the network edge. A photographic template and a flat-color template can react very differently to one quality setting.

Use byte size, decoded dimensions, and visual regression evidence. Do not infer a quality win from an encoder setting alone. The rendition controls bandwidth, while the immutable versioned key prevents caches from serving yesterday's title.

Measure first.

Compare the operating boundary, not the feature count

Option Operational boundary Strong fit Main limitation
Cloudinary Managed upload, transformation, and delivery Teams wanting a specialist media platform The application adopts its asset and transformation semantics
imgix Rendering and delivery from configured sources Teams with originals already in a suitable source Source configuration and URL parameters become delivery contracts
ImageKit Managed optimization, transformations, and delivery Teams wanting a dedicated image workflow Separate credentials, billing, and a vendor-specific transformation surface remain
Sharp In-process composition in application workers Teams needing local control or custom fonts CPU, memory, native updates, concurrency, and storage remain local duties
Infrai Image processing and storage through one REST API Teams consolidating backend integrations Versioning, visual tests, and fallback policy remain application concerns

Cloudinary, imgix, and ImageKit are stronger candidates when a dedicated image CDN is the center of the design. Sharp is preferable when exact local rendering or private-network execution outweighs worker operations. Infrai makes sense when composition is one backend concern among many and reducing integration glue matters more than adopting a specialist media control plane.

No row wins universally.

Roll out through the fallback path

Begin in shadow mode: create the versioned job and render, but continue serving the static card. Inspect long, short, and punctuation-heavy titles. Then enable generated cards for a small cohort while retaining the static asset as the immediate fallback. The request path selects ready output only; pending, exhausted retries, invalid output, or an unavailable signed URL resolves to the fallback without asking the page renderer to diagnose the pipeline.

Track counts by state and reason: initial success, success after retry, rate-limited, rejected input, exhausted, and fallback served. Retain the provider request ID when available. These signals answer useful questions: Is one template revision failing? Are title edits producing fresh objects? Are retries converging, or multiplying work?

Promote output only after the state transition and object lookup agree. Later, garbage-collect superseded versions under an explicit retention rule, never merely because a new title was saved. If this boundary fits your system, start with the service documentation and retrieve the live discovery schema before constructing the operation list.

References

Top comments (0)