Building a Full-Stack Video Generation SaaS with AI-Assisted Programming: A Three-Hour Practice
This article walks through building a production-oriented video generation SaaS from requirements to a runnable version using AI-assisted programming. It covers why video generation is a strong test case for AI coding, how spec-driven development turns a complex system into executable steps, and the engineering foundations that matter most: data modeling, asynchronous task processing, authentication and credit-based billing, object storage, encapsulation of external generation services, observability, and safe collaboration with AI agents. Readers will learn practical patterns for idempotency, credit pre-deduction and settlement, multi-tenant isolation, state machines, and the common pitfalls to avoid when using AI to deliver a complete business system rather than a single page.
1. From “Writing Pages” to “Delivering Systems”: The Leap in AI-Assisted Programming
Over the past few years, AI-assisted programming tools have mostly been used for lightweight scenarios: local code completion, single-function generation, and building page fragments. For most business systems, that level of capability is enough to answer the “do we have it or not” question, but it still falls noticeably short of what a truly usable production system requires.
The hard part of a production-grade business system has never been whether a single page looks good. It is whether the system has a complete engineering loop: can requirements be decomposed accurately, can data be stored reliably, can tasks be scheduled dependably, can permissions be strictly isolated, can billing be settled correctly, and can exceptions be traced and compensated.
A video generation SaaS platform happens to be a highly concentrated sample of this complexity. It touches user accounts, media upload, asynchronous tasks, long-running computation, credit-based billing, object storage, external generation service calls, status polling, failure retries, and log monitoring all at once. If any single module is designed poorly, it can lead to stuck tasks, duplicate charges, resource leaks, or a broken user experience.
So when AI-assisted programming starts to emphasize long context, long-horizon tasks, agent planning, and systems engineering, the real question worth validating is not “can it generate a page,” but “can it take a complex business system from requirements research all the way to a runnable version.”
2. Why Choose Short-Video Generation SaaS as the Validation Scenario
Short-video generation SaaS was chosen as the practice target not because it “sounds complex,” but because it can fully cover several key capabilities of a modern business system.
1. The Scenario Has Clear Commercial Value
Short-video commerce, bulk material production, and automated marketing content for merchants are all very typical needs in the content-commerce space today. Merchants do not inherently care about models, algorithms, or workflows. They care about three things:
- How much does it cost to generate a single video;
- Can it reliably produce enough content every day;
- Does it require specialist operators, or can it be ordered and used directly.
This means the product cannot stop at the “developer toy” stage. It has to be a closed-loop system that supports registration, top-up, generation, task status queries, and asset reuse.
2. High System Complexity Makes It a Good Test of Engineering Ability
A usable short-video generation SaaS platform needs to cover at least the following modules:
- User registration, login, and authentication;
- Image or material upload and validation;
- Video generation task creation;
- Asynchronous task queue and execution;
- Task status queries and callback notifications;
- Credit or quota deduction;
- Object storage access and resource management;
- Logging, monitoring, and exception alerting;
- Admin console and operations configuration;
- Multi-tenant data isolation and security control.
These modules do not exist in isolation; they constrain and depend on one another. For example, task creation must first complete material validation and quota pre-deduction; task execution must update status and record cost; failed tasks must refund credits; concurrent requests must avoid duplicate charges; and after an external generation service times out, the task must be able to enter a retry or dead-letter flow.
This kind of system is not a simple stitching together of CRUD operations. It is systems engineering in the classic sense.
3. Spec-Driven Development: Turning a Complex Task into an Executable Process
When facing a complex system, simply telling an AI-assisted programming tool to “build me a short-video generation platform” is often not enough. Overly broad instructions tend to produce fragmented output and can even cause context drift, missing modules, and inconsistent interfaces.
A more reliable approach is spec-driven development: define the specification first, then generate the architecture, and finally move into implementation. The overall flow can be summarized as:
- Research phase: clarify target users, core flows, inputs and outputs, and constraints;
- Architecture phase: split modules, define interfaces, design data structures, and set technical boundaries;
- Development phase: generate code module by module, add tests, and run self-checks and revisions.
The advantage of this approach is that it turns “generating a complex system” into several verifiable smaller goals, letting the AI-assisted tool work around clear constraints at every step.
1. Research Phase: From Vague Requirements to a Clear Specification
The research phase needs to answer a few core questions:
- Who is using the system?
- What do users input?
- What does the system output?
- How long does a task take?
- How are failures handled?
- Is billing involved?
- Is multi-tenant isolation needed?
- Is an admin console needed?
- Which dependencies are external services?
- What does the minimum runnable version include?
For example, in a short-video generation SaaS scenario, you can form the following specification summary:
- After logging in, users can upload images or basic materials;
- Users choose generation parameters such as template, aspect ratio, and duration;
- The system creates an asynchronous video generation task;
- Task status falls into pending, queued, running, success, failed, or canceled;
- Credits are pre-deducted when a task is created;
- Credits are refunded when a task fails;
- Users can query task progress and preview results;
- Admins can view tasks, users, and exception records;
- All tasks must carry an idempotency key to prevent duplicate submissions;
- All resource access must pass a permission check.
The clearer the specification, the less likely later generation is to drift from the goal.
2. Architecture Phase: Using Module Boundaries to Reduce Complexity
In the architecture phase, the focus is not on pursuing a complicated design, but on ensuring clear system boundaries, single responsibilities, and extensibility.
A common layering approach looks like this:
- Access layer: handles login, authentication, upload, task creation, and status queries;
- Business layer: responsible for material validation, task orchestration, credit deduction, and template matching;
- Task layer: responsible for task enqueueing, execution, retry, timeout, and status transitions;
- Storage layer: includes relational databases, object storage, caches, and so on;
- Integration layer: wraps external capabilities such as video generation, media processing, and content moderation;
- Observability layer: records logs, metrics, traces, and exceptions.
This layering is not about formalism. It keeps boundaries intact when the AI-assisted tool generates code. For example, upload logic should not directly modify the database, task execution logic should not be exposed directly to the frontend, and credit deduction should not be tightly coupled to generation logic.
When every module has a clear responsibility, replacing one part later will not affect the whole system.
4. Data Model Design: Making State, Resources, and Billing Traceable
The data model design of a video generation SaaS is the foundation of the entire system. If the data model is poorly designed, tasks, billing, and permissions all become complicated downstream.
A minimum usable data model usually includes the following types of entities:
- Users: record identity, login information, and status;
- Materials: record metadata for uploaded images or materials;
- Tasks: record the inputs, outputs, and status of video generation tasks;
- Credit ledger: record quota acquisition, freezing, deduction, and refund;
- Callback events: record results returned by external generation services;
- Operation logs: record key actions for auditing and troubleshooting.
Below is a simplified example of a task table structure:
CREATE TABLE generation_task (id TEXT PRIMARY KEY,user_id TEXT NOT NULL,asset_id TEXT NOT NULL,status TEXT NOT NULL,cost_credit INTEGER NOT NULL DEFAULT 0,idempotency_key TEXT NOT NULL,external_task_id TEXT,error_message TEXT,created_at TIMESTAMP NOT NULL,updated_at TIMESTAMP NOT NULL);CREATE UNIQUE INDEX idx_generation_task_idempotencyON generation_task(user_id, idempotency_key);
This design contains several key points:
user_idis used for multi-tenant isolation;idempotency_keyis used to prevent users from submitting duplicate tasks;statusdrives the task state machine transitions;cost_creditrecords the resources a task consumes;external_task_idlinks to the task identifier returned by the external generation service;error_messagepreserves the failure reason for troubleshooting.
For multi-tenant scenarios, beyond business-layer validation, you should also establish unified constraints at the data access layer to ensure users can only read their own tasks and materials. Common practices include:
- Enforcing a user dimension on query interfaces;
- Establishing row-level permission isolation in the database;
- Using separate data access entry points for the admin side and the user side;
- Recording audit logs for sensitive operations.
5. Asynchronous Tasks: Long-Running Generation Cannot Rely on Synchronous Requests
Video generation is usually not a millisecond-level response. It is on the order of seconds, minutes, or even longer. So the system cannot use a synchronous mode where “the request comes in and waits for generation to finish.” It must use an asynchronous task mode.
The core idea of asynchronous tasks is:
- The user initiates a task creation request;
- The system completes parameter validation and credit pre-deduction;
- The task is written to the database and enters the queue;
- A background executor pulls the task and invokes the generation capability;
- After generation completes, the task status is updated;
- The user learns the result through polling or callbacks.
Simplified pseudocode:
# Create tasktask_id = create_task(user_id, asset_id, idempotency_key)reserve_credit(user_id, task_id, cost_credit)enqueue(task_id)return task_id# Execute task in the backgroundtask = fetch_task()if task is null:returnupdate_task_status(task.id, "running")try:result = call_generation_service(task.asset_id)save_result(task.id, result)settle_credit(task.id, "deduct")update_task_status(task.id, "success")except Exception as error:update_task_status(task.id, "failed")refund_credit(task.id)log_error(task.id, error)
When designing asynchronous tasks, focus on the following issues:
- Idempotency: the same task must not be executed more than once;
- Timeout control: an executor must not wait indefinitely;
- Failure retry: transient failures should be retried automatically;
- Dead-letter handling: after multiple failed retries, the task enters a manual-handling queue;
- State consistency: database state and queue state must not conflict;
- Credit consistency: deduct only on success, and always refund on failure;
- Observability: every status change should be traceable.
6. Authentication and Billing: Giving the System a Foundation for Commercial Operation
A SaaS platform truly built for end users must have clear authentication and billing mechanisms. Authentication answers “who can access,” and billing answers “how many resources a user has consumed.”
1. Authentication Design
Authentication generally includes:
- User registration;
- Login verification;
- Session or token management;
- Interface permission checks;
- Resource ownership checks;
- Separation of admin console permissions.
The key principle is that all user resource access must carry the user’s identity, and the server must verify that the resource belongs to the current user. You cannot rely only on hiding buttons in the frontend, nor can you rely only on a simple check of the interface path.
For example, when querying task details, you cannot return data based on the task ID alone. You must also verify that the task belongs to the current user.
task = get_task_by_id(task_id)if task.user_id != current_user_id:return forbidden()return task
2. Credits and Quota Billing
Billing design should follow the principle of “pre-deduct first, then settle, and refund on failure.” This avoids discovering insufficient balance only after a task has finished executing, and it avoids charging for tasks that failed.
A typical credit ledger model can include:
- Credit account: records the user’s current available credits;
- Credit ledger: records every credit change;
- Freeze record: records the pre-deducted amount at task creation;
- Settlement record: records the final deduction after a task succeeds;
- Refund record: records the return after a task fails.
A simplified flow is as follows:
1. User creates a task2. Check whether credits are sufficient3. Freeze the corresponding credits4. Create the task record5. Execute the generation task6. Formally deduct credits after success7. Release frozen credits after failure8. Record the ledger throughout the whole process
To avoid duplicate charges in concurrent scenarios, each task should have a unique idempotency key, and a unique constraint should be established on the credit ledger table. This way, even if a request arrives more than once, only one valid deduction record is created.
7. Object Storage and Media Resource Management: Do Not Put Large Files in the Database
A video generation SaaS inevitably involves resources such as images, videos, templates, and cover art. These resources are not suitable for storing directly in a relational database and should instead be placed in object storage.
The advantages of object storage are:
- It is well suited to storing large files;
- Access paths are independent;
- Lifecycle management can be configured;
- It can combine with signed-access mechanisms to control permissions;
- It can be decoupled from database metadata.
The database usually stores only resource metadata, such as:
- Resource ID;
- User ID;
- File type;
- File size;
- Storage path;
- Access URL;
- Creation time;
- Moderation status.
When a user uploads an image, the flow can be:
1. The client requests an upload credential;2. The server verifies the user identity and file type;3. The client uploads to object storage;4. The server records the resource metadata;5. Later tasks use this resource to generate video.
If the generation result involves private content, it is not advisable to expose a public link directly. Instead, the resource should be returned through a temporary access URL or a controlled interface.
8. Wrapping External Generation Capabilities: Do Not Let Business Logic Depend Directly on Underlying Services
Video generation often relies on external generation capabilities or model services. Regardless of what the underlying capability is, the business system should avoid directly coupling to specific interfaces and should instead wrap them through a unified internal service layer.
The internal service layer should be responsible for at least:
- Request parameter conversion;
- Timeout control;
- Retry strategy;
- Error code mapping;
- Result validation;
- Cost recording;
- Callback signature verification;
- Resource transfer and storage.
For example, the business system should not care whether the external service returns an original task ID or a temporary URL. It only needs to know:
submit_generation(params) -> external_task_idquery_generation(external_task_id) -> status, result_url
The benefit of this is that when the underlying generation capability is switched, upgraded, or replaced, the upper business logic does not require large-scale modification.
9. Observability: Complex Systems Must Be Traceable
For long-running task systems, observability is not optional. It is infrastructure.
A video generation task may go through the following steps:
- User submission;
- Material upload;
- Parameter validation;
- Credit pre-deduction;
- Task enqueueing;
- Executor pull;
- Calling the generation service;
- Generating;
- Result saving;
- Credit settlement;
- Status update.
If any of these steps fails, the system must be able to answer:
- Which step is the task stuck at?
- Has the user already been charged?
- Was it executed more than once?
- What did the external service return?
- Does the user need to retry?
- Is manual intervention required?
Therefore, the system should record complete trace logs and, as much as possible, generate a unique tracking identifier for each task. For key status changes, it is recommended to record:
- Task ID;
- User ID;
- Current status;
- Timestamp;
- Operation source;
- Error message;
- External request summary.
On this basis, you can build metrics and alerts, such as:
- Task creation success rate;
- Task execution failure rate;
- Average generation time;
- Queue backlog count;
- Number of abnormal credit changes;
- External service timeout ratio;
- Number of failed callbacks.
10. AI Agents in Development: From “Generating Code” to “Generating Engineering”
In long-horizon AI-assisted programming practice, an agent is not simply outputting code from a prompt. It can take on a composite role similar to a junior architect, developer, and tester. But it still needs clear constraints and review mechanisms.
A relatively reliable collaboration approach is as follows:
1. Generate a Research Checklist
Have the AI-assisted tool first produce a requirements list, user stories, boundary conditions, and acceptance criteria, rather than writing code immediately.
2. Generate an Architecture Draft
This includes module breakdown, directory structure, interface definitions, data model, and the task state machine.
3. Generate Implementations Module by Module
Generate step by step by module—interfaces, database, task queue, frontend pages, admin console—avoiding generating the entire system at once.
4. Automatically Add Tests
Generate test cases for key paths, such as:
- Access without login should fail;
- Insufficient balance should prevent task creation;
- Duplicate submissions should create only one task;
- Generation failure should refund credits;
- A user cannot access another user’s task;
- External callbacks must verify their source.
5. Self-Check and Revision
Have the agent check the implementation item by item against the specification for consistency and fix omissions.
6. Human Review
Developers still need to focus their review on:
- Whether the permission design is rigorous;
- Whether the billing logic is consistent;
- Whether keys and configuration are secure;
- Whether external calls are controllable;
- Whether exception paths are complete;
- Whether there is over-engineering;
- Whether it is deployable in a production environment.
The value of AI-assisted programming is not to fully replace developers, but to free developers from repetitive labor so they can focus more on architecture, constraints, review, and key decisions.
11. Common Pitfalls and How to Avoid Them
In long-horizon task practice, the following problems are far from rare.
1. Context Drift
As tasks grow longer, the model may forget earlier constraints, leading to inconsistent interface naming, muddled status fields, or duplicated functionality.
Ways to avoid it:
- Use the specification document as the single source of truth;
- Break large tasks into smaller tasks;
- Produce a verifiable deliverable at each stage;
- Periodically reread the specification and validate the implementation against it.
2. Over-Engineering
Complex systems are easily generated with over-abstracted structures, making them hard to run early on.
Ways to avoid it:
- Build the minimum closed loop first;
- Prioritize getting the main flow running;
- Leave the admin console, complex statistics, and fine-grained permissions for later iterations;
- Validate the design with running results rather than pursuing perfection in advance.
3. Asynchronous State Inconsistency
Task state, queue state, credit state, and external service state may fall out of sync.
Ways to avoid it:
- Use a state machine to constrain status transitions;
- Log every status change;
- Use idempotency keys;
- Route failed tasks into a compensation flow;
- Periodically scan for tasks that have been stuck for a long time.
4. Billing Errors
Billing logic is prone to errors in scenarios involving concurrency, retries, failures, and delayed callbacks.
Ways to avoid it:
- Pre-deduct first, then settle;
- Always refund on failure;
- Credit ledger entries must be unique;
- Use database transactions for key operations;
- Set up alerts for abnormal credit changes.
5. Security Risks
User uploads, resource access, and admin management are all risk points.
Ways to avoid it:
- Validate the type and size of all uploaded resources;
- Use controlled access for private resources;
- Separate admin and user backend permissions;
- Keep sensitive configuration out of the code repository;
- Record audit logs for key operations.
12. Conclusion: AI-Assisted Programming Enters the Systems Engineering Stage
From this complete practice of building a short-video generation SaaS, it is clear that AI-assisted programming is moving from “helping write code” into “participating in systems engineering.”
In the past, developers mainly used AI tools to solve the following problems:
- Quickly completing functions;
- Generating boilerplate code;
- Writing test cases;
- Explaining errors;
- Writing documentation.
In long-horizon task scenarios, AI tools now begin to participate in a more complete process:
- Requirement decomposition;
- Specification definition;
- Architecture design;
- Data modeling;
- Interface design;
- Asynchronous task design;
- Permission and billing design;
- Testing and self-checking;
- Documentation generation;
- System iteration.
This does not mean developers are no longer important. On the contrary, the importance of developers is shifting to more critical positions:
- Defining the right problem;
- Designing a sound architecture;
- Clarifying non-functional constraints;
- Reviewing security and consistency;
- Controlling cost and risk;
- Taking responsibility for the final system.
Completing a video generation SaaS prototype—with registration, upload, task creation, asynchronous execution, credit billing, and status queries—within a time window on the order of three hours reflects the efficiency gained from combining AI-assisted programming with systems engineering methods. It shows that the minimum closed loop of a complex business system can be built faster, and that developers can validate from requirements to a runnable system in less time.
Going forward, the real value of AI-assisted programming lies not in generating more code, but in helping developers build systems faster, validate assumptions, and reduce the cost of trial and error. The more tightly model capability, engineering standards, and developer judgment are combined, the higher the efficiency of software delivery.
