Long-Running AI Agents in Production: Building a Video Generation SaaS

    This article examines what it takes to turn AI coding assistance into a sellable UGC video generation service. It explains why demo sites fall short of commercial requirements, how spec-driven development turns long-running work into checkable contracts across research, architecture, and development phases, and which mechanisms a reference architecture needs: a queue-based task layer, a generation adapter layer, idempotent billing with a reserve-settle-release ledger, row-level tenant isolation, and observability keyed by task ID. It also covers what long-running agents are good at, which business rules they should not decide alone, common failure patterns, and a minimal pre-launch checklist. Readers will come away with a practical model for running video generation as a recoverable, billable system rather than a script that cannot be reconciled.

    Many teams treat AI-assisted programming as “writing pages faster.” The moment the goal becomes a sellable user-generated content (UGC) video service, the problem shifts from lines of code to whether the system can stay consistent, recoverable, and billable for hours at a time. Cross-border e-commerce sellers generally do not care how the workflow is wired together. They care whether a day produces a large volume of usable finished videos, whether failures can be retried, and whether credits are deducted correctly. Turning “teaching a person to fish” into a clickable fish is fundamentally a matter of architecture and engineering discipline, not the eloquence of a single conversation.

    1. Why a Demo Site Cannot Carry a Commercial Product

    A demo site usually has an upload form, a preview, and a fake progress bar. A commercial product has to answer at least five categories of questions at the same time.

    Request entry point. Inputs such as images, copy, duration, aspect ratio, and voice must be validated. Anything out of range should be rejected explicitly, so dirty data never reaches the expensive generation stage.

    Long-running work. A single video often takes minutes, so it cannot occupy a synchronous request thread. You need task queuing, a state machine, timeouts, cancellation, and idempotency.

    Multi-tenant data. Users must see only their own assets, finished videos, and bills. Isolation belongs in data-layer policies and API authorization — two separate gates — not in hiding buttons in the frontend.

    Accounts and billing. Phone or email verification, session tokens, credits or quotas, whether failures are refunded, and whether repeated clicks cause repeated charges all require a ledger, not temporary variables.

    Observability. Queue depth, success rate, average duration, storage growth, and exception traces must be traceable by task ID. Without these, a so-called “full-stack long task” merely postpones uncertainty until the middle of the night.

    2. Spec-Driven Development: Splitting Long-Running Work into Checkable Contracts

    What breaks long-running automation is rarely a single line of code. It is the quiet change of definitions midway through: a table name changes, state enums disagree, or the charging point migrates from “on submit” to “on success.” Spec-driven development requires the contract to be written down first, and only then allows implementation.

    A useful approach is to split the build into three phases and define the exit condition for each.

    Research phase produces constraints only, no business code. Define the target users, assumed daily capacity, per-task time limit, acceptable failure rate, asset retention period, and compliance red lines (likeness rights, trademarks, misleading claims). Write “can generate video” as measurable indicators: how many seconds after submission a task enters the queue, the requirement that every failure carries an error code, and the rule that one idempotency key must never produce two charges.

    Architecture phase produces boundaries and the data model. At minimum: accounts, asset objects, generation tasks, finished-video objects, ledger entries, and audit logs. A reasonable fixed set of task states is CREATED, QUEUED, RUNNING, SUCCEEDED, FAILED, CANCELLED, with transitions allowed only along defined edges. Object storage holds the binaries; the database holds metadata and checksums. Do not put large files into the transactional database.

    Development phase delivers vertical slices. First get “create task → enqueue → simulated execution → success callback → downloadable” working end to end, then swap in the real generation adapter. Every slice needs an acceptance checklist. An agent can modify several modules in a row, but a human must review against the spec at each slice boundary, so the context does not drift after several hours.

    3. Reference Architecture and Key Mechanisms

    Logically the system splits into an access layer, an application layer, a task layer, a generation adapter layer, and a data layer. The access layer handles authentication, rate limiting, and parameter validation. The application layer maintains tasks and the ledger. The task layer decouples work through a message queue, with workers pulling up to a concurrency limit. The generation adapter layer translates internal tasks into external or internal model calls, hiding vendor differences so the implementation can be replaced later without touching the ledger. The data layer contains the relational database, object storage, cache, and logs.

    Asynchronous processing and polling can coexist. The browser or client queries status through short polling or server push; workers do not depend on the client being online. The progress endpoint reads only the status table and never queries the generation process directly, which keeps internal addresses from leaking.

    For idempotency, use “user identifier + client request ID” as the key. A repeated submission returns the same task ID. Billing follows a reserve–settle–release model: quota is frozen before enqueueing, converted to an actual charge on success, and released on failure or timeout. Ledger entries are append-only and never overwritten, which makes reconciliation straightforward.

    Row-level isolation can be implemented with database policies or by forcing a tenant condition into every query, backed by an integration test: two accounts attempt to access each other’s tasks, and every attempt must be rejected. Tokens should be short-lived, with refresh and revocation traceable. A verification code only proves that a message can be received; it cannot replace the authorization model that follows.

    An illustrative, language-neutral state transition set expressing only the constraints:

    1. on_create: validate -> freeze_quota -> persist(CREATED) -> enqueue -> QUEUED
    2. on_start: QUEUED -> RUNNING
    3. on_success: RUNNING -> SUCCEEDED -> settle_quota -> write_object_meta
    4. on_fail: RUNNING -> FAILED -> release_quota
    5. on_retry: FAILED -> QUEUED only if retry count not exceeded and error is retryable

    Workers must separate retryable failures (network jitter, brief overload) from non-retryable ones (non-compliant content, invalid parameters, insufficient quota). Otherwise the queue fills up with poison messages.

    4. What Long-Running Agents Should Do, and What They Should Not Decide Alone

    Long-running agents are good at generating interfaces, table migrations, state machines, and test skeletons in bulk against a spec, and at keeping naming consistent across many files. They should not decide business rules on their own: how many credits a video is worth, whether failures are charged, how many days assets are retained by default, and which content requires human review. These belong in a human-readable spec — change the rule by changing the spec, then the code.

    Common pitfalls in practice include silently renaming fields as the context grows, disabling authentication to “get it running,” committing secrets to the repository, faking asynchronous completion with a synchronous endpoint, and testing only the happy path. The mitigations are to treat the spec file as the single source of truth, allow only one slice to change per round, keep secrets in environment variables and a secret manager, and retain a minimal integration test set: authentication failure, duplicate submission, queue timeout, insufficient quota, and cross-tenant reads.

    Total runtime is usually not one model response. It is the sum of queueing, generation, storage, and human review. Going from research to a demonstrable closed loop in a few hours is normal. When compute or queueing slows down, reduce concurrency and cache the spec and intermediate artifacts, rather than letting the agent rewrite the whole database repeatedly without logs.

    5. A Minimal Pre-Launch Checklist

    Spec and state machine first, pages second. Object storage, queue, relational database, logging, and alerting come before anything that “looks good.” Billing is authoritative only through the ledger, and the task ID is traceable across the whole chain. On the content side, keep at least a complaint channel and deletion capability. Size capacity by “queue waiting time,” not by “how many pages are open simultaneously.” AI-assisted programming can move an individual from “needing a whole team to start” to “one person can build a reviewable skeleton,” but commercial responsibility stays with people: acceptance testing, compliance, secrets, quotas, and failure drills cannot be outsourced to autocomplete.

    Treat long-running tasks as systems engineering — spec first, slice delivery, idempotent billing, recoverable failures — and a video generation service has a chance to become a repeatable, sellable capability instead of another script that cannot be reconciled.