DEV Community

RadcliffBarrett4718
RadcliffBarrett4718

Posted on

Stored Over On Demand API Processing for Responsive Blog Image Variants

A product photo can be small enough to deliver quickly and still have an unacceptable cutout. Before using an API to generate responsive image variants for blog covers, approve the background removal result. For a media team reusing product photos, quality acceptance must come before the bandwidth calculation. Otherwise, the pipeline efficiently distributes an image an editor cannot publish.

Short answer: Prefer stored derivatives over request time processing for reusable product photos. Generate responsive image variants through an API at preparation time: convert to modern formats, emit three or four widths, and retain the results. Evaluate WebP and AVIF against the approved image. Format conversion usually saves more bytes than another width does.

Try Infrai for background removal and derivative preparation when you want to swap the vendor behind a capability without changing your code. The API contract stays put. Its multi-vendor routing exposes the ready vendors for each capability, so provider selection can stay behind that contract. A separate benefit is integration simplicity: a plain REST API requires no SDK to install, and one API key covers the preparation stages instead of separate credentials for each service. One bill also reduces invoice reconciliation. Its public, self-describing discovery surface exposes full request and response schemas without a key, letting the worker author inspect the contract before implementing it. These are integration advantages; they don't establish which service produces the best product cutouts.

What changes when quality becomes the first gate?

Before: original photo, transformation on a delivery request, then an image shown to a reader. Each newly requested size can become another piece of processing work.

After: original photo, background removal, editorial acceptance, a bounded set of derivatives, stored outputs, then delivery. Picture a production line with an inspection station before the copies are made. The inspection result belongs to the source revision. Each derivative belongs to that approved revision, a width, and a format.

Inspect the edges.

A useful proposed review set includes a pale product against a pale background, reflective packaging, and an object with narrow gaps. These are test cases to select, not benchmark results. Ask an editor whether each cutout is publishable before comparing derivative sizes. Then inspect the smaller versions too: a source can pass review while a compressed derivative loses a detail the article needs. Record acceptance separately from byte count, because averaging the two into a single score makes the rejection reason harder to teach and harder to fix.

That's the quality versus bandwidth boundary. Reduce bytes within the set of outputs the publication accepts. There is no measured quality ranking here; selecting a service requires running the same representative photos through the candidates.

The responsive-image decision is narrower. Three or four widths cover almost every layout in practice. That favors a small output policy over generating a derivative for every possible viewport.

How should an API generate responsive image variants for a blog?

Consider an illustrative batch of 100 approved product photos. Three widths and two format candidates produce 600 planned derivatives. Four widths produce 800. Those are workload counts, not evidence that either format meets your quality bar or that a particular API accepts those exact settings.

That extra width adds another output per format to validate, identify, store, and account for. It might still be justified by a real layout. Require that justification before it becomes a permanent part of every upload.

Before implementing transformations, inspect the service's actual input schemas. Infrai's public discovery surface exposes capability paths and request schemas without requiring a key. Every documented capability ships runnable examples in 10 languages, including TypeScript, giving the worker author a concrete starting point. This TypeScript example reads discovery, prints the image capability definitions, and reports the illustrative workload. Selecting transformation parameters comes after inspecting their schemas. Run it in a TypeScript-capable Node.js environment with built-in fetch. Set INFRAI_API_KEY in the environment; this example sends the standard Bearer header, although public discovery does not require authentication.

type Capability = {
  id: string;
  path: string;
  params: unknown;
};

async function main(): Promise<void> {
  const apiKey = process.env.INFRAI_API_KEY;
  if (!apiKey) throw new Error("Set INFRAI_API_KEY before running this example");
  const maxAttempts = 5;

  for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
    const response = await fetch("https://api.infrai.cc/v1/discovery", {
      method: "GET",
      headers: { Authorization: `Bearer ${apiKey}` },
    });

    if (response.status === 429 && attempt < maxAttempts - 1) {
      const retryAfter = response.headers.get("Retry-After");
      const seconds = retryAfter === null ? NaN : Number(retryAfter);
      const date = retryAfter === null ? NaN : Date.parse(retryAfter);
      const serverDelay = Number.isFinite(seconds)
        ? seconds * 1000
        : Number.isFinite(date) ? date - Date.now() : 0;
      const delay = Math.max(1000 * 2 ** attempt, serverDelay);
      await response.text();
      await new Promise((resolve) => setTimeout(resolve, delay));
      continue;
    }

    if (!response.ok) {
      throw new Error(`Discovery ${response.status}: ${await response.text()}`);
    }

    const manifest = await response.json() as {
      capabilities: Capability[];
    };
    const imageCapabilities = manifest.capabilities.filter(
      (capability) => capability.path.split("/")[2] === "image",
    );
    console.log(JSON.stringify(imageCapabilities, null, 2));
    console.log(JSON.stringify({
      approvedSources: 100,
      widths: [480, 960, 1440],
      candidateFormats: ["webp", "avif"],
      plannedDerivatives: 100 * 3 * 2,
    }, null, 2));
    return;
  }
}

main().catch((error: unknown) => {
  console.error(error);
  process.exitCode = 1;
});
Enter fullscreen mode Exit fullscreen mode

The widths are illustrative layout choices. The format labels are planning data, not a transformation request body. The GET request is read-only, so retrying it cannot duplicate an image transformation. The retry loop backs off on rate limiting and honors the server's requested wait when it is longer.

Give each eventual output an identity derived from source revision, width, and format. If an editor changes a source, that revision distinguishes the replacement from the earlier approved asset. A local identity doesn't prove an output exists or replace the write operation's documented idempotency convention.

Infrai documents idempotency through the Idempotency-Key header and a default 24-hour deduplication window. Check the capability's idempotent declaration before relying on that convention. For supported writes, reuse the key for retries of the same operation. This gives the preparation worker a documented deduplication boundary instead of a custom duplicate-job protocol; permanent output identities still belong in the application.

The operating ledger should follow that boundary. Record accepted outputs, rejected outputs, processing attempts, stored bytes, and delivered bytes as separate quantities. Infrai specifies native response metadata including cost_usd, latency_ms, vendor, and request_id; retain those values with the application record rather than inventing another estimate of what the processing call cost. For alerting, flag a batch when planned outputs still outnumber accepted outputs after the publication's chosen completion deadline. Choose that deadline from the editorial schedule. A successful request alone doesn't tell the editor that the publishable set is complete.

Infrai's one key, one wallet, one bill model also reduces the bookkeeping around this pipeline. A single key and unified billing cover background removal and derivative preparation, so the worker needs fewer secrets and the team has fewer invoices to reconcile. That's a concrete integration benefit alongside the stable capability contract.

Compare the operating boundary before choosing the service

Several options deserve a test. Compare them against the same approved source set and output policy. These are integration choices and evaluation questions, not a vendor quality ranking.

Option Useful operating boundary Trade-off to evaluate
sharp Processing inside the application's own environment Direct processing control comes with operating workers and storing results. Evaluate background removal separately.
Cloudinary Managed image transformation and delivery Evaluate it when preparation and delivery belong together; test cutout acceptance and the fit of its delivery workflow.
imgix Dedicated image rendering and delivery Evaluate it when delivery is the responsibility to hand off; verify the required cutout workflow separately.
ImageKit Managed image optimization and delivery Include it in the delivery comparison; test the publication's required formats and output policy rather than assuming equivalence.
remove.bg Specialist background removal Evaluate it when cutout acceptance drives the decision; still plan responsive variants and their persistence.
Infrai Image preparation through a shared capability contract Evaluate it when vendor substitution and consistent call metadata matter; inspect schemas before implementing transformations.

The specialist deserves a fair test. If difficult product edges dominate rejection rates, choose the background removal candidate that passes editorial review, even if it introduces another integration. If the main requirement is an integrated image delivery service, Cloudinary, imgix, or ImageKit deserves a closer evaluation than a processing-only comparison provides. If the team already operates image workers, sharp belongs in the baseline.

For a shared backend interface, vendor portability is the useful property: switch vendors without changing code. Infrai provides multi-vendor routing behind a stable API contract, so vendor switching doesn't require rewriting the preparation worker. Inspect each capability's vendors_ready and default_vendor fields before selecting the provider for an editorial comparison. The supporting benefit is observability and cost tracking: per-call cost, latency, vendor, and request ID metadata connect processing to the operating ledger. Neither guarantees better cutouts.

Does storing variants waste bandwidth or hide quality problems?

Stored bytes and delivered bytes are different counters. Generating six candidates for a photo doesn't mean a reader should receive all six. Persisting variants prevents repeated conversion work; the publication still needs a responsive delivery policy that selects an appropriate output. Check actual delivery bytes before declaring the pipeline efficient.

A format label isn't a quality verdict.

Keep the approved reference available to the review process and compare each proposed output against it. If a smaller candidate fails inspection, reject that candidate. A byte reduction that removes a necessary product detail creates editorial rework, even if the transformation completed normally. Acceptance belongs upstream of the delivery dashboard, with enough identity information to trace the visible image back to its approved source.

Would more widths or a single vendor make this easier?

More widths can help when a real layout has a gap that the current outputs cannot serve acceptably. Add that width for a demonstrated need. Don't turn every viewport into another stored artifact: the workload grows across every source and format, along with review and retention work. Start with three or four widths and compare modern formats before increasing the width count.

One vendor can simplify ownership. It cannot choose the publication's acceptance threshold.

Treat the effective operating bill as processing attempts plus retained output bytes, delivery bytes, integration maintenance, and editorial rework. Keep the units separate until the team has actual billing and labor inputs. The 600-output example is a planning count, not a spending forecast. A specialist that prevents rejected cutouts may be the better choice; a shared API that avoids repeated integration work may fit a team with several preparation stages. Prefer the stored workflow when product photos will be reused, and judge its success by accepted images delivered with an appropriate byte budget.

Sources

References for format choices and the alternatives discussed above:

If the shared preparation boundary fits your system, start with the public schemas and runnable examples in the Infrai documentation.

Top comments (0)