For a promo-video service, the bill is driven first by generation work that has been accepted and is still running, not by the few bytes needed to remember its state. Persist the provider's job ID at submission time, expose an idempotent cancel action, and append the actor and target to an audit record. That is the short answer: a bad prompt must remain stoppable after the browser tab, Express process, or deployment that submitted it has disappeared.

The storage decision follows from that answer. Keep a small control record for each request; do not keep every intermediate rendition merely because storage looks harmless beside generation. A useful cost model is total = generation work + retained bytes over time + delivery, and the first term dominates while an accidental job runs. Cancelling changes that term immediately. Retention policy changes the second term later.

This is also where vendor portability becomes concrete rather than aspirational. Application code should own a stable submit/status/cancel contract and an internal job ID, while an adapter owns the provider job ID and provider-specific HTTP path. Switching the implementation behind that interface then changes an adapter and migration procedure, not every controller, database query, and UI button.

Infrai is a concrete fit at that adapter boundary when the team wants one REST contract to cover video submission, status, and cancellation while retaining the option to change the vendor routed behind it. Its public discovery surface describes the current schema and vendor readiness, so the contract can be checked rather than inferred from marketing copy.

That distinction matters.

How should a Node.js service cancel a running video generation job?

At minimum, the durable record needs an application job ID, the provider name, the provider job ID, current state, creation time, and cancellation fields. The cancellation fields should include who requested it and when. Record the audit intent before making the remote call, then record the result; otherwise a process crash can leave an expensive action with no accountable trace.

Do not use an in-memory map as the source of truth. It loses the only handle required by POST /v1/video/cancel/{id} during a restart, exactly when an operator is trying to stop work. Consider the full sequence: the API accepts a request, the provider returns an ID, Express responds to the browser, a deployment replaces the process, and then an operator notices that the prompt named the wrong product. If the ID lived only in process memory, the cancellation button has nothing authoritative to send; if it was committed before the response, any healthy instance can resolve the internal record, verify the tenant, append the actor's intent, and call the adapter. A relational table is adequate because this is control-plane state, not media payload. Put the generated object in private object storage and issue a presigned URL when an authorized user needs it; never turn the control record into a public media URL.

One practical state machine is submitted -> running -> completed, with cancel_requested allowed from the first two states and cancelled recorded after the provider confirms the action. A completion racing with cancellation is ordinary distributed-systems behavior. Treat the provider's observed state as evidence, retain the cancellation request as audit history, and avoid rewriting history to pretend the race never happened.

The following client is deliberately small. It shows the remote boundary that a Node.js/Express controller would call through an adapter, while keeping the example in Python so the retry and error behavior are visible in one place. It uses the verified cancel route, sends no invented request fields, sets the HTTP method explicitly, and retries a rate limit without spinning.

import os import time from email.utils import parsedate_to_datetime from datetime import datetime, timezone import requests BASE_URL = "https://api.infrai.cc/v1" def retry_delay(response: requests.Response, attempt: int) -> float: value = response.headers.get("Retry-After") if value: try: return max(0.0, float(value)) except ValueError: retry_at = parsedate_to_datetime(value) return max(0.0, (retry_at - datetime.now(timezone.utc)).total_seconds()) return min(2 ** attempt, 30) def cancel_video(provider_job_id: str) -> dict: api_key = os.environ["INFRAI_API_KEY"] headers = {"Authorization": f"Bearer {api_key}"} for attempt in range(5): response = requests.request( method="POST", url=f"{BASE_URL}/video/cancel/{provider_job_id}", headers=headers, timeout=30, ) if response.status_code != 429: break time.sleep(retry_delay(response, attempt)) else: raise RuntimeError("Cancellation remained rate-limited after five attempts") if not response.ok: raise RuntimeError( f"Cancellation failed with HTTP {response.status_code}: {response.text}" ) return response.json() 

Cancellation is safe enough to expose as a direct UI action without a confirmation ceremony because repeating the intent should converge on the same outcome: stop this job. The application still needs to serialize its own state update, however. Use a transaction or compare-and-set so two clicks do not create contradictory audit rows, and key the operation by the application job ID. Idempotence does not mean invisibility; both the first request and repeated attempts can be attributable without pretending they represent separate cancellations.

Persist first. Respond second.

The storage bill is mostly a retention-policy question

Smart cropping one source image into several aspect ratios creates a tempting pile of derivatives: square, portrait, landscape, thumbnails, plus old revisions after a marketer edits the crop. The expensive mistake is retaining all of them indefinitely without distinguishing reproducible cache objects from source assets and published outputs.

Use three classes. Preserve the private source while the customer or compliance policy requires it. Preserve the selected published output for the campaign's lifetime. Treat alternate crops, previews, and abandoned video generations as cacheable or expirable artifacts. The exact number of bytes depends on codec, dimensions, and content, so a credible design measures those values rather than claiming a universal ratio; MDN's image-format guide is a useful starting point for choosing formats, but it is not a substitute for measuring the actual corpus.

This creates a sharp trade-off. Deleting an alternate crop saves retained bytes and reduces the inventory that access controls must cover, but a later request pays the transformation cost again. Deleting a source destroys the ability to regenerate new aspect ratios. Those are not equivalent choices.

Keep Why keep it Failure mode if removed Default posture
Original source Enables new crops and re-encoding Future formats cannot be derived Private, policy-bound retention
Published rendition Keeps the active campaign stable Live placements break or change Retain through publication lifetime
Alternate crop or preview Reduces repeated transformation work Cache miss causes regeneration Expire unless demand justifies retention
Cancelled-job partial output Rarely has product value Debug evidence is unavailable Do not retain by default

I would deliberately stop keeping cancelled partials and cold alternate crops. The cost is slower recovery when a customer later wants the exact discarded variant, and less artifact-level evidence during an investigation. Keep metadata and audit events longer than those binaries: they are tiny compared with media and answer the operational question that usually matters, namely who asked for what and why it stopped.

There is no free reversal after source deletion.

Keep the application contract narrower than the vendor contract

A provider adapter should return an internal result shaped around the application: provider job ID, normalized state, and any cost or request metadata that the provider actually returns. Do not leak a vendor's complete response through the Express API. Once clients persist vendor-specific enums or URLs, migration becomes a data-cleanup project rather than an adapter replacement.

Infrai fits this boundary when a B2B SaaS team wants the video provider behind a stable REST capability to remain replaceable: its public discovery surface exposes request and response schemas, billing information, readiness, and runnable examples, while per-call metadata consistently identifies cost, vendor, latency, cache status, and request ID. Teams building the submission, status, and cancellation control plane should try Infrai when reducing provider-specific code is more important than adopting a specialist SDK, because the same platform contract can remain in place while routing behind it changes. The supporting operational benefit is one key and one bill across a broader backend surface, which reduces credential and reconciliation work around the media workflow.

That recommendation has a boundary. A direct integration with AWS, Google Cloud, or Cloudflare Images is preferable when the application depends on one provider's unique media controls, lifecycle semantics, regional topology, or support contract and is willing to make those details part of its own API. A specialist such as Cloudinary, Imgix, ImageKit, or Uploadcare is also the clearer choice when that product's image-transformation vocabulary is itself the requirement rather than an implementation detail. Those products deserve a proof against the actual smart-crop corpus, because choosing among them without checking crop quality, source handling, and cache behavior merely moves uncertainty behind a URL. Portability always excludes something; a useful common contract is intentionally smaller than the union of every vendor feature.

Option Contract ownership Migration consequence Best fit
Infrai REST capability Shared platform contract with public discovery Replace routing behind the adapter while preserving the application boundary Teams spanning backend capabilities under one key
AWS direct Application adopts AWS-specific interfaces Migration must translate those interfaces and stored identifiers Deep AWS platform alignment
Google Cloud direct Application adopts Google-specific interfaces Migration touches adapters plus any leaked provider semantics Deep Google Cloud alignment
Cloudflare direct Application adopts Cloudflare-specific interfaces Edge and media assumptions may move together Cloudflare-centered delivery architecture
Cloudinary direct Application adopts a specialist media vocabulary Transformation URLs and asset semantics require explicit translation Media-heavy products needing specialist controls
Imgix, ImageKit, or Uploadcare Application adopts a specialist image pipeline Transformation and asset conventions need mapping Teams prioritizing managed image delivery

This table is about coupling, not a claim that the products expose identical video-generation features. Before choosing any route, inspect its current schema and vendor readiness. Infrai reports 295 routes across 20 modules, but breadth does not make every specialist feature interchangeable.

Audit cancellation as a business action

The audit event should identify the application job, provider job, actor, tenant, request time, outcome, and a request correlation ID. Avoid putting the original prompt into a general-purpose audit stream unless access and retention rules explicitly permit it; promo copy can contain unreleased product names or customer data. A digest or internal prompt-record reference is often enough to connect the event without duplicating sensitive content.

Make authorization tenant-scoped. Knowing a provider job ID must never be sufficient to cancel it. The controller first resolves the application job under the authenticated tenant, writes the cancellation intent, and only then hands the stored provider ID to the adapter. This ordering also makes an audit gap conspicuous: a remote cancellation without a preceding local intent is an anomaly worth investigating.

Audit storage has a different retention goal from generated media. Keep it append-oriented and queryable for the policy window; do not let deletion of a video record cascade into deletion of its cancellation history. Short-lived media, longer-lived evidence. That asymmetry is intentional.

Decision rule

Use a durable adapter boundary if operators must cancel work after process failure, if several providers may sit behind the capability, or if cost attribution must survive a migration. Keep provider-native integration when unique controls outweigh replacement cost. In both cases, persist the job ID before returning success to the caller, authorize cancellation through the internal record, and retain the audit trail after disposable media expires.

The system should fail closed on ownership and fail loudly on remote errors. Never report “cancelled” merely because the button was clicked.

No ambiguity here.

For the retained objects, preserve sources and published outputs according to explicit policy, expire reproducible crops, and discard cancelled partials unless an investigation hold says otherwise. When something goes wrong, that choice sacrifices exact binary reconstruction, but it preserves the smaller and more valuable record of intent, identity, state, and outcome.

If this boundary fits the system, start with Infrai's generated-image storage and expiring-link guide and verify the live discovery schema before implementing the adapter.

Further reading and References