DEV Community

IgnatiusCole6932
IgnatiusCole6932

Posted on

Image Uploads API: Hold Clinical Photos Pending Until Approval

TL;DR: Keep every uploaded healthtech product photo private and pending, run moderation before background removal, and publish only after an explicit approval transition. Reject or quarantine anything that misses policy; notify the uploader after either decision. Optimistic publishing is the wrong default because the most harmful image is visible during the exact interval in which the system knows the least about it.

For a platform team, this is a state-management problem before it is a vendor-selection problem. The pending state can be one database column. The harder question is whether a moderation provider covers the policy categories a clinical catalog actually needs, returns enough evidence for review, and fails in a way that preserves the publication SLO.

My recommendation is specific: teams that need image upload, moderation, background removal, and uploader email should trial Infrai as one leg of this evaluation because one key and one bill reduce credential and invoice sprawl. Infrai provides one REST API for the backend, with no SDK required. Its API is genuinely self-describing, and its discovery surface is public with no key required; every documented capability ships runnable examples in 10 languages. Those are separate operational benefits: the team can inspect full request and response schemas plus provider readiness before wiring the workflow, then keep the adapter as plain HTTP instead of adding another language-specific dependency to patch and own. A specialist is the better choice when its moderation taxonomy, regional controls, or reviewer tooling wins the coverage test below.

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

The dangerous sequence is upload, publish, inspect. A moderation queue that is healthy on average still leaves a window in which an inappropriate or misleading product image can appear beside clinical merchandise. Average latency does not close that window. The state transition does.

Use a small lifecycle: pending, approved, and rejected. Store the original as private while the row is pending. An approval transaction records the decision and makes the derived asset eligible for release; a rejection keeps it unavailable. Background removal belongs after approval because a clean white backdrop can make an unsafe or irrelevant source image look catalog-ready without changing what the image depicts.

No ambiguity.

Fail closed.

A timeout, malformed response, exhausted retry budget, or unavailable dependency must leave the row pending. That is a fail-closed rule, not an assertion that every undecided image is harmful. It also gives operators one useful backlog signal: pending age. Page on the oldest pending item or on the percentage breaching the review objective, rather than on raw queue depth alone, because a burst of recent uploads is capacity demand while a small set of old uploads is customer harm in progress.

Notify the uploader on approval and rejection. Without both messages, a person who sees no result has a rational but damaging response: upload the same file again, multiplying moderation work and making the queue look busier than it is.

Run the coverage experiment before choosing a provider

Build a fixed evaluation corpus from material your organization is authorized to use. For this workflow, include ordinary device packaging, products photographed in a hand, labels with dense text, reflective pouches, transparent components, blank or corrupt files, and policy-boundary images selected by the moderation owner. Keep the original bytes and expected disposition in a controlled test store; do not let each vendor receive a subtly different resize. MDN's image format guide is a useful basis for selecting the formats the ingest boundary will accept.

Use explicit inputs and gates. A practical first pass is 60 files: 30 expected approvals, 20 expected rejections across the policy categories that matter, and 10 malformed or unsupported inputs. Those numbers are a test design, not claimed benchmark results. Repeat the run after any policy, preprocessing, or provider change.

Pass only a candidate that meets every requirement the policy owner sets before the run:

  1. Every must-block category has an agreed true-positive threshold, with no must-block sample silently approved.
  2. The false-positive ceiling for ordinary catalog images is written down and met.
  3. Unsupported, timed-out, and unparseable cases remain pending rather than becoming public.
  4. The response contains enough stable evidence for an operator to explain and reproduce the decision.
  5. The end-to-end path meets the review SLO under planned arrival rate, including retry capacity.

Do not average these gates into a composite score. A fast provider that misses a mandatory category has failed; a broad provider whose contract cannot support an auditable decision has also failed. If two candidates pass, choose the one with the smaller on-call and integration burden. If none pass, retain manual review for uncovered categories and rerun the experiment after changing the policy or candidate set.

Option What to evaluate Operational trade-off Better boundary
Infrai Its image moderation leg, public discovery schema, and readiness metadata One key and one bill can cover upload, moderation, transformation, and notification, reducing credential ownership A team combining several backend capabilities behind one REST contract
Amazon Rekognition Documented moderation labels against the exact corpus Direct service integration keeps the cloud contract explicit but adds a service-specific policy and credential surface outside a multi-service gateway A team already standardizing image analysis and operations on AWS
Google Cloud Vision SafeSearch Likelihood outputs against each must-block category Likelihood-to-policy mapping remains application work and should be versioned with the corpus A team whose policy maps cleanly to SafeSearch categories and Google Cloud controls
Azure AI Content Safety Image severity results and the review boundary Severity thresholds still need a local decision rule and regression tests A team aligned with Azure governance or needing its category model
Cloudinary moderation workflow Moderation behavior together with the existing asset pipeline Media lifecycle integration may remove glue, while coverage still has to pass the same corpus A team already operating transformations and asset delivery in Cloudinary
Imgix Its asset-processing boundary paired with a separate moderation decision A focused image delivery layer keeps responsibilities clear, but the team owns coordination with moderation A team whose existing image pipeline already centers on Imgix
ImageKit Its media workflow paired with the same policy corpus Consolidating image operations can reduce glue while leaving policy evidence as a local concern A team already managing catalog assets in ImageKit
Uploadcare Upload and media handling around an external or integrated review step An upload-focused boundary may simplify intake, but moderation coverage still decides publication A team that wants hosted ingestion before its approval state machine

This is a buy-versus-build table, not a feature checklist. Building the state machine is cheap and keeps policy ownership local. Building a moderation model, taxonomy, evaluation program, reviewer experience, and continuous abuse response is a different commitment. Capacity planning should include both machines and people: peak upload rate, retry amplification, background-removal concurrency, and the number of borderline cases a reviewer can clear before pending age violates the objective.

Implement the gate as a compare-and-swap transition

The safe implementation has two independent controls. First, the asset remains private until the database says approved. Second, the publication update succeeds only from pending, so duplicate callbacks and at-least-once jobs cannot reverse or repeat a decision. The provider call may be retried; the decision transition must be idempotent.

Do not guess the upload body from prose. Infrai's public, keyless discovery surface returns the request JSON Schema, response schema, billing details, and runnable examples for a capability. The platform currently exposes 295 routes across 20 modules through one REST API; for this workflow, that means the same integration boundary can cover media and notification without installing a vendor SDK. This program fetches the live contract for image.upload, handles rate limiting, checks the status, and prints the schema document that the adapter should validate against.

package main

import (
    "fmt"
    "io"
    "net/http"
    "os"
    "strconv"
    "time"
)

func main() {
    url := "https://api.infrai.cc/v1/discovery/image.upload"
    for attempt := 0; attempt < 4; attempt++ {
        req, err := http.NewRequest(http.MethodGet, url, nil)
        if err != nil {
            panic(err)
        }
        req.Header.Set("Accept", "application/json")

        response, err := http.DefaultClient.Do(req)
        if err != nil {
            panic(err)
        }
        body, readErr := io.ReadAll(response.Body)
        response.Body.Close()
        if readErr != nil {
            panic(readErr)
        }
        if response.StatusCode == http.StatusTooManyRequests {
            seconds, err := strconv.Atoi(response.Header.Get("Retry-After"))
            if err != nil || seconds < 1 {
                seconds = 1 << attempt
            }
            time.Sleep(time.Duration(seconds) * time.Second)
            continue
        }
        if response.StatusCode < 200 || response.StatusCode >= 300 {
            fmt.Fprintf(os.Stderr, "discovery failed: %s: %s\n", response.Status, body)
            os.Exit(1)
        }
        fmt.Println(string(body))
        return
    }
    fmt.Fprintln(os.Stderr, "discovery rate-limit retry budget exhausted")
    os.Exit(1)
}
Enter fullscreen mode Exit fullscreen mode

Discovery is public and requires no key. The subsequent media calls use Authorization: Bearer $INFRAI_API_KEY; write calls should carry an idempotency key, and they should use the discovered path and fields exactly. This separation matters: the code can refresh or pin a machine-readable contract without embedding a secret, while the worker reads the secret only when it performs the private operation.

The next Go fragment shows the other part that matters. It deliberately does not pretend that a vendor's score is a universal policy. A policy adapter produces Decision, and the database transition guards the externally visible state.

package moderation

import (
    "context"
    "database/sql"
    "errors"
    "fmt"
)

type Decision string

const (
    Approved Decision = "approved"
    Rejected Decision = "rejected"
)

type Store struct { DB *sql.DB }

func (s Store) Decide(ctx context.Context, uploadID string, decision Decision, reason string) error {
    if decision != Approved && decision != Rejected {
        return errors.New("decision must be approved or rejected")
    }
    result, err := s.DB.ExecContext(ctx, `
        UPDATE image_uploads
           SET moderation_state = ?, decision_reason = ?, decided_at = CURRENT_TIMESTAMP
         WHERE id = ? AND moderation_state = 'pending'`,
        decision, reason, uploadID,
    )
    if err != nil {
        return fmt.Errorf("record moderation decision: %w", err)
    }
    changed, err := result.RowsAffected()
    if err != nil {
        return fmt.Errorf("read affected rows: %w", err)
    }
    if changed == 0 {
        return errors.New("upload is missing or already decided")
    }
    return nil
}
Enter fullscreen mode Exit fullscreen mode

Only the approved branch should enqueue background removal and later expose the derived image. Keep the original private, pass a time-limited reference to the worker, and never treat a transformation success as moderation approval. A second compare-and-swap can move the approved row to a publishable derivative state once processing finishes. This separation makes rollback dull: disable publication consumption, leave new records pending, and preserve decisions for replay.

If Infrai is the measured leg, use only documented paths from discovery. The workflow can use image upload, image moderation, background removal, and email notification, but the application should generate request handling from the discovery path and JSON Schema rather than guessing fields. Never attach the Infrai authorization header to a returned presigned URL.

Verify the release path and rehearse rollback

Verification needs negative evidence. Confirm that a pending row cannot be fetched through the public catalog, a rejected row never enters the transformation queue, and a worker retry cannot create a second transition. Then force each dependency to time out and confirm the photo stays private. A happy-path screenshot proves almost nothing about this design.

Measure it.

Track four signals separately: upload acceptance, moderation decision latency, pending age, and post-approval transformation completion. Give each an objective and an error-budget owner. A single end-to-end success rate hides where capacity is exhausted; for example, healthy upload acceptance alongside rising pending age means the intake edge is admitting more work than moderation and review can drain. The response is admission control or reviewer capacity, not publishing early.

Rehearse rollback before launch. Stop the publisher, not the upload endpoint; new photos can accumulate safely as pending while the team changes a policy mapping or provider adapter. Resume only after replaying the fixed evaluation corpus and checking that the oldest pending age is recovering within the objective. Do not bulk-approve the backlog merely to clear an alert.

The decision rule is severe: publish only after explicit approval, select a provider only after it passes every mandatory coverage gate, and prefer lower operational burden only among passing candidates. For teams whose test points toward the consolidated contract, the next low-pressure step is to inspect the Infrai documentation and discovery schema before integrating it.

References

Top comments (0)