Dev.to AI 🤖 Ai 👁 0 📖 4 min read

Integrating a face-editing step into an upload pipeline: timeouts, retries, idempotency and retention

Every "AI media" feature starts as a nice-to-have button and ends as the flakiest part of your backend. A face-editing step — take a photo or a short video, return an edited one — looks like a single API call. In product

Every "AI media" feature starts as a nice-to-have button and ends as the flakiest part of your backend. A face-editing step — take a photo or a short video, return an edited one — looks like a single API call. In production it is a long-running job with cost per attempt, a hard-to-undo user action, and files that must disappear afterwards.

I have been working with hosted face-swap tools, including FaceSwapAI, and the same four failure modes show up every time. Here is how to design around them.

1. Timeouts are a budget, not a constant

Media jobs are slow for reasons you cannot control: upload bandwidth on a phone, queue depth at the provider, a 30-second video rather than a 3-second one. fetch(url, {timeout: 8000}) with the same 8 seconds for every request is how you get spurious failures on good traffic and hung workers on bad traffic.

Treat the deadline as a budget split across stages:

  • upload: proportional to file size, capped by the user's patience (they are staring at a spinner);
  • processing: usually the largest share, and the part you should not block a request thread on;
  • download and verify: short, but never zero.

Two patterns work well:

Async job + poll. Submit, return a job id immediately, and let the client poll or wait on a webhook. Your HTTP request lifetime stops mattering, and retries become safe because the job is the unit of work rather than the connection.

Per-stage deadline with a hard ceiling. If you must stay synchronous, give the whole operation one deadline and check the remaining budget before each stage. When the budget is gone, fail with something the UI can explain ("still processing, we will notify you") instead of a generic 500.

2. Retries need a key, or they cost money twice

The default retry loop is wrong for anything billed per call: a timeout does not mean the provider did not process your request. It usually means you stopped waiting.

So every request carries a client-generated idempotency key:

const key = crypto.randomUUID(); // persist before the first attempt

async function swapOnce(file, key, attempt = 1) {
  const res = await fetch(API, {
    method: "POST",
    headers: { "Idempotency-Key": key },
    body: form,
    signal: AbortSignal.timeout(20000),
  });
  if (res.status === 409) return pollExisting(key); // same job, already running
  if (res.status >= 500 || res.status === 429) {
    if (attempt >= 4) throw new Error("gave up after 4 attempts");
    const backoff = Math.min(30000, 1000 * 2 ** attempt) * (0.5 + Math.random());
    await sleep(backoff);
    return swapOnce(file, key, attempt + 1);
  }
  if (!res.ok) throw new Error(`provider rejected: ${res.status}`);
  return res.json();
}

Three rules that matter more than the code:

  • Persist the key before the first call. If your process dies mid-request, the key on disk is the only thing that lets you reconcile later.
  • Retry only what cannot double-charge. Network errors, 429 and 5xx are retryable. A 4xx validation error is not; retrying it just burns quota.
  • Back off with jitter. Synchronised retries from many workers turn one provider hiccup into an outage of your own.

3. Partial state is the real bug

The interesting failure is not "the call failed". It is "the call probably succeeded and I do not know". That is where you need a local record written before the remote call: user id, input file hash, idempotency key, provider job id, state, timestamps.

Then reconciliation is a boring loop you can run from a cron:

  1. jobs stuck in submitted for more than N minutes → poll the provider by key;
  2. provider says done → mark complete, fetch output, notify;
  3. provider says unknown → safe to resubmit with the same key, or refund the credit.

Write the row first, then call out. The reverse order leaves you with charged requests and no trace of them.

4. Retention is a feature, not cleanup

Uploaded faces are sensitive. Your retention policy should be visible in the product and enforced in code:

  • delete inputs and outputs on a timer (24 hours is a common default for consumer tools), not only when a user clicks delete;
  • keep deletion jobs idempotent too — a delete that fails silently is worse than no policy;
  • never log file URLs, signed links or base64 payloads; log ids;
  • tell the user what the provider's own policy is, separately from yours, because you may not control it.

If you use a hosted face swap web app, read its retention terms and mirror them in your own docs. "We delete in 24 hours" is only true if someone wrote the job that does it.

A checklist I keep reusing

  • [ ] one deadline per request, split across stages, with a hard ceiling;
  • [ ] idempotency key persisted before the first attempt;
  • [ ] retry only on network errors, 429 and 5xx, with jitter and a cap;
  • [ ] intent row written before the outbound call;
  • [ ] reconciliation job for jobs stuck in flight;
  • [ ] TTL deletion for inputs and outputs, with its own monitoring;
  • [ ] no file URLs or payloads in logs;
  • [ ] user-facing copy that says what happens while the job runs and what happens to their files.

None of this is specific to face swapping. Any pipeline that takes a file, spends money on it, and must delete it afterwards has the same shape. Getting the four pieces above right is most of the difference between a demo and something you can leave running.

📰 Read the original article on Dev.to AI

Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.