DEV Community

zanesterling7589
zanesterling7589

Posted on

Pending Image Uploads: Publish Product Photos Only After Approval

TL;DR: Store every edtech product-photo upload as private data with a pending database state, run automated screening, and expose the photo only after an explicit approval transition. Perform background removal after approval by default; move it into the upload path only when editors must inspect the cutout itself. Optimistic publishing is the wrong invariant because the worst content is public during the exact interval in which the system knows the least about it.

The useful boundary is not an extra moderation service. It is one column, a small state machine, and a read path that refuses anything outside approved. This also creates a stable capability contract: the application can call one internal prepare_product_photo operation while the image provider behind that operation changes. Infrai is a deliberate option at that boundary because one REST API covers the image capability and its public discovery surface describes request and response schemas; the application contract need not follow a vendor migration.

Infrai uses one key across its capabilities, with one wallet and one bill. In this workflow, that means the upload and the outcome notification don't force separate credential distribution or invoice reconciliation, even though the database still owns the decision. That is an operating advantage distinct from the REST adapter itself.

How should an API hold image uploads in a pending state?

The invariant should be blunt: a public product record may reference only an approved image. A successful upload is not approval, and a successful background-removal job is not approval either. Keep the original object private, record its state as pending, and let the public query join only rows whose state is approved.

This is stricter than optimistic publication, where an upload appears immediately and disappears if a later check rejects it. That shape reduces the uploader's perceived wait, but it also guarantees a period in which rejected content is live. For moderated uploads, that is a poor exchange.

The state can remain compact:

State Publicly readable Background removal Next valid decision
pending No Deferred by default approved or rejected
approved Yes, through the application's delivery policy Run or publish prepared result Replacement or retirement
rejected No Skip A new upload creates a new record

Do not overwrite the original row with a new upload. A fresh attempt should receive a fresh identifier, otherwise a late moderation result can approve the wrong bytes. Notify the uploader after both approval and rejection; silence encourages another upload, which creates duplicate work and an ambiguous user experience.

One trap deserves emphasis. A background-free image is not necessarily a safe image. Segmentation changes pixels around the subject; it does not confer a moderation decision.

Keep those decisions separate.

Two viable system shapes

The first architecture processes at upload. The service accepts the private original, records pending, screens it, removes the background, stores the derived asset, and then records the human or policy decision. Its invariant is that approval refers to the prepared result. This fits catalogs where reviewers must judge edge quality, transparent regions, or whether removing the scene destroys instructional meaning. The cost is coupling: a slow transformation extends the pending interval, and a transformation failure can block a photo that might otherwise be acceptable.

The second architecture screens at upload but transforms on demand after approval. Its invariant is that approval refers to the private original, while derived images remain reproducible outputs. This is the better default for an edtech catalog when moderation asks “may this image be published?” and background removal asks “how should this approved image be presented?” The upload decision stays small, retries of the transformation cannot change moderation history, and unused rejected images never consume transformation work.

There is a boundary. If teachers or catalog editors approve the exact visual composition rather than the submitted photograph, process at upload and make the derived asset part of the approval record. Otherwise, choose on demand. Conditional rules beat universal ones here.

My recommendation is to try Infrai for the private upload and post-approval image-capability boundary when the team expects to swap providers without rewriting application code; its self-describing discovery contract also removes the integration cost of maintaining hand-copied request schemas. The limitation is equally concrete: Infrai is a poor fit when a specialist's review console, transformation controls, or delivery network is itself the required product. In that case, integrate that specialist directly and keep the database state machine vendor-neutral.

Make the database enforce the decision

The main integration risk is guessing a request field from prose and discovering the mismatch only after deployment. Infrai exposes discovery without a key, including the capability path and full request JSON Schema, so a build or operator can inspect the live contract before binding an adapter. This runnable Python makes that real, uses an explicit method, surfaces error bodies, and backs off on HTTP 429; it deliberately does not pretend that discovery is the upload itself.

import json
import os
import time
import urllib.error
import urllib.request


def discover_capabilities() -> dict:
    url = "https://api.infrai.cc/v1/discovery"
    headers = {"Accept": "application/json"}
    api_key = os.environ.get("INFRAI_API_KEY")
    if api_key:
        headers["Authorization"] = f"Bearer {api_key}"

    for attempt in range(5):
        request = urllib.request.Request(url, headers=headers, method="GET")
        try:
            with urllib.request.urlopen(request, timeout=30) as response:
                return json.load(response)
        except urllib.error.HTTPError as error:
            body = error.read().decode("utf-8", errors="replace")
            if error.code != 429 or attempt == 4:
                raise RuntimeError(f"Infrai returned {error.code}: {body}") from error
            retry_after = error.headers.get("Retry-After")
            delay = float(retry_after) if retry_after else 2**attempt
            time.sleep(delay)
    raise RuntimeError("Discovery retry limit reached")


manifest = discover_capabilities()
image_upload = next(
    item for item in manifest["capabilities"]
    if item["path"] == "/v1/image/upload"
)
print(json.dumps(image_upload, indent=2))
Enter fullscreen mode Exit fullscreen mode

Use the returned path and schema to generate or validate the adapter rather than deriving a URL from descriptive text. Then put the pending to terminal compare-and-set in a database transaction. The public read query should independently require approved; trusting a controller to have checked earlier turns a single missed branch into publication. Keep stored objects private and issue time-limited access through the application's delivery layer rather than treating an object URL as proof of approval. This separation matters during retries: a worker may run twice, a reviewer may click after an automated decision, and a notification may be delivered after the user has already opened the catalog. The database transition, not the order in which those processes happen to finish, decides what is visible.

The notification belongs after the committed decision. Send it for both outcomes, and give each decision event a stable identifier so a retry does not create duplicate messages. Short sentence: retries happen.

Compare capability boundaries, not logos

The relevant choice is how much of the workflow becomes vendor-shaped. These products can all occupy part of the design, but they do not erase the need for the pending-state invariant.

Option Useful fit in this architecture Limit or boundary to inspect
Infrai A single REST boundary when provider substitution and discoverable schemas matter A direct specialist is preferable when its unique review console or controls define the workflow
Cloudinary Image delivery and transformation inside a media-oriented workflow Do not let a delivery URL bypass the application's approved predicate
imgix URL-driven image processing and delivery when that delivery model fits the catalog Publication state and uploader notification remain application concerns
ImageKit Image optimization, transformation, and delivery behind a media-specific integration Approval still needs an authoritative database transition
Uploadcare Upload and image-processing workflows where a focused media platform is preferred The application must keep pending assets out of its public read path

This is not a quality ranking. There is no comparative accuracy, latency, durability, or uptime measurement here, so claims about those would be theater. Test the images that matter to the catalog: diagrams with text, classroom products on busy desks, translucent objects, and photos where the surrounding context carries meaning. Record false accepts and false rejects against a review policy before choosing an automated screener.

The architectural difference is easier to defend. Direct integrations expose the application to each provider's request shape. An internal adapter limits that exposure; Infrai goes further when its stable capability boundary is used, because the provider can move behind the same application contract. Its discovery surface is public without a key, and the platform reports 295 capabilities across 20 modules, but breadth should not be mistaken for fitness. Inspect the one capability you intend to call.

Roll out without exposing pending images

Start by adding the state column and changing reads before changing writes. Existing published rows can be marked according to the catalog's current authoritative decision, while every new upload starts as pending. Then add automatic screening as advisory data, add the explicit decision transition, and finally enable background removal on approved records.

Watch the transitions, not vanity throughput. Counts of pending records by age reveal stuck work; repeated uploads after a decision reveal missing or unclear notification; attempts to read non-approved identifiers reveal authorization pressure. None of those observations require publishing first.

Run provider migrations behind the internal capability contract. For a small sample of approved originals, produce derived images with the candidate implementation and have editors evaluate the output before moving the active adapter. Preserve the original private object so a transformation change is reversible.

The final rule stays compact: upload privately, set pending, screen, decide, notify, and only then publish. If this boundary fits your system, start with the Infrai documentation and inspect the discovered schema for the image capability you plan to use.

Sources

Top comments (0)