Building a Video Generation SaaS in 3 Hours: A Long-Horizon Agent Test
This article documents a three-hour automated development experiment using a long-horizon AI agent to build a multi-tenant SaaS platform that turns uploaded images into short promotional videos. It explains why long-horizon tasks are harder than generating a landing page, and presents a spec-driven development (SDD) workflow that moves through research, architecture, and implementation with reviewable documents at each step. Key technical sections cover multi-tenant data isolation with row-level security, asynchronous render task orchestration with a six-state machine and idempotency, and a two-phase credit model that reserves quota before settlement. The conclusion highlights what long-horizon agents do well, where human oversight is still required, and four reusable practices for teams.
1. Why Long-Horizon Tasks Are Much Harder Than Writing Pages
Over the past two years, most people’s impression of AI coding tools has stopped at “generating a good-looking landing page.” But when the goal shifts from a demo page to a commercially usable software service, the scale of the problem changes fundamentally: it is no longer single-file code completion, but systems engineering that spans services, data, and permissions.
Take a SaaS platform where users upload an image and the system automatically generates a short promotional video. A minimum viable commercial version involves at least four layers of capability: an access layer (sign-up, login, quota, and billing), an application layer (asset management, task submission, and status queries), an asynchronous execution layer (render queueing, retries, and timeouts), and a data layer (multi-tenant isolation, auditing, and idempotency). These four layers are tightly coupled, and an oversight in any one of them can be amplified into a production incident.
This is exactly where a Long-Horizon Agent adds value: it must maintain goal consistency and context coherence across hours of continuous execution, breaking a “system-level requirement” into verifiable engineering steps instead of forgetting the constraints from step one by the time it reaches step three. This article is based on a three-hour automated development experiment and abstracts a transferable methodology from it.
2. Method First: A Three-Stage Spec-Driven Development (SDD) Workflow
The experiment used a spec-driven development model that forced the model to proceed through “research → architecture → development,” producing a reviewable specification document at each step before moving on. The benefit is turning uncontrollable free-form generation into an auditable engineering pipeline.
The research-stage spec should include target users and core scenarios, a feature list with priorities, non-functional targets (concurrency, latency, availability), and compliance and data boundaries. The architecture-stage spec should include service boundaries, the data model, the state machine, and failure-handling strategy. The development stage then proceeds in small module-by-module commits, each with its own verification method.
A validated prompt skeleton looks like this (illustrative, not tied to a specific product interface):
You are a senior system architect. Follow the process below strictly. At each step, output the specification document first, and continue only after I confirm:1) Research: list user roles, core use cases, non-functional targets, and a risk list;2) Architecture: provide service boundaries, table DDLs, the task state machine, and idempotency and retry strategy;3) Development: implement module by module, with run and verification steps for each module.Constraints: all write operations must be idempotent; all cross-tenant queries must include a tenant filter.
3. Data Layer Design: Multi-Tenant Isolation Is the First Red Line
The biggest difference between a SaaS product and a single-user application is tenant isolation. A common industry practice is to add a tenant identifier to every business table and enable row-level security at the database layer, so isolation does not depend on the application layer’s discipline.
create table render_task (id uuid primary key,tenant_id uuid not null,user_id uuid not null,status text not null default 'queued',input_uri text not null,output_uri text,cost_credit integer not null default 0,created_at timestamptz default now());alter table render_task enable row level security;create policy tenant_isolation on render_taskusing (tenant_id = current_setting('app.tenant_id')::uuid);
There are three key points. First, the tenant identifier is injected into the connection context rather than carried by request parameters. Second, all list endpoints enforce pagination and filtering. Third, audit tables are append-only and never updated, making it easy to trace charges and generation records.
4. Asynchronous Task Orchestration: Turning “a Few Minutes of Waiting” into a Controllable State Machine
Video rendering typically takes tens of seconds to a few minutes, so a synchronous request will inevitably time out. The correct approach is to return a task identifier immediately on submission, let a message queue drive execution, and have the client poll or subscribe to status changes.
The state machine should be kept to six states: queued, running, succeeded, failed, cancelled, and timed out. Every state transition should carry a timestamp and a failure reason, and update operations must be idempotent to avoid duplicate charges caused by duplicate consumption.
TERMINAL = {"succeeded", "failed", "cancelled", "timeout"}def on_message(msg):task = repo.get(msg.task_id)if task.status in TERMINAL: # Idempotency: discard if already terminalreturnif not wallet.reserve(task): # Reserve quota first, settle after successrepo.mark(task, "failed", "insufficient_credit")returntry:out = renderer.run(task.input_uri)repo.mark(task, "succeeded", output_uri=out)wallet.settle(task, actual=1)except Retryable as e:queue.retry(msg, delay=e.backoff) # Exponential backoffexcept Exception as e:repo.mark(task, "failed", str(e))wallet.refund(task)
Engineering practice also needs three safeguards: a dead-letter queue to collect tasks that cannot be processed; a timeout scanner that reclassifies tasks stuck in “running” for too long as timed out and refunds them; and object storage with a lifecycle policy for render outputs to control cost.
5. Billing and Quota: Reserve First, Settle Later
The core of a credit system is not “how much to deduct” but “when to deduct and what happens on failure.” A two-phase model is recommended: reserve quota when the task is submitted, settle based on actual consumption after the task succeeds, and unfreeze and refund on failure or timeout. All quota changes are written to a ledger table to guarantee reconcilability.
For authentication, a common combination is SMS verification-code login in exchange for a short-lived access token, paired with a refresh token to extend the session; admin and user permissions are separated, with a second verification for sensitive operations.
6. Experiment Results and Capability Boundaries
Three hours of continuous development is feasible, but the prerequisite is constraining “free generation” into “spec-first, step-by-step verification.” The strength of a long-horizon agent lies in maintaining long-context consistency and the ability to make cross-layer changes; its boundaries are equally clear: real concurrency load testing, production failure drills, and compliance assessment still require human oversight.
Four reusable lessons stand out: specification documents are the signposts for long tasks; idempotency and isolation must be decided at the architecture stage; the asynchronous state machine determines system stability; and billing logic must be tightly bound to execution results. Turning this method into a team template is where the real productivity of these tools lies.
