Long-Horizon Agentic Coding in Practice: Building a Video SaaS in Three Hours

    This article presents a practice-based build of a short-video UGC generation SaaS from scratch to show how long-horizon agents can support commercial systems. It explains why spec-driven development (SDD) is a critical constraint, then covers backend and data modeling, task state machines, asynchronous queues and polling, observability, authentication, credits and reconciliation, and common pitfalls. Readers get a practical view of how to keep a multi-hour agent run aligned with architecture, billing correctness, and operational requirements.

    A new generation of coding models has shifted focus from “does the page look good” to agent capability, long-horizon task coherence, and systems engineering. For developers, this means requirements are no longer split into isolated scripts. The model can decompose them the way a senior architect would: service boundaries, data models, asynchronous pipelines, authentication, and billing all remain in the same context for hours. Based on a practice of building a short-video UGC generation SaaS from scratch, this article explains how such capability can land in a commercial system and why spec-driven development (SDD) becomes a key constraint.

    Why This Is No Longer “Just a Demo”

    The complexity gap between a commercial SaaS and a demo page is exponential. A demo needs only one synchronous call and a static result page. A commercial system must solve several problems at once: how backend services are layered, how relational database schemas and row-level security are designed, how video generation jobs are queued and polled when generation takes minutes, how phone-number verification codes and token authentication are implemented, and how credits are deducted and reconciled. This is a system architecture problem, not a single-file coding problem. Such work used to require a small team working in parallel. The value of a long-horizon agent is that it can keep goals, constraints, and completed modules from drifting during an automated task that runs for hours.

    The topic also comes from a real business pain point. In short-video commerce, merchants care more about cost per video, daily throughput, and “upload assets and get a video” than about learning workflow orchestration. Rather than teaching users to fish, the platform should put a click-and-use service in front of them: users upload images or assets, the system asynchronously generates a commerce video and writes back the result. The platform side must be stable, billable, and auditable, which determines that the architecture must be organized around a task state machine and quotas.

    Spec-Driven Development: Keeping Long-Horizon Tasks on Track

    Long-horizon tasks often fail not because a single step is wrong, but because the definition changes midway. SDD requires strict progression from research → architecture → development, and prompts should explicitly forbid skipping steps.

    The research phase produces only the problem space: target users, core use cases (upload, generate, preview, download, failure retry), non-functional metrics (concurrency, timeout, idempotency), and compliance boundaries (asset copyright, content moderation integration points). The architecture phase freezes the component diagram: API gateway and business services, object storage for source and final videos, message queue for generation tasks, relational database for user and task metadata, and logging and monitoring covering queue backlog and failure rate. The development phase only implements frozen interfaces and table schemas; changes must first be written back to the spec.

    This constraint is especially important for agents. Models in long contexts tend to add features “while they are at it.” The spec document becomes the single source of truth, and review against interface contracts and the state machine can catch drift.

    Backend and Data: Encoding the State Machine in the Database

    Business services fit a high-performance web API framework and should be split by domain: account, assets, tasks, and billing. Video generation is a typical long transaction. Synchronous HTTP will time out, so “create task” and “execute generation” must be separated.

    The relational database handles strongly consistent metadata. Core tables should include at least: users, assets, generation tasks, and credit ledger. The task table uses a state field to express the queue lifecycle: created, queued, generating, succeeded, failed, and canceled. Row-level security isolates tenants, and the default policy forbids cross-user reads and writes of tasks and assets. Credit deduction should not only change a balance field; it should write a ledger entry: task ID, deducted amount, before and after balance, and idempotency key. On generation failure, roll back or freeze for manual handling according to policy, avoiding “charged but no video.”

    A schematic task creation flow looks like this:

    1. def create_job(user_id, asset_id, idempotency_key):
    2. assert_quota(user_id)
    3. job = insert_job(status="queued", user_id=user_id, asset_id=asset_id)
    4. enqueue("video.generate", job.id, idempotency_key)
    5. return job.id

    The idempotency key prevents duplicate submissions from causing duplicate charges and duplicate videos.

    Async Queues, Polling, and Observability

    The generation pipeline should work like this: the API only validates and enqueues; a worker pulls the task from the queue, fetches the asset from object storage, calls the generation service, writes the final video back to storage, and updates the task state. The frontend or public API polls by task ID, or uses server-side push to reduce idle polling. The polling endpoint must be lightweight and return only status, progress, and result URL, avoiding a scan of large objects on every request.

    On the operations side, monitor at least: queue depth, worker failure rate, per-task latency percentiles, storage failures, and authentication error rate. When backlog exceeds a threshold, auto-scale workers or degrade new task submissions. Logs should carry a trace_id from the creation request through the worker and external generation call, making it easier to locate where a multi-hour task is stuck.

    Authentication, Credits, and the Commercial Loop

    The account system uses verification-code login plus a short-lived access token and a long-lived refresh token. APIs authorize by role: regular users can access only their own assets and tasks. Credits are the commercial loop: pricing corresponds to generation duration or resolution tier. Pre-deduction or post-completion settlement must be fixed in the spec so the agent does not mix the two modes during implementation. Reconciliation reports summarize successful tasks and ledger entries by day for finance review.

    Content safety and copyright are not expanded in this coding detail, but the architecture should reserve moderation callbacks and asset source fields to avoid schema-breaking patches after launch.

    Practice Rhythm and Common Pitfalls

    The full path from research to a demo-ready commercial prototype takes roughly hours when the spec is clear and the environment is ready. Actual time is amplified by compute queueing, dependency installation, and spec rework. Common pitfalls include: writing business code before freezing the schema, which causes repeated migrations; putting the generation call in the request thread; polling that saturates the database; and credit deduction and task state not sharing the same transaction boundary. The response is still to return to SDD: change the spec first, then the code, and test the task state machine across success, failure, retry, and cancellation paths.

    Conclusion

    When models can maintain system-level context across long tasks, the bottleneck in full-stack delivery shifts from “can it write a piece of code” to “is the spec hard enough and is the state machine complete enough.” Short-video UGC generation SaaS is a good touchstone: it tests asynchronous engineering, data isolation, billing correctness, and observability at the same time. Lock the track with a spec, express real business with queues and ledgers, and the agent can upgrade from writing pages to delivering an operable system. For teams, the next step is not one-shot generation of all code, but including review, testing, and monitoring in the same long-horizon pipeline so every automated run is reproducible, auditable, and rollback-able.