Building a Short-Video Generation SaaS with AI-Assisted Development: Engineering Practices

    This article walks through the engineering work behind a short-video generation SaaS for e-commerce, where users upload product images and the system produces promotional videos. It covers requirements scoping, a layered architecture for frontend, backend, and database, asynchronous task handling with idempotency, phone-based authentication and credit billing with a pre-deduct, confirm, and refund model, a spec-driven workflow for working with large language models, code examples, and common risks with mitigations.

    1. Background: From a Single Tool to a Complete Product

    Demand for short-form video in e-commerce is growing quickly. Merchants care about a few direct metrics: the cost to produce each video, how many videos they can produce per day, and how difficult the tool is to use. A user uploads product images, and the system automatically generates a promotional video. In essence, this kind of service packages video generation models, asset processing, and task scheduling into a product that can be reused.

    The hard part of such a project is not any single piece of code. It is coordinating the whole system. A platform that charges users must handle user identity, resource quotas, asynchronous tasks, file storage, and access control at the same time. Only when these parts work together does the result become a SaaS product that can be delivered and operated.

    2. Requirements: Define the Boundaries Before Implementation

    Requirements analysis is the starting point of the project. It is useful to split requirements into functional and non-functional categories.

    Functional requirements usually include user registration and login, image upload with format validation, submitting generation tasks, checking progress and downloading results, credit top-up and deduction, and basic admin back-office capabilities.

    Non-functional requirements shape the architecture. Video generation usually takes minutes, so it must be processed asynchronously. Concurrency and unit cost need to be estimated in advance. Data from different users must be strictly isolated. Critical operations need audit logs. Failed tasks must be retried or rolled back safely.

    The clearer the requirements, the more stable the architecture and development will be. Vague requirements lead to repeated rework during implementation. This is especially true when large language models assist with development.

    3. Architecture Design

    3.1 Frontend

    The frontend can use a mainstream component-based framework with server-side rendering or hybrid rendering. Requests that involve keys or sensitive configuration should be handled on the server. The browser should store only short-lived access credentials. Pages are organized by function into an upload page, a task list page, a credits page, and a user profile page, which avoids putting all state into a global store.

    3.2 Backend

    The backend should use a layered structure. The routing layer handles protocol conversion and parameter validation. The service layer contains business rules, such as credit deduction and task status transitions. The repository layer encapsulates database access. The task layer interacts with the asynchronous queue and worker processes. Asynchronous Python web frameworks suit high volumes of I/O-bound requests. Combined with strongly typed request models, they can reject most invalid input at the entry point.

    3.3 Database

    The core tables should include at least a users table, a verification code records table, a tasks table, an assets table, and a credit transactions table. The credit transactions table should be an append-only ledger. Each credit increase or decrease creates one entry with a business reference. The balance can be calculated by summing the entries, or a cached balance field can be updated in the same transaction. The ledger pattern makes reconciliation easier and helps with troubleshooting.

    In multi-tenant scenarios, row-level security (RLS) policies can be enabled at the database layer to restrict each user to reading and writing their own records. This mechanism complements application-layer authorization. It does not replace the permission checks in the application.

    3.4 Asynchronous Tasks

    The state machine for a video generation task can have five states: pending, processing, succeeded, failed, and cancelled. State changes are allowed only along defined paths. For example, only a pending task can be claimed by a worker process. Tasks are delivered to worker processes through a message queue. While running, a worker periodically updates a heartbeat timestamp.

    There are two common ways to check task status. The first is client polling. It is simple to implement, but the request frequency must be controlled, typically with exponential backoff. For example, the initial interval might be 2 seconds, increasing gradually up to a maximum. The second is server push, where a long-lived connection or event stream notifies the client in real time. It offers better responsiveness, but connection management is more complex. For small and medium-sized projects, polling is usually the first choice, and the system can move to push when the user experience requires it.

    The retry strategy must work together with idempotent design. Each task carries a unique idempotency key. If a worker runs the same task again and finds that a result already exists, it returns that result directly. This prevents generating two videos or charging credits twice.

    3.5 Authentication and Billing

    Phone verification code login needs matching risk controls. Limit how often codes can be sent to a single phone number. Set a code expiration time, commonly 5 minutes. Store only a hash of each code. Temporarily lock the account after the number of incorrect attempts exceeds a threshold.

    Sessions can use a short-lived access token combined with a refresh token. A short access token lifetime reduces the risk if a token leaks. Refresh tokens must support active revocation. For example, they should be invalidated when a user logs out or changes their password.

    For credit deduction, a three-step pattern works well: pre-deduct, confirm, and refund.

    • When a task is created, check the balance and freeze the required credits in the same transaction.
    • When the task succeeds, convert the frozen credits into actual consumption.
    • When the task fails or is cancelled, release the frozen credits.

    This pattern stops users from submitting tasks when their balance is insufficient. It also prevents losses from failed tasks.

    4. Spec-Driven Development Workflow

    When large language models assist with development, process management matters more than any single prompt. One effective approach is spec-driven development. The work is split into three stages, and each stage produces a document that can be reviewed.

    Research stage. Compile the requirements list. Identify candidate technologies and compare them on maturity, community maintenance, team familiarity, and cost. Also identify risks, such as third-party service quota limits and content compliance requirements.

    Architecture stage. Produce a module diagram, interface contracts, the data model, the task state machine, and error code definitions. Interface contracts should specify field types and required fields precisely, so that both the model and the developers have a consistent reference during implementation.

    Development stage. Implement the modules one at a time. After each module is complete, run its unit tests and integration tests. Move on to the next module only after these tests pass.

    The key to this workflow is human checkpoints. At the end of each stage, a developer confirms that the documents match expectations before the project moves to the next stage. Without these checkpoints, early deviations compound at each stage, and the code eventually drifts away from the requirements.

    5. Key Implementation Examples

    The pseudocode below shows the basic logic that links credit pre-deduction with task status. It focuses on transaction boundaries and idempotency control.

    1. def create_video_task(user_id, image_key, template_id, idem_key):
    2. existing = find_task_by_idem_key(idem_key)
    3. if existing:
    4. return existing.id # Idempotency: return the existing task for duplicate requests
    5. cost = pricing.cost_of(template_id)
    6. with db.transaction():
    7. ensure_balance(user_id, cost) # Raise an exception if the balance is insufficient
    8. task_id = insert_task(
    9. user_id=user_id,
    10. image_key=image_key,
    11. template_id=template_id,
    12. status="pending",
    13. idem_key=idem_key, # Unique constraint prevents duplicate submissions under concurrency
    14. )
    15. freeze_credits(user_id, cost, ref=task_id)
    16. queue.enqueue(task_id)
    17. return task_id
    18. def on_task_finished(task_id, succeeded):
    19. with db.transaction():
    20. if succeeded:
    21. confirm_credits(ref=task_id) # Convert frozen credits into actual consumption
    22. else:
    23. release_credits(ref=task_id) # Refund the frozen credits on failure
    24. update_task_status(task_id, "succeeded" if succeeded else "failed")

    The client-side polling logic is equally simple, but it needs an upper limit to avoid endless requests:

    1. interval = 2 seconds
    2. max_interval = 30 seconds
    3. Loop to query the task status:
    4. If the status is succeeded or failed, stop polling
    5. Otherwise, wait for interval, then query again
    6. interval = min(interval * 2, max_interval)
    7. If the total wait time is exceeded and the task is still running,
    8. tell the user to check the task list later

    6. Common Risks and Mitigations

    1. Duplicate charges: Use idempotency keys and a database unique constraint together. Create the task and deduct credits in the same transaction.
    2. Queue backlog: Set a per-user concurrency limit and a global rate limit. Use priority queues for different task types.
    3. Stuck tasks: Workers report heartbeats regularly. A monitoring job marks any task whose heartbeat has not updated beyond a threshold as failed and triggers a refund.
    4. Asset security: Validate file type and size, and inspect file content again after upload. Store files in a private bucket, and grant access through short-lived presigned URLs.
    5. Runaway costs: Set a daily quota for each user, and send alerts for abnormal high-frequency requests.
    6. Compliance risk: When generated content involves portraits or product assets, implement an authorization confirmation mechanism and a content review process.

    7. Summary

    Building a commercially viable short-video generation SaaS depends on system design. Identity and permissions, the credit ledger, the asynchronous task state machine, and failure compensation are all essential. Large language models can speed up coding considerably, but the quality of their output depends on how clear the requirements and architecture documents are. Complete the research and architecture documents first, then move into development, and keep a human review at each stage. This approach captures the efficiency of automated development while keeping the final system stable, secure, and cost-controlled.