Agentic Coding: Building a Video Generation SaaS with Long-Horizon Tasks

    AI coding is shifting from generating code snippets to delivering complete, production-ready systems. Using a batch marketing video generation SaaS as a case study, this article explores what it actually takes to ship a commercial product through agentic coding. It breaks down the core engineering challenges—stateless backend APIs, multi-tenant databases with row-level security, asynchronous task scheduling, and concurrency-safe credit billing—and shows how Spec-Driven Development keeps an AI agent coherent across multi-hour, long-horizon tasks. It also covers moving from a three-hour prototype to stable production traffic on general-purpose cloud infrastructure, along with pitfalls and practical lessons for evaluating agentic coding solutions.

    1. AI Coding Is Crossing a Watershed

    Over the past two years, most of our understanding of AI coding has stayed at the level of “autocomplete a line of code” or “explain a function.” But the latest generation of agentic coding models has clearly shifted its center of gravity: the emphasis is no longer on “does the generated page look good,” but on agentic capability, long-horizon tasks, and system engineering.

    This signals a qualitative change. The model is no longer just a “tool that writes code”; it is beginning to show the potential to decompose requirements like an architect and maintain context coherence across hours of automation. To validate this capability, building a pretty demo web page is nowhere near enough—the real stress test is having it build a complete, production-grade system from scratch.

    2. Topic Selection: From “Teaching to Fish” to “Giving the Fish”

    I chose a “batch marketing video generation platform” as the experiment for a very practical product insight.

    In the past, I loved sharing various low-code automation workflows and teaching people how to piece together a product-promotion video step by step. But I gradually realized a counterintuitive fact: the users with genuine business needs—cross-border e-commerce sellers, for example—don’t want to learn a workflow at all. They only care about return on investment. Is the cost of one video a few cents or a few dollars? Can it reliably produce thousands of videos a day? Is there a ready-made platform where you “just click once to generate”?

    The conclusion is clear: in the AI era, “giving the fish” beats “teaching to fish.” Instead of teaching users to assemble a pipeline, it’s better to put the finished capability directly in front of them. And that need happens to require an entire backend system to support it—making it the perfect test of an agent’s “system engineering” ability.

    3. The Real Challenge of a Commercial SaaS Lies in the “System,” Not the “Code”

    Building a demo only takes a few front-end pages, but building a commercial-grade SaaS platform grows in complexity exponentially. At its core, it’s not a “writing code” problem—it’s a “system architecture” problem.

    3.1 Backend Services

    You need a stable set of asynchronous API services: accepting a user’s asset upload request, creating a video generation task, querying task status, and handling callbacks. The interface design should follow stateless principles for easy horizontal scaling. At the same time, you must handle parameter validation, rate limiting, timeout control, and standardized error codes to prevent a single slow request from dragging down the entire service.

    3.2 Database Design and Row-Level Security

    The data model must cover at least three core tables: users, video tasks, and credit ledger. More importantly, in a multi-tenant scenario you need data isolation—you must enable Row-Level Security (RLS) to ensure users can only read and write their own records, preventing unauthorized access. A sketch looks like this:

    1. CREATE TABLE video_tasks (
    2. id BIGSERIAL PRIMARY KEY,
    3. user_id BIGINT NOT NULL REFERENCES users(id),
    4. status VARCHAR(20) NOT NULL DEFAULT 'pending', -- pending/running/succeeded/failed
    5. input_media TEXT, -- reference to the asset in object storage
    6. output_url TEXT, -- storage address of the generated result
    7. cost_credit INT NOT NULL -- credits reserved upfront
    8. );
    9. -- Row-level security: enforce user-level data isolation
    10. ALTER TABLE video_tasks ENABLE ROW LEVEL SECURITY;
    11. CREATE POLICY user_isolation ON video_tasks
    12. USING (user_id = current_setting('app.current_user_id')::bigint);

    3.3 Asynchronous Task Scheduling

    Video generation usually takes several minutes, so it must never block synchronously inside an HTTP request. The right approach is to introduce a “message queue + Worker” asynchronous architecture: the API only accepts the request, deducts credits, writes the task, and enqueues it, then immediately returns the task ID. A background Worker does the actual work—calling the video generation model, polling its internal progress, and persisting the result. The state transitions across the whole pipeline can be abstracted as:

    1. Receive generation request
    2. ├─ Validate token auth (e.g., JWT) and session validity
    3. ├─ Atomically deduct credits (reserve upfront to prevent concurrent overdraft)
    4. ├─ Insert task, status = pending
    5. ├─ Enqueue task_id to the message queue
    6. └─ Return the task ID immediately
    7. ▼
    8. Worker consumes
    9. ├─ Claim the task (pending → running)
    10. ├─ Call the video generation model and poll until completion
    11. ├─ Write result to object storage, backfill output_url
    12. └─ Update status = succeeded / failed (refund credits on failure)
    13. ▼
    14. Frontend: poll task status, or receive a completion notification via callback / long-lived connection

    3.4 Authentication and Credit-Based Billing

    A commercial platform must handle three things: phone-number + verification-code login, token authentication, and credit deduction. Credit deduction is the most error-prone part: under high concurrency, without locking, it’s easy to end up with a “balance driven negative”—overselling. The correct approach is to use a database row lock plus a ledger table to guarantee atomicity and idempotency:

    1. BEGIN;
    2. SELECT credits FROM users WHERE id = :uid FOR UPDATE; -- row lock serializes deductions
    3. IF credits >= :cost THEN
    4. UPDATE users SET credits = credits - :cost WHERE id = :uid;
    5. INSERT INTO credit_ledger(user_id, delta, task_id) -- record ledger for reconciliation and idempotency
    6. VALUES (:uid, -:cost, :task_id);
    7. COMMIT;
    8. ELSE
    9. ROLLBACK; -- insufficient balance, reject the request

    4. Spec-Driven Development (SDD): Constraining the Agent’s Output

    To keep an agent from drifting during long-horizon tasks, the most effective method isn’t repeated questioning—it’s establishing a “contract” first through Spec-Driven Development (SDD). I required it in the prompt to strictly follow the order “research → architecture → development”:

    • Research phase: first clarify user roles, core scenarios, and non-functional requirements (concurrency, task duration, billing model), producing a requirements specification.
    • Architecture phase: before writing any code, first present the system layering, table structures, interface list, and task state machine, and have it self-check whether the architecture forms a closed loop.
    • Development phase: implement module by module against the spec, validating each completed block against the spec rather than improvising.

    The value here is turning “open-ended creation” into “constrained engineering.” The clearer the spec, the stronger the agent’s ability to maintain context coherence over long time spans, and the lower the rework rate.

    5. Why Long-Horizon Tasks Go Off Track—and How to Keep Them Coherent

    Across hours of automation, the most common failure mode is this: as the context grows, early architecture decisions gradually get forgotten, leading to mismatches between table structures and interfaces, or contradictions in the state machine. There are three countermeasures:

    First, capture key decisions in documents rather than relying on memory, so every step can be traced back to the spec. Second, adopt a small-steps, module-by-module approach that closes each loop, locking in results as soon as a verifiable unit is complete. Third, build in a self-check step so the agent actively compares its implementation against the architecture to find gaps. Only by combining these three can “long-horizon” be turned from a risk into an advantage.

    6. Going to Production in the Cloud

    No matter how well the architecture is designed, in the end it has to withstand real traffic. Production environments typically rely on the general-purpose capabilities of a cloud platform: object storage for uploaded assets and generated results, a message queue for asynchronous tasks, a container platform for elastic scaling to match traffic peaks and valleys, and log services plus monitoring and alerting for observability. Baidu AI Cloud, for instance, offers these general-purpose cloud product categories, so developers can compose them as needed and focus their energy on business logic rather than infrastructure operations. This is what lets “build a prototype in three hours” transition smoothly into “run stably 24/7.”

    7. Pitfalls and Lessons Learned

    In practice, the biggest distraction often comes from external factors rather than the technology itself. For example, compute resources may be tight during peak hours and queueing on the platform side may be heavy, stretching out a process that was originally smooth. This is a reminder that when evaluating an agentic coding solution, beyond model capability you also have to consider the stability of the compute supply behind it. The lessons boil down to three sentences: define the spec before writing code; break down long-running tasks with an asynchronous architecture; and treat concurrency safety (billing, unauthorized access) as a first-class concern.

    8. Conclusion

    What this experiment truly demonstrates isn’t that some model can “write a website in three hours,” but that the standard for evaluating AI coding is shifting from “generation quality” to “system delivery capability.” When an agent can understand architecture, decompose requirements, and stay coherent across long-horizon tasks, the developer’s role shifts accordingly—from “the person who writes code” to “the person who defines the spec and the constraints.” Whoever can describe requirements clearly enough will gain the upper hand in this new leap in productivity.