AI Coding Enters the Long-Horizon Era: Building a SaaS in 3 Hours

    An experimental build shows that AI coding tools can now handle long-horizon, spec-driven projects, not just isolated functions. Using the goal of building a production-grade SaaS that turns product images into ready-to-run marketing short videos, this article breaks down a three-stage workflow of research, architecture, and implementation. It covers multi-tenant data isolation, asynchronous task orchestration with state machines, idempotent billing through a freeze-settle-release model, authentication and abuse prevention, context management, and observability. It also documents real pitfalls, the limits of what AI can deliver, and a practical checklist for teams running their first long-horizon experiment.

    1. Bottom Line Up Front: AI Coding Is Crossing the Long-Horizon Threshold

    Over the past two years, the question “can AI write code?” has a clear answer. But “can it take a complete, runnable, extensible, and commercially viable system from zero to done?” has long remained in a gray zone.

    The bottleneck isn’t single-point coding ability. It’s task span. Generating a function, a page component, or a data-processing script has a low verification cost. When something breaks, you fix a few lines. Building a SaaS platform is a different beast: it’s a set of tightly coupled engineering decisions. How do you model the data? How do you orchestrate tasks asynchronously? How do authentication and billing close the loop? How do you handle failures gracefully, and how do you observe the system in production? A mistake in any one of these areas gets amplified during integration.

    In an experimental build, I asked an AI coding tool to run a complete product-development exercise: build a SaaS for short-video creative generation aimed at e-commerce sellers, starting from zero. Done smoothly, the whole process took roughly three hours. More important than the time was the execution method. I didn’t ask it to “just write code.” Instead, I required it to follow a spec-driven workflow of “research → architecture → development”: understand the business first, then freeze the architecture, and finally implement and self-test step by step. The result showed that what constrains output quality isn’t the speed of code generation, but whether intent is fully conveyed and whether constraints are strictly honored.

    Using this experiment as a thread, this article breaks down the methodology and engineering essentials of long-horizon agentic coding, including prompt templates, data isolation, task orchestration, idempotent billing, context governance, and pitfalls to watch for.

    2. The Three Layers of Long-Horizon Agentic Coding

    To understand what makes this shift significant, it helps to first distinguish “long-horizon agentic coding” from ordinary code generation. It involves at least three layers of capability.

    2.1 The Goal Layer: From “Implementing a Function” to “Operating a System”

    Ordinary code generation deals with a clearly bounded function: inputs and outputs are well-defined, and there’s a single way to verify it. A long-horizon task deals with a product that has only a goal and no path: the user uploads an image, and the system automatically generates a short video ready for direct marketing use.

    This requires the model to decompose requirements at a system level, translating a vague product vision into data models, task pipelines, interface contracts, permission boundaries, and billing rules. The quality of this decomposition sets the ceiling for everything that follows. This is precisely why spec-driven development puts “research and architecture” ahead of coding.

    2.2 The Time Layer: From “Single Response” to “Consistency Across Hours”

    The real challenge of long tasks is time. Building a SaaS typically involves dozens of interdependent subtasks: build the tables first, then the APIs; set up the task queue before you can poll for progress; build the quota system before you can implement deductions.

    Each individual task takes minutes to tens of minutes, and the cumulative span can reach several hours. Throughout this process, the model must maintain goal consistency. It can’t introduce a design midway that conflicts with the new architecture, and it can’t forget the original constraints after pushing forward for a long time. This isn’t a matter of “longer memory.” It’s a state-management problem: whoever can persist global state outside the task itself has genuine long-horizon capability.

    2.3 The Engineering Layer: From “It Runs” to “It’s Deliverable”

    A demo prototype aims to “run.” A commercial system aims to be “deliverable.” The former focuses on the happy path; the latter must answer:

    • Is multi-tenant data strictly isolated?
    • Can long-running tasks retry on failure?
    • Will duplicate submissions cause duplicate charges?
    • Will downstream API instability overwhelm upstream services?
    • When something breaks in production, can you trace it to a specific request?

    Engineering capability determines whether AI produces a toy or an asset.

    3. Why the Choice of Project Determines the Difficulty: The Gap Between SaaS and Demo

    When many people test AI coding ability, they have it write a to-do list or a landing page. This actually validates very little. These tasks have fixed architectures and simple state, with almost no engineering difficulty.

    A SaaS platform built for a real business, by contrast, must answer four categories of questions.

    3.1 The Data Layer: Multi-Tenant Isolation and Data Integrity

    The platform serves multiple merchants, so the data model must carry a tenant dimension from the very start: entities like merchants, users, quota accounts, creative-generation jobs, and finished-video records all need clear ownership. The key point is that isolation isn’t a convention written into documentation. It’s a constraint enforced at the database layer.

    In a relational database that supports row-level security policies, you can define access policies per tenant:

    1. -- Row-level security policy example: each request session binds the current tenant ID
    2. -- The table must include a tenant_id column, enforced on write
    3. CREATE TABLE video_jobs (
    4. id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    5. tenant_id bigint NOT NULL,
    6. created_by bigint NOT NULL,
    7. status text NOT NULL DEFAULT 'pending',
    8. input_key text NOT NULL, -- key of the raw material in object storage
    9. output_key text,
    10. request_hash text NOT NULL, -- used for idempotent deduplication
    11. cost_tokens bigint NOT NULL DEFAULT 0, -- records actual consumption
    12. attempt int NOT NULL DEFAULT 0,
    13. created_at timestamp with time zone NOT NULL DEFAULT now(),
    14. updated_at timestamp with time zone NOT NULL DEFAULT now(),
    15. CONSTRAINT uq_jobs_tenant_request UNIQUE (tenant_id, request_hash)
    16. );
    17. ALTER TABLE video_jobs ENABLE ROW LEVEL SECURITY;
    18. CREATE POLICY tenant_isolation ON video_jobs
    19. USING (tenant_id = current_setting('app.current_tenant')::bigint)
    20. WITH CHECK (tenant_id = current_setting('app.current_tenant')::bigint);

    3.2 The Task Layer: Asynchronous Orchestration and State Management

    Video generation takes minutes, so a purely request-response design will inevitably time out. The platform must adopt a “submit task → execute asynchronously → return result or poll actively” model, supported by a task state machine, retry strategy, timeout handling, and a dead-letter queue.

    Long-running tasks with many external dependencies are naturally suited to an “at-most-once delivery, at-least-once processing” design, with idempotency and a state machine layered on top to guarantee eventual consistency.

    3.3 The Permission Layer: Authentication and a Closed Billing Loop

    For a commercial SaaS, authentication is more than “let users in once they log in.” It involves at least phone or email verification-code login, short-lived access tokens with a refresh-token mechanism, role-based access control, deduction and rollback of user credits or quota accounts, and strategies to prevent duplicate submissions and abuse.

    Billing is the most easily overlooked module in long-task scenarios. If you charge at job creation, what happens when the user cancels or generation fails? If you charge only after the job completes, how do you guarantee task quality when the balance is insufficient? These questions must be solved with a funds-flow model of “freeze → settle → release.”

    3.4 The Operations Layer: Observability and Cost Governance

    A SaaS in production must be able to answer: “How many jobs are backlogged?” “What’s the failure rate?” “What’s the average processing time?” “What does a single video cost?” Without structured logging, metrics collection, and distributed tracing, troubleshooting relies entirely on manually combing through logs.

    A mistake in any of these four layers prevents the system from reaching commercial readiness. This very complexity is what makes it a litmus test for AI coding ability.

    4. Business Context: From “Teaching People to Fish” to “Giving Them the Fish”

    I chose “e-commerce short-video creative generation” as the experiment’s subject based on observations of shifting user needs.

    Over the past two years, the content ecosystem around workflow-orchestration tools has thrived, with countless tutorials teaching people how to chain model nodes to batch-generate videos. But the real audience for these tutorials is mainly tech enthusiasts and productivity hobbyists, not the merchants who actually pay. The needs of cross-border e-commerce sellers and small-to-medium merchants are highly consistent and can be distilled into three questions:

    • Unit cost: What’s the all-in cost of a single creative?
    • Throughput ceiling: How many deployable creatives can be produced steadily per day?
    • Barrier to entry: Can I get a finished video with a few clicks, without learning any tool?

    For merchants, no matter how flexible a visual workflow is, it can’t beat a website where you input an image, click generate, and get a finished video. This isn’t a difference in capability but a difference in product form: the former requires the user to become a “producer,” while the latter hands the producer role to the platform.

    So the product strategy in the AI era must shift from “teaching users how to do it” to “doing it for them.” This judgment directly shaped the experiment’s product form:

    • A creative-generation platform aimed at merchants;
    • Image as input, a deployable short video as output;
    • Built-in quota billing, batch jobs, and visible progress;
    • The latest video-generation capabilities wrapped underneath, so merchants only face “upload and download.”

    5. Methodology: Long-Horizon Tasks Under Spec-Driven Development

    In long-horizon tasks, the biggest risk isn’t insufficient model capability. It’s intent getting distorted as it’s passed along. To address this, I used spec-driven development, whose core principle is “define the spec first, then write code.”

    5.1 Staged Prompts

    I split the task into three phases and required the model to advance strictly in order, producing a reviewable document at each stage and moving on only after my confirmation.

    1. [Task Context]
    2. Build, from zero, a short-video creative-generation SaaS platform for e-commerce sellers.
    3. The goal is not a demo page, but a minimal viable system that is deployable, commercially usable, and operable.
    4. [Phase 1: Research and Spec]
    5. 1. Clarify the target users and core use cases; produce a requirements list ranked P0/P1/P2;
    6. 2. List technical constraints: tech stack, database, task queue, object storage, authentication method;
    7. 3. Identify compliance requirements: material copyright, content-safety review, generated-content labeling, privacy protection;
    8. 4. Produce a "Requirements Specification" and, after my confirmation, proceed to the next phase.
    9. [Phase 2: Architecture Design]
    10. 1. Output a system architecture diagram and module boundaries;
    11. 2. Output a database ER diagram and DDL scripts, explaining the multi-tenant isolation approach;
    12. 3. Define the task state machine, retry, and compensation strategy;
    13. 4. Design an API list (path, method, request, response, error codes);
    14. 5. Produce an "Architecture Design Document" and, after my confirmation, proceed to the next phase.
    15. [Phase 3: Phased Implementation]
    16. 1. Implement in this order: "infrastructure → data layer → auth → task scheduling → business APIs → frontend → observability";
    17. 2. Immediately run self-tests after implementing each module, and output the self-test results;
    18. 3. When the spec conflicts, pause and ask. Do not make assumptions on your own;
    19. 4. Deliver only one complete, verifiable module at a time, with a list of changed files.
    20. [General Constraints]
    21. - Hardcoding secrets in code is forbidden; read everything uniformly from environment variables or a config center;
    22. - All external-facing APIs must implement idempotency and parameter validation;
    23. - All asynchronous tasks must have timeouts, retries, and failure fallbacks;
    24. - Do not introduce third-party dependencies that have not been confirmed.

    The key to this prompt is putting constraints up front. Most failures happen not because the model can’t write code, but because you never made clear “it must be idempotent,” “it must be multi-tenant isolated,” “it must be rollback-capable.” Only by writing these requirements into the spec does the model have a basis for enforcing them in every implementation detail.

    5.2 Why It Must Be Split Into Three Phases

    Many practitioners like to give the complete requirements in one shot, expecting the model to produce the whole system directly. This works in the prototype stage but almost certainly fails in the commercial stage.

    The reason is that architectural decisions are irreversible. If the data table lacks a tenant column, backfilling it later is extremely painful. If the task model is designed for synchronous calls, switching to asynchronous means rewriting the entire chain. If the permission model is checked only in the application layer, introducing multi-role management later requires large-scale refactoring. Putting research and architecture up front essentially concentrates the “irreversible decisions” into one stage that can be reviewed and corrected.

    5.3 Context Governance for Long-Horizon Tasks

    For a task spanning three hours, the biggest enemy is context bloat. As files multiply and the conversation grows longer, the model naturally drifts from earlier constraints, producing duplicate implementations, style drift, and references to modules that don’t exist. Effective strategies include:

    • Persisted state: Write the spec, architecture, API list, and task progress as documents in the repository, so the model reads from files each round instead of relying on conversational memory;
    • Small, incremental commits: Organize the changes each time you finish a module, making rollback and review easier;
    • Explicit verification: After each stage, require the model to check itself against a checklist, for example, “did every external API do parameter validation?” “are there any hardcoded secrets?”;
    • Human checkpoints: Step in at three points—spec review, architecture review, and acceptance of critical APIs—and leave the rest for the model to advance autonomously.

    6. Core Engineering Points, Broken Down

    6.1 Multi-Tenant Isolation: Three Layers, None Optional

    Multi-tenant isolation is the bottom line for a SaaS. A production-grade approach typically has three layers:

    1. Connection layer: Each request session binds the tenant context;
    2. Data layer: Database row-level security policies enforce filtering, guarding against application-layer omissions;
    3. Application layer: All query APIs uniformly inject the tenant condition; raw queries are forbidden.

    Relying only on the application layer means pinning your security on “never making a mistake every single time.” Having only database policies without tenant context passed at the connection layer means having no policy at all. Stacking all three covers the three risks of “writing it wrong,” “forgetting to write it,” and “privilege escalation.”

    6.2 Asynchronous Tasks: The State Machine Is the Cornerstone of Reliability

    Video-generation jobs involve multiple external services and uncertain durations, so they must be modeled explicitly. A recommended state machine:

    1. pending → running → succeeded
    2. ↘ failed → (retry) → pending
    3. pending → canceled
    4. running → (timeout) → failed

    Supporting reliability designs include:

    • Idempotent submission: Use “tenant + request fingerprint” as the unique key, so duplicate requests return the existing job;
    • Conditional updates: When claiming a job, use an update statement with a state condition to prevent multiple executors from processing the same job;
    • Exponential backoff: Failed retries use increasing intervals, with a maximum retry count per job;
    • Dead-letter fallback: Jobs exceeding the retry limit go to a dead-letter queue that triggers an alert rather than being silently dropped;
    • Timeout control: Set an independent timeout for each stage to avoid a job occupying an executor indefinitely.

    Conditional updates can be expressed with general SQL:

    1. -- Only claimable when the job is still pending, naturally preventing duplicate consumption
    2. UPDATE video_jobs
    3. SET status = 'running', attempt = attempt + 1, updated_at = now()
    4. WHERE id = :job_id
    5. AND status = 'pending'
    6. RETURNING id;
    7. -- zero affected rows means another executor already claimed the job; skip directly

    6.3 The Billing Loop: Freeze, Settle, and Release

    The right way to bill for long tasks is “pre-freeze, then settle”:

    1. When the job is created, freeze quota based on estimated cost;
    2. When the job succeeds, settle against actual consumption and release the difference;
    3. When the job fails, release the entire frozen quota;
    4. When the balance is insufficient, reject job creation outright, avoiding the “run first, charge later” overdraft.

    This process must sit within the same transaction boundary as job creation. Otherwise you get inconsistencies like “the job was created but not charged” or “charged but the job was lost.” At the same time, the freeze and release operations themselves must be idempotent to prevent network retries from causing duplicate deductions.

    1. # Billing pseudocode: freeze and settle must be idempotent and in the same transaction as the job status change
    2. def on_job_created(tx, tenant_id, job_id, estimated_cost):
    3. tx.execute("INSERT INTO quota_ledger "
    4. "(tenant_id, job_id, type, amount) "
    5. "VALUES (:t, :j, 'freeze', :c) "
    6. "ON CONFLICT (tenant_id, job_id, type) DO NOTHING", t=tenant_id, j=job_id, c=estimated_cost)
    7. tx.execute("UPDATE quota_account SET frozen = frozen + :c WHERE tenant_id = :t", c=estimated_cost, t=tenant_id)
    8. def on_job_finished(tx, tenant_id, job_id, actual_cost, estimated_cost):
    9. tx.execute("UPDATE quota_ledger SET type='settle', amount=:a "
    10. "WHERE tenant_id=:t AND job_id=:j AND type='freeze'",
    11. a=actual_cost, t=tenant_id, j=job_id)
    12. tx.execute("UPDATE quota_account "
    13. "SET frozen = frozen - :e, used = used + :a "
    14. "WHERE tenant_id = :t",
    15. e=estimated_cost, a=actual_cost, t=tenant_id)

    6.4 Authentication and Rate Limiting: Keep Abuse Out

    Beyond login and token refresh, a commercial platform also needs three types of abuse protection:

    • Rate limiting: Limit both by user and by IP to prevent scripts from mass-submitting jobs;
    • Quota limiting: Set daily job caps for free users and tier them by plan for paid users;
    • Content safety: Both uploaded materials and generated results must go through review to keep violating content out of the distribution chain.

    These capabilities are typically provided as general-purpose cloud services, such as identity services, API-gateway rate limiting, and content-moderation services. Developers can compose them as needed rather than building everything from scratch.

    7. Field Notes: Pitfalls From the Experiment

    Even with the right approach, a long-horizon experiment runs into several typical problems worth anticipating.

    Pitfall 1: A mismatch between perceived speed and the real bottleneck. During the experiment, I saw obvious response slowdowns, but the cause was usually a surge in concurrent requests queuing on the server side, not a drop in the model’s capability. Long tasks are extremely sensitive to stability. It helps to avoid peak hours and to split large tasks into small stages that can resume from breakpoints.

    Pitfall 2: Spec drift. In the later implementation phase, the model tends to “optimize” designs that were fixed early on, for example, changing status enums or altering API response structures on its own. The countermeasure is to mark “frozen items” in the spec document and require any change to first explain its reason and obtain confirmation.

    Pitfall 3: Fake completion from missing verification. The model declares “done and self-tested,” but in reality only the happy path was verified. The countermeasure is to require self-test evidence, such as a test-case list, actual output snippets, and verification results for failure scenarios. A completion claim without evidence should be treated as incomplete.

    Pitfall 4: Secrets and insecure defaults. Generated code easily contains hardcoded placeholder secrets or authentication middleware that’s disabled by default. Long-horizon tasks need a security sweep in the closing stage, checking for: hardcoded credentials, unauthenticated public endpoints, and sensitive fields printed in logs.

    Pitfall 5: Uncontrollable external dependencies. Downstream capabilities like video generation fluctuate and have quota limits. Without fallback and queuing strategies, upstream jobs will fail en masse. It helps to implement “local queue + failure fallback + result caching,” isolating external uncertainty at the task layer.

    Pitfall 6: The difficulty of reviewing a one-shot output. Three hours generates a huge amount of code, making line-by-line review unrealistic. A workable compromise is to review key files module by module in stages, focusing on three areas—the data model, the task state machine, and authentication logic—and letting automated tests and static analysis cover the rest.

    8. Capability Boundaries: What AI Can and Cannot Do

    Objectively, long-horizon agentic coding still has clear boundaries, in at least four areas:

    1. Business judgment: Who the target users are, how to prioritize features, how to weigh cost against benefit—these are product decisions. The model can only advise; it can’t choose for you.
    2. Compliance responsibility: Requirements for content copyright, privacy policy, and generated-content labeling vary by region and industry and must be confirmed by a human.
    3. Quality assurance: What the model produces is a high-quality starting point, not a ready-to-launch endpoint. Load testing, security audits, and capacity evaluation still require human effort.
    4. Long-term evolution: Trade-offs in refactoring as requirements change, technical-debt management, and team-collaboration conventions still depend on human engineering judgment.

    Acknowledging boundaries doesn’t mean undervaluing what AI offers. It means a shift in role: the developer moves from “the person who writes code” to “the person who defines the spec, reviews the work, and takes responsibility.”

    9. Implications for Teams and Enterprises

    This experiment yields four transferable lessons for engineering teams.

    First, treat the spec as the primary deliverable. Teams should build up requirements-spec templates, architecture-review checklists, and API-contract standards. The clearer the spec, the more usable the AI output and the less human rework.

    Second, redesign the review and verification process. When code is produced several times faster, the bottleneck moves from “writing” to “reviewing.” You need automated tests, static analysis, dependency scanning, and a CI pipeline to keep quality from spinning out of control along with output speed.

    Third, redefine role capabilities. The weight of “upstream skills”—architecture design, domain modeling, observability design, cost governance—goes up, while the share of purely repetitive coding goes down. The focus of development should shift from “how fast you write” to “how clearly you think and how strictly you verify.”

    Fourth, plan compute and tooling resources sensibly. Long-horizon tasks demand resource stability. It helps to reserve capacity by task size, run during off-peak hours, and support resume-from-breakpoint. General-purpose cloud platforms offer complete product portfolios covering model services, container platforms, object storage, message queues, logging, and monitoring alerts; for example, Baidu AI Cloud provides such capabilities that enterprises can compose as needed to quickly build this kind of “AI-generates, AI-executes” engineering pipeline.

    10. Action Checklist: How to Start Your First Long-Horizon Experiment

    If you also want to validate similar capabilities, here’s a recommended order:

    1. Pick a problem with real complexity: It should include at least three kinds of difficulty—data isolation, asynchronous tasks, and authentication/billing—and avoid purely frontend pages;
    2. Write the spec before coding: Produce the requirements list, architecture document, and API contract first; get them reviewed, then start coding;
    3. Set checkpoints per stage: Each stage must produce verifiable evidence at its end; don’t advance to the next stage until it passes;
    4. Put the security baseline up front: Bake secret management, authentication, rate limiting, and content moderation into the spec from Phase 1;
    5. Build observability alongside: Design logging, metrics, and distributed tracing together with the task model, not after the fact;
    6. Do three things at the close: A security sweep, load testing, and a cost review, to form reusable experience.

    Conclusion

    The takeaway from this experiment is that AI coding is indeed crossing the “long-horizon task” threshold. The sign of crossing it isn’t that more code was generated, but that a complex system can be built while maintaining goal consistency, keeping constraints from drifting, and producing verifiable output over a long span.

    For developers, this means a role upgrade: you’re responsible for defining the problem, designing the architecture, and setting acceptance criteria, while implementation can be handed off to agents at scale. Being able to write code with AI is no longer a scarce skill. Being able to break requirements into specs the model can execute—and taking responsibility for the final result—is the new core competency.

    Start with a small but complete project and run the “research—architecture—development—verification” loop through once. You’ll find the real threshold was never model capability, but whether you’ve already thought the problem through clearly.