AI Coding in Practice: Building a Video SaaS Platform with Spec-Driven Development
This article walks through building a production-grade video generation SaaS platform with modern AI coding tools. It explains why video generation SaaS is a compelling use case, and why the hard part is system design rather than writing code. You will see how the core challenges break down into backend services, database design with row-level security, asynchronous task scheduling, and authentication and billing. The article then shows how spec-driven development keeps AI agents grounded across long-horizon tasks, with concrete implementation patterns for credit billing (pre-deduction, transactions, rollback, idempotency, and compensation via the transactional outbox pattern), PostgreSQL row-level security, task state machines, and queue deduplication. It closes with testing and monitoring checklists, common pitfalls, and answers to frequently asked questions.
1. AI Coding Is Crossing the Long-Horizon Task Threshold
Over the past two years, most AI-assisted development tools have stopped at “completing a single function” or “generating a static page.” They share the same traits: short interactions, small context, and clearly bounded tasks. Real commercial software is different. It usually spans many rounds of conversation, multiple technical modules, and a continuous build that can last hours or even days.
The new generation of intelligent coding tools has made a clear leap along three dimensions:
- Agentic capability: instead of passively responding to prompts, the tool actively plans steps, calls tools, and self-corrects based on intermediate results.
- Long-horizon tasks: it maintains context coherence over hours of execution and does not drop the architectural constraints set early on.
- System engineering: the focus shifts from “does the UI look good” to “can the system hold up under real traffic, data consistency, and security boundaries.”
To avoid muddying the concepts, it helps to separate them: ordinary code completion solves “writing the next line of code”; agentic tools solve “decomposing a task and executing it continuously”; long-horizon tasks emphasize “holding the goal and constraints over a long period”; and system engineering demands “balancing correctness, security, observability, and maintainability in a real environment.” The real test of whether an AI coding tool has reached the next stage is not how flashy the pages it can generate, but whether it can independently complete most of the engineering implementation of a commercially viable system once a human provides a clear spec.
2. Topic Choice: Why a Video Generation SaaS
This topic is not arbitrary. In recent years, the capabilities of video generation models have improved rapidly. A product image, a voice-over clip, or a script can now be turned into a usable short promotional video, which has significantly lowered the content supply cost for short-video commerce.
Early on, many people were eager to share workflow automation recipes and teach others how to “assemble” videos. But they soon ran into a counterintuitive fact: users with genuine business needs do not want to learn complex workflows. They only care about return on investment: whether a single video costs a few cents or a few dollars, whether they can run thousands a day, whether it needs manual supervision, and whether the failure rate is controllable. The conclusion is clear: rather than teaching users to fish, put the fish directly in front of them. That is the motivation for packaging the capability into a SaaS product built around “upload an image, click generate, get a finished video.”
3. The Real Challenge: Not Writing Code, but System Design
There is a whole set of engineering problems between a toy demo and a commercially usable SaaS. The requirements document groups the core challenges into four categories:
1. Backend services. Use an asynchronous framework to organize the API, such as FastAPI in the Python ecosystem. It needs to handle request validation, dependency injection, unified exception handling, and authentication middleware, while ensuring long-running tasks do not block the main thread.
2. Database design. Use PostgreSQL to model entities such as users, assets, video tasks, and credit transactions. The key is configuring row-level security (RLS) so each user can only read and modify their own data, reducing the risk of unauthorized access at the database layer.
3. Asynchronous task scheduling. Video generation usually takes minutes, so you can never wait synchronously. You need a message queue for asynchronous dispatch, with clients retrieving progress through polling, callbacks, SSE, or WebSocket. On the worker side, you need idempotency, failure retries, dead-letter handling, and timeout compensation.
4. Authentication and billing. Phone-number OTP login, JWT token issuance and refresh, and credit deduction. Deduction should “pre-deduct” before generation, “roll back” when a task fails, and rely on idempotency keys, deduplication tables, compensation tasks, and reconciliation to guarantee financial consistency.
To bring AI coding under controlled scope, you can establish an executable checklist:
- Version baseline: Python 3.11+, FastAPI 0.110+, PostgreSQL 15+, Redis or RabbitMQ as the queue/cache, Alembic for database migrations, Pytest for testing, and OpenTelemetry for logging and distributed tracing.
- Dependency installation: pin versions through pyproject.toml or requirements.txt, separating development dependencies from production dependencies.
- Database migrations: use Alembic to manage table structures, indexes, unique constraints, and RLS policies, avoiding hand-written SQL.
- RLS initialization: set
app.user_idfor each request transaction, and verify that access is denied by default when it is not set. - API contract validation: generate client or server-side validation from an OpenAPI schema, and run contract tests in CI.
- Testing and monitoring acceptance: cover unit tests, integration tests, permission tests, concurrency tests, duplicate queue-consumption tests, and credit-consistency tests, and configure metrics for task success rate, queue backlog, compensation failure rate, and RLS denial count.
This is no longer simply “writing code”; it is “system design.” Not long ago, it was hard for a small team of three to five people to do it alone. Now the process can be handed to an AI coding tool, but it must be constrained with spec-driven development.
4. Methodology: Constraining AI with Spec-Driven Development
The core of spec-driven development is to require the tool to proceed strictly through three stages: research, architecture, and development, rather than jumping straight into code.
- Research stage: first produce the product positioning, user roles, feature list, competitor boundaries, and a technical selection comparison, and make clear what will not be done.
- Architecture stage: output the system architecture diagram, database ER diagram, API contracts, directory structure, state machine, and error codes, and let a human review them before implementation.
- Development stage: implement incrementally by module, running the corresponding tests after each block is done, avoiding a one-time pile of unmaintainable code.
The benefit of spec-driven development is that it decouples “decisions” from “implementation.” Humans gatekeep at the architecture layer, and AI produces code at scale under controlled constraints. This lets you take advantage of AI’s long-task execution while preserving architectural correctness. For long-horizon AI coding, the spec document is not only an input to the AI; it is also the anchor that prevents context drift.
5. Key Implementation Details: Billing, Async Tasks, and Row-Level Security
Take billing, the most error-prone area, as an example. The core is “pre-deduct + transaction + rollback + idempotency + compensation.” It is worth emphasizing that only when pre-deduction, rollback, idempotency, and compensation are all in place can the system pursue ledger consistency; it does not guarantee ledger consistency by default.
One workable approach is to insert an Outbox event inside the transaction and dispatch it to the message queue after commit, avoiding the “database rolled back but the message was already sent” problem:
# Pseudocode: pre-deduct credits, create the task, and write to the Outboxasync def create_video_task(user_id: int, asset_id: int, cost: int, request_id: str):async with db.transaction():await db.execute(text("SET LOCAL app.user_id = :uid"),{"uid": user_id},)# 1. Atomic pre-deduction to avoid over-deduction under concurrencyupdated = await db.execute(text("UPDATE account SET credits = credits - :c ""WHERE user_id = :u AND credits >= :c RETURNING credits"),{"c": cost, "u": user_id},)if not updated:raise InsufficientCredits()# 2. Persist the task, using an idempotency key to avoid duplicate creationtask = await tasks.insert(user_id=user_id,asset_id=asset_id,status="queued",idempotency_key=request_id,)# 3. Write to the Outbox; the relay publishes to the queue after commitawait outbox.insert(event_type="video.generate",payload={"task_id": task.id},dedupe_key=request_id,)return task.id
After the transaction commits, the Outbox Relay is responsible for publishing the event to the message queue. On the consumer side, you need to maintain a processed_event deduplication table with event_id or dedupe_key as a unique constraint, ensuring that when the same event is delivered more than once it does not double-charge, double-create a task, or double-refund credits.
The task state machine should be explicit: queued -> running -> succeeded / failed / canceled. When a worker processes a task, it first claims the task and writes running; if execution fails, it increments retry_count. When the maximum number of retries is reached, say 3, the task moves to failed and, if necessary, to a dead-letter queue. For permanently failed tasks, credits are refunded. The refund itself also needs an idempotency key, such as refund:{task_id}, to avoid duplicate refunds.
Common exception scenarios include:
- Duplicate delivery: the same task event is consumed multiple times, and the consumer deduplication table must intercept it.
- Refund failure: the credit refund endpoint or transaction fails, and it must enter a compensation queue and trigger an alert.
- Timeout unresolved: a task stays in
runningfor too long, and a scanner must mark it as abnormal and trigger manual or automatic compensation. - Manual reconciliation: periodically compare the task table, credit ledger, Outbox, and message queue, and handle long-standing inconsistencies.
At the database layer, RLS backs up the protection against unauthorized access with policies. Note that you cannot set the user variable only at connection initialization; otherwise, connection-pool reuse could cross users. A safer approach is to use SET LOCAL inside each transaction:
BEGIN;SET LOCAL app.user_id = '10001';SELECT * FROM assetsWHERE user_id = current_setting('app.user_id')::int;COMMIT;
Example policy:
ALTER TABLE assets ENABLE ROW LEVEL SECURITY;CREATE POLICY owner_only ON assetsUSING (user_id = current_setting('app.user_id')::int);
In FastAPI, you should inject app.user_id within each request transaction through a database dependency, and ensure the transaction is rolled back or committed when it ends, so that the next request does not reuse the old context. Under a connection pool, never rely on session-level SET to distinguish users.
6. Pitfalls and Engineering Lessons
Common pitfalls in long-horizon builds include:
- Context drift: later in the run, the AI tends to forget early constraints. The fix is to solidify architecture decisions, state machines, error codes, and API contracts into documents that travel with the process, rather than relying only on conversational memory.
- The experience of long generation times: pure polling wastes requests and can cause the frontend to retry frequently. When cost is acceptable, introduce progress events, SSE, or a WebSocket long connection; if connection counts are high and operational cost is high, fall back to polling.
- Missing tests: the more automated the generation, the more you must enforce tests for every module. In particular, add migration tests, permission tests, concurrency tests, and queue tests.
- Insufficient permission testing: verify RLS unauthorized-access cases, for example that user A accessing user B’s assets is rejected or returns nothing.
- Credit concurrency testing: simulate concurrent deductions to verify there is no over-deduction, no duplicate deduction, and no missed refund.
- Duplicate queue-consumption testing: manually redeliver events to verify idempotency on the consumer side.
Recommended acceptance items include: RLS unauthorized-access cases, concurrent credit over-deduction cases, duplicate queue-consumption cases, Outbox delivery-failure retry cases, task timeout-unresolved alert cases, and dead-letter queue alert cases. Monitoring metrics can cover task success rate, queue backlog, refund failure rate, RLS denial count, API P95 latency, and Outbox backlog.
7. FAQ
How do you do spec-driven development?
First write down the product boundaries, roles, feature list, API contracts, database models, state machine, and acceptance criteria, then have the AI implement module by module. Require tests and checkpoints at every step.
What are the common mistakes in long-horizon AI coding?
Common mistakes include losing context, ignoring security constraints, generating an overly large code block in one shot, lacking tests, having no state machine, having no idempotency design, and putting external calls inside a database transaction.
How do you prevent credit over-deduction?
Use an atomic conditional deduction in the database, such as WHERE credits >= cost; use a transaction to keep task creation and deduction consistent; use an idempotency key to prevent duplicate requests; use a consumer deduplication table to prevent duplicate queue consumption; and route failed tasks into a compensation and refund flow.
8. Summary
The real takeaway from this experiment is not “how much labor the AI saved me,” but that it validated the feasibility of AI coding across agentic capability, long-horizon tasks, and system engineering. When a tool can reliably execute the full loop of research, architecture, and development, the developer’s value moves up to requirement definition, architecture gatekeeping, and risk control. AI will not replace architects, but it will use the architect’s spec to build the system for them. For developers, the key to mastering long-horizon AI coding is to command spec-driven development, push constraints to the front, and write exception scenarios into the acceptance checklist.
