Agentic Coding in Practice: Building a Long-Horizon SaaS System From Scratch

    This article looks at a threshold shift in AI-assisted programming: from generating a single function to decomposing, orchestrating, and continuously delivering a production-ready product. Using an agentic coding tool, the author builds a short-video generation SaaS platform from zero — users upload product images and receive finished marketing videos rather than another tool to learn. The article walks through spec-driven development (SDD) as a three-phase constraint (research, architecture, iterative development), four core design decisions (multi-tenant data model with row-level security, async task queue with an explicit state machine, authentication and credit-billing consistency, and object storage plus observability), and a debugging table for the failure modes that show up in long-horizon work. It also includes a short FAQ on context drift, row-level security, and polling versus callbacks.

    1. A signal: AI coding is crossing the “system-level” threshold

    Ordinary code generation answers “how do I write this one function?” Systems engineering answers “how does a commercially usable product get decomposed, orchestrated, and delivered over time?” The first is a point; the second is a surface. To test where that capability boundary now sits, I used an agentic coding tool to build a short-video generation SaaS platform from scratch: users upload product images, and the system produces ready-to-post marketing videos on its own — delivering a result rather than another tool.

    One clarification up front: what follows is a method, an architecture, and a set of acceptance criteria — not a performance guarantee. Timings, concurrency limits, and costs vary with team experience, model versions, and infrastructure choices. Re-run your own load tests in your own environment instead of copying any number from this article.

    2. Why a video-generation SaaS

    In the AI era, “teaching a person to fish” is losing marginal value. Shipping the result straight to the user is worth more. Data-driven business teams usually have no interest in learning complex workflow orchestration — they care about return on investment: does a single video cost cents or dollars? Can I reliably produce enough of them in a day? Is there a platform where I click once and get the output?

    That is precisely the SaaS value proposition: package low-level capability as a turnkey service, keep the complexity inside the system, and leave simplicity on the outside.

    3. The core challenge: this is architecture, not coding

    Once the goal becomes “commercially viable,” the problem set multiplies:

    • Backend services: How do you build a high-concurrency web service with a clear structure and sensible module boundaries?
    • Data model: How do the tables support the many-to-many relationships between users, assets, tasks, and videos?
    • Data isolation: In a multi-tenant system, how do you guarantee that user A can never read user B’s data?
    • Async scheduling: Video generation takes minutes — how do you keep it from blocking request threads?
    • Auth and billing: How do you wire up phone-OTP login, token authentication, and real-time credit deduction with rollback?

    This is no longer “write one endpoint.” It is a complete distributed-systems architecture problem. Depending on team experience and scope, it typically takes several people a few weeks — it does not materialize in one pass from one person.

    4. The method: constraining AI with SDD

    Keeping an agent on track across a long-horizon task is a process problem, not a prompting problem. I used Spec-Driven Development (SDD): the AI is forced through three phases — research → architecture → development — and each phase must produce a reviewable spec document before the next begins. The value is that an open-ended task becomes a sequence of well-bounded sub-tasks, which substantially reduces context drift and logical breaks in long conversations.

    Inputs, outputs, and acceptance criteria for the three phases:

    Phase Input Output Acceptance criteria
    Research and requirements clarification Product goal, user roles Requirements spec (feature list, core flows, list of open questions) Every feature has exactly one owner and a priority; ambiguities are closed
    Architecture design Requirements spec Technical architecture (module split, data model, API contracts, deployment topology) Contracts include field types, error codes, and auth requirements
    Iterative development API contracts, architecture docs Code implemented in batches, plus integration results Each batch ships with acceptance cases; regressions pass before integration

    5. Architecture breakdown: four key designs

    1. Data model and row-level security (RLS)

    The core is four main tables: users, assets (uploaded images), tasks (generation jobs), and outputs (videos). Every table carries an owner_id column, and multi-tenant isolation is enforced in the database rather than left to application-layer filtering:

    1. -- 1) Enable RLS on the table and force it for the table owner too
    2. ALTER TABLE tasks ENABLE ROW LEVEL SECURITY;
    3. ALTER TABLE tasks FORCE ROW LEVEL SECURITY;
    4. -- 2) Policy: users only see their own rows; an empty context is rejected outright
    5. CREATE POLICY user_isolation ON tasks
    6. USING (owner_id = current_setting('app.user_id', true)::uuid);

    Key points: app.user_id must be set server-side from a validated token and never passed in by the client; if the value is empty or malformed, the query should be rejected rather than allowed through. Database roles should follow least privilege and receive only the read/write permissions they actually need. Asset access in object storage needs matching isolation — enforce it via signed URLs or path-prefix validation so that unauthorized access is also blocked at the storage layer.

    2. Async task queue and state machine

    Video generation is a classic long-running job. The request returns a task ID immediately and pushes work onto a message queue (self-hosted or a cloud provider’s messaging service), where background workers consume it. The task needs a well-defined state machine plus supporting mechanics:

    1. POST /tasks -> create task, carry an idempotency key, enqueue, return task_id
    2. GET /tasks/{id} -> status: pending / running / done / failed
    • Idempotency key: the client submits a unique key on submission to prevent duplicate enqueues.
    • Retries: failures retry with exponential backoff up to a maximum attempt count.
    • Timeouts and dead letters: tasks that exceed the threshold or exhaust retries move to a dead-letter queue for investigation.
    • Polling strategy: the frontend polls at a fixed interval; add jitter and backoff to avoid a polling storm.

    This design decouples “the user is waiting” from “the system is computing,” and it is the foundation for concurrency. Whether it holds up under peak load depends on queue capacity, worker concurrency limits, and object-storage quotas — verify with load tests rather than assumption.

    3. Consistency between auth and billing

    Login exchanges a phone OTP for a token, and subsequent requests identify the user through that token. Billing is the hard part: reserve first, settle later, roll back on failure, with database transactions holding it together.

    • Pre-deduct credits inside the transaction at task creation, using row locks or optimistic locking (version number) to prevent over-deduction under concurrency.
    • Confirm the deduction when generation succeeds; return it automatically on failure.
    • Use the idempotency key and a unique request ID to prevent double charges.
    • Run periodic reconciliation that compares reserved, settled, and refunded amounts to catch accounting gaps early.

    4. Object storage, asset access control, and observability

    Outputs are written to object storage; assets and videos are served through short-lived signed URLs that expire, avoiding the leak risk of a public bucket. Alongside that, instrument the task pipeline: enqueue time, start and end time, retry count, failure reason — then aggregate success rate and P95 latency. Observability is the health check for long-horizon tasks; without it you cannot tell whether the queue is backing up or the model is timing out.

    6. Common pitfalls and a debugging table

    Long-horizon work rarely goes smoothly. Problems cluster into a few categories:

    Symptom Likely cause Fix
    API fields drift Contracts not aligned across batches Treat the contract document as authoritative; align before integration
    Duplicate task submission No idempotency key Add a unique request ID and deduplicate on enqueue
    RLS returns empty results app.user_id not set Check token parsing and context injection
    Polling storm overwhelms the service Frontend polls too frequently Add interval, jitter, and backoff, or switch to callbacks
    Tasks pile up at peak Worker concurrency too low Set concurrency limits and rate limiting; scale out the queue

    Context accumulation deserves separate attention: late in a long conversation the AI tends to forget API contracts agreed earlier, so the spec documents have to keep pulling the thread back.

    7. Conclusion and FAQ

    Once an agent has genuine long-horizon and systems-engineering capability, the role of AI coding shifts from “assistive tool” to “primary producer,” and the developer’s center of gravity shifts from writing code line by line to defining specs, constraining process, and reviewing results. Humans still own architecture decisions, security boundaries, and acceptance criteria.

    FAQ

    • How does agentic coding reduce context drift? Constrain the work with three-phase SDD spec documents, deliver in batches, and attach acceptance criteria to each batch.
    • How do you configure row-level security for a multi-tenant SaaS? Enable and FORCE RLS, base policies on a session variable injected by the server, reject empty values, and apply least-privilege roles.
    • How should long-running tasks be polled or called back? Prefer callbacks plus a state machine, supplemented by low-frequency polling with backoff; pair them with idempotency keys, retries, timeouts, and a dead-letter queue.

    The real efficiency gain comes from a collaboration pattern in which humans define the right problem and AI solves it efficiently — which may be what the next phase of AI coding actually means.