How Long-Running AI Agents Build a Video SaaS: A Spec-Driven Approach
This article examines why building a video generation SaaS is a systems engineering problem rather than a simple page-generation task. It explains how long-running AI agents drift from their goals and how spec-driven development, phase gates, and rollback checkpoints keep them on track. The core architecture, asynchronous job state machine, authentication, credit-based billing, asset storage, content moderation, observability, and acceptance criteria are all covered for engineers building reliable agent-driven systems.
1. Reframing the Problem: This Is Systems Engineering, Not Page Generation
The core insight from the original experiments is that having an agent build a video generation SaaS is difficult not because it needs to produce a few pages, but because it must simultaneously handle three engineering constraints: long-running tasks, state consistency, and permissions with billing. Video synthesis often takes several minutes, so requests must be asynchronous; user identity, verification codes, tokens, and credit deductions must be atomic; and assets and final videos must land in object storage and pass content moderation. Handing all of these constraints to an agent at once is essentially a test of its long-range planning and context retention.
So this article strips away specific product features and focuses only on the general technical problem: how to use spec-driven development (SDD) to let AI coding tools reliably deliver a runnable system during long tasks.
2. Why Long Tasks Drift, and How to Constrain Them
Long tasks usually fail not because of poor code quality in a single step, but because of goal drift: interfaces defined early get rewritten midway, error handling gets simplified, and billing logic gets deferred with a “just make it run first” attitude. There are three practical layers of constraints.
The first layer is spec-first. Before writing any code, produce the requirements spec, data model, and interface contracts, and define the acceptance criteria. An example structure:
# Spec- Goal: user uploads an image, asynchronously generates a short product video- Data model: User / Asset / Job / CreditLedger- Interface contract: POST /jobs -> 202 + jobId- Acceptance: 20 concurrent jobs with no lost orders; credits never go negative
The second layer is phase gates. Fix the workflow as “research -> architecture -> development -> self-test,” where each phase must produce artifacts written to disk, and the next phase cannot begin until the current one passes.
The third layer is rollback checkpoints. Commit once every time a vertical slice (auth, upload, jobs, billing) is complete, so that when something goes wrong, the cost of rolling back stays manageable.
3. Layered Architecture of the Target System
A minimal viable system can be split into five layers, decoupled from each other through clear contracts:
- Access layer: handles authentication, rate limiting, and parameter validation;
- Application layer: four domain services for users, assets, jobs, and billing;
- Async layer: message queue plus worker nodes, carrying minute-level generation tasks;
- Storage layer: relational database for metadata, object storage for images and final videos;
- Support layer: logging, monitoring and alerting, content moderation.
The key design principle is: synchronous interfaces only validate and enqueue; they never block waiting for the generation result.
Client -> API(auth/rate limit) -> JobService -> MQ -> Worker -> Object Storage| |credit hold/settle moderation + transcode
4. Async Tasks and the State Machine
Jobs must have an explicit state machine to avoid the “stuck but nobody knows” situation. Recommended states: PENDING -> RUNNING -> SUCCEEDED | FAILED, with a timeout and a retry limit. Retries must be idempotent; the usual approach is to give each job a business-unique key and deduplicate during settlement.
def on_job_done(job, ok):if job.state != "RUNNING":return # Idempotent: ignore duplicate callbacksjob.state = "SUCCEEDED" if ok else "FAILED"settle_credits(job) # Settle on success, refund the hold on failure
You also need a dead letter queue to catch jobs that still fail after multiple retries and trigger alerts.
5. Authentication, Verification Codes, and Credit Billing
Authentication follows the common approach: phone number with a verification code login exchanges for a short-lived access token and a refresh token, and the token is silently renewed after it expires. What is really error-prone is billing. It is recommended to use a two-phase ledger of hold + settle/refund, where every change is written to an immutable transaction table:
CREATE TABLE credit_ledger (id BIGSERIAL PRIMARY KEY,user_id BIGINT NOT NULL,delta INT NOT NULL, -- negative for hold, positive for refundref_type TEXT NOT NULL, -- job / refundref_id BIGINT NOT NULL,created_at TIMESTAMPTZ DEFAULT now());
Deductions must happen inside a database transaction, and a conditional update like UPDATE ... WHERE balance >= cost guarantees the balance never goes negative; when the balance is insufficient, reject the request before enqueueing to avoid wasting compute on invalid jobs.
6. Assets, Final Videos, and Content Safety
Images and videos are large and long-lived, so they should go to object storage, with the database storing only keys and metadata. Uploads use one-time credentials for direct upload, reducing bandwidth pressure on the application layer. After a final video is generated, it enters moderation; if machine moderation fails, the job is marked failed and the credits are refunded. Also set lifecycle policies for temporary assets to control storage costs.
7. Observability and Cost Control
A long-task system must be observable: carry the same trace ID through each job, record queue time, execution time, and retry count; set threshold alerts for queue backlog, failure rate, and per-job cost. On the cost side, set concurrency limits and daily quotas per job type to prevent abnormal traffic from blowing through the budget.
8. Acceptance Checklist
- Submit 20 concurrent jobs with no loss and no duplicate settlement;
- Expired tokens renew automatically, and unauthorized access is rejected;
- Jobs are blocked up front when the balance is insufficient;
- Credits for failed jobs are automatically refunded with a traceable ledger;
- Queue backlog and failure rate trigger alerts.
9. Conclusion
Handing “generate a video SaaS” to a long-range agent, the real value is not how much code it writes, but whether it can hold the architectural boundaries during hour-level tasks: async without blocking, billing without over-deducting, state that is traceable, and failures that can be rolled back. Constraining goals with spec-driven development, controlling pace with phase gates, and lowering rollback cost with vertical slices are the key practices that move AI coding into its next stage.
