Building a Full-Stack Short Video Generation SaaS with Long-Horizon AI Agents
Long-horizon AI agents are increasingly expected to handle system-level work, but their value in production depends on clear specifications, stable architecture boundaries, and complete engineering guardrails. This article presents a full-stack practice for a UGC short-video generation SaaS in which users upload images and the system automatically generates short videos. It covers authentication, credit billing, asynchronous job orchestration, object storage, database isolation, queues, callbacks, monitoring, acceptance testing, and common pitfalls. Readers will learn how a spec-driven workflow can guide an agent from research and architecture to implementation and validation for an operable SaaS.
The short version: AI-assisted programming is moving from “generating a page that looks usable” to “taking on system-level, long-running tasks.” But the value of long-running tasks does not depend on how much code a model can write in one pass. It depends on whether the requirements specification is clear, the architecture boundaries are stable, and the engineering guardrails are complete. This article uses a UGC content-generation SaaS—where users upload images and the system automatically generates short videos—as an example to discuss how long-horizon agents can complete the full workflow from research and architecture to development and acceptance. The scenario includes authentication, credit billing, asynchronous jobs, object storage, databases, queues, callbacks, and monitoring, which is enough to test whether an agent has systems engineering capability.
1. Target Definition: An Operable SaaS, Not a Demo
A demo page only needs three steps: upload, generate, and display. A commercial SaaS must answer more questions: How do users log in? How are credits reserved and rolled back? How is video generation status managed over several minutes? How are failures retried? How are assets isolated? How are jobs rate-limited? How are costs audited? Therefore, the first step is not to write code, but to turn the target into an acceptable system specification.
It is recommended to split the product target into four layers:
- User journey: registration and login, project creation, asset upload, template selection, generation submission, progress tracking, download or sharing, and credit details.
- Business capabilities: project management, asset management, generation jobs, credit accounts, orders or plans, and admin configuration.
- Non-functional requirements: idempotency, observability, retryability, tenant isolation, rate limiting, auditing, and cost control.
- Acceptance criteria: every interface has a contract, every state has a transition, every failure has an error code, and every credit charge has a ledger entry.
2. Spec-Driven Development: Contracts Before Implementation
The most common problem with long-horizon agents is that they “drift away from the target while writing.” The solution is to use the specification document as the single source of truth and adopt a spec-driven development (SDD) process: research, architecture, development, and validation. The specification should include domain terminology, role permissions, an interface list, data tables, state machines, error codes, acceptance cases, and non-functional constraints.
The following prompt skeleton can be used to constrain the agent’s output:
Role: You are a system architect and full-stack developer.Goal: Build the minimum operable version of a short-video UGC generation SaaS.Constraints:- Use a layered backend architecture and decouple business logic from the video generation service.- All write endpoints must support an idempotency key.- Generation jobs must be asynchronous, and the state machine must not allow skips.- Credit billing must use a three-stage reserve, confirm, and rollback flow.- Enable row-level security policies in the database and isolate records by owner_id.- Output interface contracts, table structures, state machines, error codes, and a test checklist.Process: First output research and architecture decisions, then database and interfaces, then develop module by module, and finally provide acceptance scripts.
3. Layered Architecture: Split Long Tasks into Stable Boundaries
The recommended architecture is divided into an ingress layer, an authentication and rate-limiting layer, a business service layer, a task orchestration layer, generation workers, a data and storage layer, and an observability layer. The ingress layer handles REST interfaces and parameter validation. The authentication layer handles phone-number verification-code login, signed tokens, sessions, and permissions. The business layer handles projects, assets, and credits. The task orchestration layer creates jobs, enqueues them, and updates status. Workers consume the queue, call the video generation service, and upload results to object storage. Logging services and monitoring alerts run through the entire chain.
The key principles are “interface first, service decoupling, and queryable state.” The video generation service should be abstracted through an adapter so that business code is not tied to a specific model service. Object storage uses generic category capabilities to store original assets and generated results. A message queue carries asynchronous jobs. A relational database stores business state and the credit ledger. A container platform hosts service deployment.
4. Data Model and Security Isolation
The core tables can be designed as follows:
users: user ID, phone hash, status, created time.projects: project ID, owner_id, name, template configuration.assets: asset ID, owner_id, object storage key, type, hash.generation_jobs: job ID, project_id, owner_id, status, parameter JSON, reserved credits, retry count, error code.credit_ledger: ledger ID, user_id, job_id, change value, reason, created time.idempotency_keys: idempotency key, user_id, response snapshot, expiration time.
Row-level security policies should ensure that users can only read and write records whose owner_id equals the current user. Asset downloads use short-lived signed URLs. Phone numbers are stored only as hashes or encrypted values. Admin operations are written to audit logs. Credit billing must complete the reservation within the same transaction boundary as job creation. Credits are confirmed and deducted when the job succeeds, and rolled back when the job fails or times out. The ledger is append-only and is not modified.
5. Asynchronous Jobs and State Machine
Video generation takes time and must be asynchronous. The job creation endpoint returns 202 and a job_id, and the frontend polls or receives a Webhook. The recommended state machine is: queued → validating → rendering → uploading → succeeded; failure at any step enters failed, and retryable jobs enter retry_wait. A direct transition from queued to succeeded is forbidden.
POST /v1/projects/{project_id}/generationsIdempotency-Key: <uuid>{ "template_id": "tpl_001", "asset_ids": ["a1","a2"], "duration_sec": 15 }-> 202 { "job_id": "j_123", "status": "queued", "cost_credits": 10 }
Workers need to implement queue consumption, timeout control, exponential backoff retries, a dead-letter queue, result upload, status callbacks, and credit confirmation or rollback. All status updates use conditional updates. For example, a job can be updated to uploading only when its current status is rendering, which prevents concurrent overwrites.
6. Authentication, Rate Limiting, and Observability
Authentication uses phone-number verification-code login, signed tokens, and session refresh. Write endpoints validate idempotency keys. Rate limiting is applied by user and IP. Generation jobs have concurrency caps and daily quotas. The observability layer should include at least request logs, job logs, error-code statistics, queue backlog, generation latency, success rate, credit ledger reconciliation, and alert rules. A long-running task system without observability cannot be operated.
7. Acceptance Testing and Common Pitfalls
Acceptance should cover the following: duplicate submissions do not double-charge; failed jobs automatically roll back credits; unauthorized access is denied; queue backlog triggers alerts; object storage signed URLs expire; illegal state machine transitions are rejected; and ledger reconciliation is consistent. Common pitfalls include interface contract drift, inconsistent error codes, duplicate uploads caused by retries, credit deduction and job creation not being in the same transaction, and loss of long-running task context. The solutions are specification freeze, contract tests, idempotency keys, state machine constraints, and phased acceptance.
Conclusion
Long-horizon agents can significantly improve efficiency from requirement decomposition to code generation, but commercial systems still require humans to set boundaries and acceptance criteria. Clear specifications, fixed state machines, and solid security and ledger design are what allow agents to move from “writing pages” to “building systems.”
