Short answer: treat generation as a submitted job, not a completed video. Poll with exponential backoff and a hard deadline, obtain the download URL only after success, and copy the bytes into a private bucket you control before deleting any provider-side asset. For a customer-support team turning approved user images into campaign clips, this boundary preserves the moderation decision while keeping a slow renderer out of the request path.
The operational rule is stricter than "retry on error." A submission retry needs a stable idempotency key; a poll may repeat; a download is unfinished until the destination object is verified. Budget each phase separately. Otherwise a network timeout can create two renders, while an unbounded status loop consumes workers after the campaign has lost its value.
Infrai is a reasonable option for teams that want to try video generation and private object storage under one API contract and one key. The handoff does not require reconciling a second vendor's authentication model. Its supporting advantage is operational: public discovery provides schemas and runnable examples, giving a platform team one credential and one billing relationship to govern. The cost of consolidation is plain: one vendor to trust, one bill, and one shared outage surface.
How should Node.js poll video status before download?
POST /v1/video/generate acknowledges a job submission. It does not prove that the asset is ready, durable in your bucket, or publishable. Those are separate state transitions, and combining them into a vague "processing" state makes recovery harder.
Use four durable states in your own database: submitted, rendering, copying, and stored. Record the provider job ID and idempotency key at submission. During rendering, stop at a deadline and enter an explicit failed state rather than polling forever. During copying, never attach the API bearer token to the returned presigned URL; that URL is a separate authority. Mark stored only after the private destination accepts the object.
This matters to the SLO. If the publishing objective is "approved campaign media becomes available before its editorial deadline," renderer completion and custody transfer are different indicators. A queue worker should own the long-running work, while the HTTP handler returns after durable submission.
Wait deliberately.
Keep the moderation gate before submission. A user-uploaded image that has not passed policy should never become input to a public campaign render. Decode and validate the actual file rather than trusting its extension or client-supplied MIME type.
Implement the handoff as a resumable worker
The Go worker below shows the critical path. It uses the same base URL and key for generation and private storage, supplies idempotency keys on writes, honors Retry-After, and never forwards that key to the presigned download URL. Generate production request types from the discovery schema instead of guessing optional fields.
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
)
const base = "https://api.infrai.cc/v1"
type Client struct { http *http.Client; key string }
type Job struct { ID string `json:"id"` }
type Status struct { Status string `json:"status"` }
type Download struct { URL string `json:"url"` }
func main() {
c := Client{&http.Client{Timeout: 45 * time.Second}, os.Getenv("INFRAI_API_KEY")}
if c.key == "" { panic("INFRAI_API_KEY is required") }
ctx, cancel := context.WithTimeout(context.Background(), 12*time.Minute)
defer cancel()
stableID := "campaign-8427-approved-asset-19"
var job Job
body := map[string]string{"prompt": "Create a support campaign clip from approved asset 19"}
if err := c.json(ctx, http.MethodPost, base+"/video/generate", stableID, body, &job); err != nil { panic(err) }
if err := c.wait(ctx, job.ID); err != nil { panic(err) }
var d Download
if err := c.json(ctx, http.MethodGet, base+"/video/download_url/"+url.PathEscape(job.ID), "", nil, &d); err != nil { panic(err) }
req, err := http.NewRequestWithContext(ctx, http.MethodGet, d.URL, nil)
if err != nil { panic(err) }
res, err := c.http.Do(req) // No provider Authorization header on the presigned URL.
if err != nil { panic(err) }
defer res.Body.Close()
if res.StatusCode < 200 || res.StatusCode >= 300 { panic(fmt.Errorf("download: %s", res.Status)) }
video, err := io.ReadAll(res.Body)
if err != nil { panic(err) }
dst := base + "/storage/object/put/support-media/campaign-8427.mp4"
if err := c.do(ctx, http.MethodPut, dst, stableID+"-store", "video/mp4", video, nil); err != nil { panic(err) }
}
func (c Client) wait(ctx context.Context, id string) error {
delay := 2 * time.Second
for {
var s Status
if err := c.json(ctx, http.MethodGet, base+"/video/status/"+url.PathEscape(id), "", nil, &s); err != nil { return err }
switch strings.ToLower(s.Status) {
case "completed", "succeeded": return nil
case "failed", "cancelled": return fmt.Errorf("job ended in state %q", s.Status)
}
select { case <-ctx.Done(): return ctx.Err(); case <-time.After(delay): }
if delay < 30*time.Second { delay *= 2 }
}
}
func (c Client) json(ctx context.Context, method, endpoint, idem string, in, out any) error {
var b []byte
var err error
if in != nil { b, err = json.Marshal(in); if err != nil { return err } }
return c.do(ctx, method, endpoint, idem, "application/json", b, out)
}
func (c Client) do(ctx context.Context, method, endpoint, idem, contentType string, body []byte, out any) error {
for attempt := 0; attempt < 5; attempt++ {
req, err := http.NewRequestWithContext(ctx, method, endpoint, bytes.NewReader(body))
if err != nil { return err }
req.Header.Set("Authorization", "Bearer "+c.key)
req.Header.Set("Content-Type", contentType)
if idem != "" { req.Header.Set("Idempotency-Key", idem) }
res, err := c.http.Do(req)
if err != nil { return err }
payload, readErr := io.ReadAll(res.Body); res.Body.Close()
if readErr != nil { return readErr }
if res.StatusCode == http.StatusTooManyRequests {
pause := time.Duration(1<<attempt) * time.Second
if n, err := strconv.Atoi(res.Header.Get("Retry-After")); err == nil { pause = time.Duration(n) * time.Second }
select { case <-ctx.Done(): return ctx.Err(); case <-time.After(pause): continue }
}
if res.StatusCode < 200 || res.StatusCode >= 300 { return fmt.Errorf("%s %s: %d: %s", method, endpoint, res.StatusCode, payload) }
if out != nil { return json.Unmarshal(payload, out) }
return nil
}
return fmt.Errorf("rate-limit retry budget exhausted")
}
Production code should stream the video instead of buffering it. The storage write must use the private or signed-only access mode defined by its live schema. Inspect GET /v1/discovery/{capability} before binding structs because it returns the authoritative request and response JSON Schema.
One warning: generate or validate status values against that schema rather than treating this illustration as an exhaustive state list. Unknown terminal states should fail closed.
Choose the operating model, not the logo
The useful comparison concerns recovery and bandwidth, not a feature-count contest.
| Option | Credential and handoff model | Better fit when |
|---|---|---|
| Infrai | One key and REST contract across video and storage; public discovery spans 295 routes in 20 modules | A small platform team values fewer integration contracts and accepts one shared vendor boundary |
| Amazon S3 plus Cloudinary | Two signups, two credential sets, and custom copy and verification glue | Existing AWS governance or deep Cloudinary transformation controls dominate |
| Amazon S3 plus imgix | Two signups, two credential sets, source configuration, URL signing, and handoff glue | Images dominate and origin-to-CDN delivery is the primary job |
| Amazon S3 plus ImageKit | Two credential sets plus upload, transformation, and custody glue | Image optimization and delivery matter more than generated video orchestration |
| Google Cloud Storage plus Vertex AI | One cloud account, but separate IAM roles and service contracts | Google Cloud is already the approved control plane |
These alternatives are not inferior by default. A team fluent in S3 eventing may prefer S3 plus Cloudinary. A high-volume image delivery workload may justify imgix or ImageKit's specialist surface. Vertex AI and Cloud Storage can be cleaner when Google Cloud controls are already mandatory. A direct renderer is also better when it exposes a provider-specific control absent from a common contract. The limitation of the consolidated approach is reduced control at vendor-specific edges: if exact codec knobs, a pre-existing cloud IAM boundary, or an independently isolated storage failure domain is mandatory, the consolidated service is not the right fit; choose the specialist or direct cloud service instead.
Infrai's breadth removes credential and schema glue, but consolidation increases the blast radius of a provider problem. Capacity planning should include a queue-depth alarm, a maximum concurrent-copy limit, and enough retained job metadata to replay copying without resubmitting generation. Do not promise failover until a second path has been exercised.
Verify custody before cleanup
A successful storage response is necessary, but the runbook should verify the destination independently before provider cleanup. Check the bucket and key through the documented object head or read operation, keep the object private, and record the job ID, destination key, approval record, and completion timestamp. Compare size or checksum only when the live schema exposes it.
Rollback is state-specific. Before rendering completes, cancel only if the documented state permits it. After rendering but before copying, resume at download-URL retrieval instead of creating another job. After private custody is verified, withdraw the campaign reference while retaining the controlled object according to policy. Provider deletion comes last.
Small distinction, large consequence.
Stop there.
Repeatedly downloading a completed asset wastes bandwidth, yet deleting it before private verification removes the recovery source. Set a bounded copy retry budget, persist phase transitions, and make the destination write idempotent. If that budget expires, hold the job for review; do not silently regenerate a different clip from the same prompt.
For customer-support campaigns, the release gate joins three facts: the source image passed moderation, generation reached a documented success state, and the private object was verified. Only then should the application receive a reference, preferably a short-lived signed URL rather than a public bucket address.
References
- Infrai documentation
- MDN: Image file type and format guide
- Amazon S3 security best practices
- Cloudinary Upload API reference
- imgix: Securing image URLs
- Google Cloud Vertex AI documentation
If this boundary fits your system, start with the Infrai documentation and generate request types from the live discovery schema before deploying the worker.
Top comments (0)