How Long-Running AI Agents Build a SaaS Platform in Three Hours
This article explains why long-running tasks, rather than single-shot code generation, are the real dividing line for AI coding agents. It covers spec-driven development as a four-stage workflow, a minimal three-layer architecture for a commercial video generation platform, and the three areas most prone to failure: asynchronous queues, progress reporting, and idempotent credit billing. It also lists common pitfalls observed in practice and gives recommendations on capability boundaries and adoption.
1. Why Long-Running Tasks Are the Real Dividing Line
Over the past two years, AI coding tools have mostly been evaluated on short interactions: completing a function, generating a page. The criteria were intuitive — does a single conversation run end to end, does the page look good. But once the task scales up to a commercially usable system, the bottleneck is no longer the quality of a single generation. It is maintaining a consistent target state across tens of thousands of tokens of context and an execution span of several hours.
Long-horizon capability has to satisfy three things at once:
- No goal drift: the requirements still hold after dozens of files and hundreds of tool calls.
- Recoverable state: a failed retry resumes from the breakpoint instead of starting over.
- Engineering constraints: output follows the agreed layering, naming, and interface conventions instead of improvising each round.
This is the fundamental difference between a systems-engineering view and a “write some code” view. For a video generation platform aimed at merchants, the complexity is not in any single algorithm. It is that requirements expand exponentially: frontend routing and state management, backend service layering, relational table design and row-level security, asynchronous queues and progress callbacks, phone-number verification codes and token authentication, credit deduction and idempotency. If any one piece is missing, the system cannot ship.
2. Spec-Driven Development: From “Can Write Code” to “Can Deliver a System”
The core of Spec-Driven Development is turning unverifiable natural-language wishes into verifiable engineering contracts. A four-stage approach works well, with each stage producing a reviewable document artifact:
- Research stage: output a capability list and compliance boundaries, specifying input asset requirements, output resolution and duration, the expected time range per task, and concurrency limits.
- Architecture stage: output a layering diagram, data model, interface contracts, and a failure-state matrix.
- Development stage: implement in dependency order — contracts before implementations, skeleton before decoration.
- Acceptance stage: regress against a fixed test suite, and write any failure back into the spec.
An illustrative spec fragment (pseudocode, meant to express constraints rather than a concrete product API):
spec:goal: merchants upload product images, system auto-generates short promo videosconstraints:- task duration <= 180s, timeouts enter the retry queue- all write operations must be idempotent, idem key = user ID + asset hash- credit deduction and task creation share the same transaction boundaryacceptance:- with 50 concurrent tasks, progress callback latency < 5s- resubmitting the same asset does not charge twice
The key point: the spec is the single source of truth. When the implementation conflicts with the spec, change the implementation, not the spec. That is how a long-running task avoids “forgetting what it is doing” halfway through.
3. Architecture Layering: The Minimal Skeleton of a Commercial Platform
A three-layer structure with separated frontend and backend plus asynchronous tasks is a reasonable default.
Access layer (frontend): a component-based framework with server-side rendering. App Router-style directory conventions naturally bind pages, layouts, and API routes together, which makes it easy to read the auth state on the server and reduce the token exposure surface. Form uploads go directly to object storage via presigned URLs, so large files never pass through the application service.
Service layer (backend): an async framework with type annotations first, split into controller / service / repository. Controllers only validate parameters and handle authentication, business orchestration lives in services, and data access is consolidated in repositories, which makes swapping storage and writing unit tests easier later.
Data and task layer:
- A relational database holds four core tables: users, assets, tasks, and credit transactions.
- Row-level security policies ensure “a user can only read their own tasks”.
- A message queue absorbs traffic spikes; the task state machine is
pending → running → succeeded / failed. - Object storage holds source assets and finished videos; logging and monitoring alerts cover task success rate and queue backlog.
Illustrative core table:
create table render_task (id bigserial primary key,user_id bigint not null,asset_key text not null,status text not null default 'pending',idem_key text not null,cost_credit int not null default 0,created_at timestamptz default now(),unique (user_id, idem_key));alter table render_task enable row level security;create policy own_task on render_taskusing (user_id = current_setting('app.user_id')::bigint);
4. Async, Polling, and Billing: The Three Easiest Places to Get Wrong
Async queue: video generation is a minute-level task and must never be awaited synchronously inside a request thread. The producer only writes the task and the queue message; consumers pull according to a concurrency setting, retry with exponential backoff on failure, and move to a dead-letter queue past a threshold while rolling back credits.
Progress reporting: polling or subscription-based push both work, but every response must carry a task version number so a stale response cannot overwrite a newer state. Adaptive polling intervals are recommended: dense for the first 10 seconds, sparser afterwards, to cut wasted requests.
Idempotent billing: this is the line between a commercial product and a demo. Deduction and task creation happen in the same transaction, a unique key backstops duplicate submissions, and refunds go through a reverse transaction entry rather than deleting records, keeping the ledger auditable.
async def submit(user_id, asset_key, idem_key):async with tx():await debit(user_id, COST, idem_key) # a unique key conflict rejects the requesttask = await repo.create(user_id, asset_key, idem_key)await queue.publish("render", {"task_id": task.id})return task.id
5. Common Pitfalls in Practice and How to Avoid Them
- Context drift: over a long task the model gradually leans toward “looks good” and ignores the spec. Force a spec summary write-back at the end of each stage, and have it restate the constraints before acting.
- Dependency and version conflicts: multiple rounds of generation easily introduce mutually incompatible dependency versions. Lock the version list first, then allow installation.
- Non-replayable migrations: repeatedly altering tables breaks the migration chain. Allow append-only migrations each round and forbid rewriting history.
- Hardcoded secrets: generated code often writes configuration into source. Declare a configuration whitelist in the spec and inject everything from the environment.
- Compute queuing and rate limits: lower throughput at peak times is normal, so build retry and degradation strategies into the design instead of relying on a single successful run.
6. Capability Boundaries and Adoption Advice
Long-running agents are good at engineered delivery with clear acceptance criteria: clean layering, stable contracts, regression-testable output. They are not good at ambiguous business judgment or compliance discretion; humans must set those boundaries.
Three practical recommendations: write the spec in detail and define acceptance cases first; commit in small steps so every stage can be rolled back; and treat security, idempotency, and observability as first-class requirements rather than add-ons. If elastic compute and managed components are needed, general-purpose cloud services (object storage, message queues, container platforms, logging, monitoring and alerting) can carry the non-core paths, leaving the model to focus on business orchestration.
The conclusion is not mysterious: whether a platform can be built in three hours depends on spec quality and constraint strength, not on how loudly a tool is marketed. Managing long-running tasks as “verifiable engineering outsourcing” is what moving AI coding to the next level actually means.
