Building a Short Video Generation SaaS: Specification-Driven Development for Long-Running Tasks
This article explains how to build a short video generation SaaS that handles asynchronous tasks, user credits, file storage, authentication, and monitoring. It covers specification-driven planning, system architecture, database design, reliable task processing, security and consistency concerns, frontend status handling, and a practical pre-launch checklist for moving from a working prototype to a sustainable product.
1. From Generating Pages to Delivering Systems
In the past, many people used smart coding tools to generate a page, complete a function, or quickly build a demo application. These tasks usually have clear boundaries and simple validation: Does the code compile? Does the page render? Does the button work? Results are visible almost immediately.
A genuinely usable short video generation SaaS is much more than a page display. Users need to register and log in, upload assets, submit tasks, check progress, retrieve results, and have credits deducted according to actual usage. The platform must also handle concurrent requests, retries, file storage, task timeouts, permission isolation, data cleanup, and runtime monitoring.
The difficulty of this kind of project is therefore not “writing more code.” It is making multiple subsystems work together under a consistent set of rules. Whether a smart coding tool can maintain context, remember previously established design decisions, and identify dependencies between modules determines whether it can evolve from a code assistant into a system-level development collaborator.
This article uses a general scenario for illustration: a user uploads product images and copy, the system asynchronously generates short-video marketing content through a video generation service, and the final output is a downloadable video file.
2. Why Use Specification-Driven Development
For complex projects, entering a single prompt such as “build me a video generation website” usually produces something that looks complete but lacks critical engineering details. Common problems include:
- User state is stored only on the frontend and is lost after a page refresh.
- Task submission has no reliable asynchronous processing mechanism.
- Video generation failures cannot be recovered.
- Users can read other users’ task records.
- Credit deduction and task creation are not atomic.
- Uploaded files have no size, type, or permission restrictions.
- The database schema works but is difficult to extend.
- APIs lack a consistent error format, making frontend handling difficult.
The core of specification-driven development is to define what the system should do, what it must not do, and how it will be validated before writing code. A recommended sequence is:
1. Requirements Research
First clarify the target users, business flow, and success criteria. For example:
- Do users only upload images, or do they also provide scripts and voiceover parameters?
- Should video generation return results in real time, or run asynchronously in the background?
- Should multiple tasks be supported in parallel?
- Are credits calculated by submission count, video duration, or resource consumption?
- Should credits be automatically refunded after a generation failure?
- Which runtime metrics do administrators need to see?
2. Architecture Design
Split the system into modules such as the client, API service, task scheduling, data storage, file storage, and external generation capabilities, and define how these modules call one another.
3. API and Data Contracts
Define request fields, response fields, error codes, state transitions, and permission rules before development. This prevents the frontend and backend from implementing different interpretations of the same logic.
4. Phased Development
Complete the smallest runnable path first, then gradually add security, retries, monitoring, and optimization. Each phase should produce verifiable results instead of generating all code at once.
3. Overall System Architecture Design
A relatively robust short video generation SaaS can use the following logical structure:
User Browser│├── User Interface│└── API Service├── Identity Authentication Module├── Asset Management Module├── Video Task Module├── Credits and Billing Module└── Administration and Audit Module│├── Relational Database├── Object Storage├── Message Queue├── Background Task Executor└── Logging and Monitoring System
The API service should not wait synchronously for video generation to finish. Video generation is typically a long-running task that may take tens of seconds or longer. If the API keeps the connection open, requests may time out, service threads may be exhausted, and concurrency capacity will drop.
A more reasonable flow is:
- The user submits a generation request.
- The service validates user identity, asset format, and credits.
- A task record is created with a “pending” status.
- The corresponding credits are deducted or frozen.
- The task is published to a message queue.
- The task ID is returned to the frontend immediately.
- A background executor consumes the task.
- After completion, the result URL is written.
- The frontend retrieves status through polling or real-time notifications.
4. Key Principles of Database Design
The goal of database design is not to create as many tables as possible. It is to ensure clear data relationships, traceable states, and controllable permissions.
User Table
At minimum, it should include a user ID, login credential digest, account status, creation time, and update time. Passwords or verification codes must not be stored in plaintext. Sensitive credentials should use secure digests or short-lived tokens.
Video Task Table
The task table is the core of the entire system. It should include:
- Task ID;
- Owner user ID;
- Original asset URL;
- Task parameters;
- Current status;
- Failure reason;
- Result URL;
- Retry count;
- Creation time, start time, and end time.
Task status should use a finite state machine instead of arbitrary strings. Typical states include:
Pending → Running → Completed└→ Failed → Retryable
Once a task enters the completed state, it should not be overwritten by ordinary flows. State updates must include conditional constraints to prevent multiple executors from processing the same task simultaneously.
Credit Ledger Table
Do not maintain only a mutable “remaining credits” value in the user table. A more reliable approach is to record both the account balance and every change in a ledger. Each deduction, refund, or grant should generate an independent record for auditing and dispute investigation.
Credit deduction and task creation need to be completed in the same transaction, or consistency must be guaranteed through an explicit freeze, confirm, and release mechanism. Otherwise, a task may be created without deducting credits, or credits may be deducted without the task entering the queue.
Permission Isolation
All queries must be bound to the current user identity. For example, when querying a task, the condition must not include only the task ID; it must also include the user ID. For administrative data, independent role-based permission checks should be used.
If the database supports row-level security policies, “users can access only their own records” can be pushed down to the data layer, creating a dual defense at both the API and database layers.
5. How to Ensure Reliability in an Asynchronous Task System
The most common problem in video generation tasks is “submission succeeded, but the result disappeared.” Solving this requires designing task states, queue mechanisms, and exception handling together.
Task Submission
The API should perform only lightweight operations:
- Validate parameters;
- Check files;
- Calculate credits;
- Create the task;
- Publish the message;
- Return the task ID.
Do not execute the full video generation flow directly inside the API.
Task Execution
After claiming a task, the background executor should first update its status to “running” and record the start time. A timeout should be set during execution to prevent an abnormal task from occupying execution resources indefinitely.
Retry Mechanism
Transient network errors, temporary resource-service unavailability, and similar issues can be retried automatically a limited number of times. Retries should use increasing wait intervals and record the reason for each failure.
Not all errors are suitable for retry. Deterministic errors such as invalid parameters, corrupted files, or failed content review should fail immediately with a clear message.
Idempotency
Users may click the submit button repeatedly, and the message queue may redeliver a message because of network issues. The same business request needs an idempotency identifier. Before starting a task, the executor should check whether a successful result or execution record already exists for the same request.
Result Storage
After generation is complete, write the video to object storage first, then update the result URL in the database. Do not write the “completed” status first and save the file asynchronously afterward; otherwise, users may see a completed status but be unable to download the result.
6. Authentication, Credits, and File Security
Login and Sessions
The login flow can use a verification code plus short-lived access tokens. Access tokens are used for API calls, while refresh tokens extend the session. Tokens should have expiration times and support active invalidation.
All protected APIs must verify identity on the server. Hiding a button on the frontend does not make the API secure.
Credit Deduction
A “pre-deduct, execute, settle” model is recommended:
- Freeze credits when the task is submitted.
- Confirm deduction after the task succeeds.
- Release or refund credits if the task fails.
- Write every change to the credit ledger.
This prevents users from repeatedly submitting tasks during execution and overdrawing the account balance.
File Uploads
Upload APIs need restrictions on:
- File size;
- File extension and actual media type;
- Image resolution;
- Per-user upload frequency;
- File retention period;
- Whether public access is allowed.
Files in object storage should not remain publicly accessible for long periods. For downloads, the server can generate short-lived access URLs and, when necessary, add watermarks, permission checks, or download limits.
7. Frontend Experience Is More Than “It Works”
For long-running task applications, the frontend focus is not complex animation. It is ensuring that users always know what the system is doing.
After task submission, the page should show clear states:
- Uploading assets;
- Queued;
- Generating;
- Processing results;
- Completed;
- Generation failed.
Polling intervals should be reasonable. Do not send a request every few dozen milliseconds. When a task status has not changed for a long time, the interval can be gradually increased. For scenarios with higher real-time requirements, server push can be used, but polling should still be retained as a fallback after disconnection.
Error messages should be written for users, such as “Unsupported asset format,” “Insufficient credits,” or “Task timed out,” rather than displaying stack traces directly. Technical details should be recorded in logs to avoid exposing internal paths, tokens, or service information.
8. Where Smart Coding Tools Are Truly Valuable
In projects like this, the value of smart coding tools is not only faster code generation. More importantly, they can participate in the following work:
- Breaking vague requirements into executable tasks;
- Identifying dependencies among the frontend, backend, and database;
- Adding boundary conditions according to established specifications;
- Generating test data and API tests;
- Checking whether state transitions are complete;
- Finding missing exception handling and permission checks;
- Locating problems based on runtime logs;
- Maintaining overall architectural consistency through continuous modifications.
However, developers must still take final responsibility. Smart tools may generate code that is formally correct but wrong for the business, or they may default to implementations that are unsuitable for the current scenario. Therefore, it is essential to follow the principle of “design first, implement later; validate first, expand later.”
9. Three Hours of Development Does Not Mean Three Hours to Launch
During automated development, it is possible to build a runnable version within a few hours, but that does not mean the system is ready for commercial use. At minimum, the following checks should be completed before launch:
- Can identity authentication prevent unauthorized access?
- Can users be charged repeatedly?
- Are credits handled correctly after a task fails?
- Can the system apply rate limiting when the queue backs up?
- Can files be downloaded by public guesswork?
- Is database backup configured?
- Do logs contain sensitive information?
- Do task executions have timeouts and retries?
- Are there automated tests for critical APIs?
- Are administrator operations recorded for auditing?
Stress testing should also be performed to observe system behavior under concurrent submissions, large file uploads, a large number of task failures, database connection exhaustion, and similar conditions.
10. Conclusion
Long-running smart coding is changing how software development is organized. In the past, individual developers often had to switch frequently among product, frontend, backend, database, and operations. Now, smart tools can participate in requirement decomposition, architecture design, code implementation, and troubleshooting, enabling a single person to complete more complex system prototypes.
But what ultimately determines project quality is still engineering methodology: whether specifications are defined first, whether a clear data model is established, whether asynchronous tasks are handled correctly, whether permissions and consistency are taken seriously, and whether results are validated with tests and monitoring.
For a short video generation SaaS, “completing a basic version in three hours” can serve as an efficiency metric, but it cannot be treated as a quality conclusion. Only when task reliability, data security, credit consistency, exception recovery, and observability are fully addressed does an application truly move from a demo project to a sustainable product.
