Building a Full-Stack SaaS Platform in Hours: An Exploratory Field Report on Driving AI Agents with Spec-Driven Development
This article documents an exploratory, hours-long effort to build a full-stack SaaS platform with an AI coding agent. Rather than promising that an agent can finish any project within a fixed time, it focuses on a more general question: how developers can use agents for complex systems engineering through spec design, architectural constraints, and acceptance mechanisms. It walks through a Spec-Driven Development (SDD) workflow (research → architecture → development), a four-part architecture breakdown (backend services, database modeling with row-level security, asynchronous task scheduling, and auth plus credit-based billing), and a stage-by-stage experiment log with concrete failure-and-fix records. Readers will find practical guidance on multi-tenant isolation, idempotent billing, async task design, and a troubleshooting checklist for common long-horizon failure modes such as dependency drift, contract mismatches, duplicate task consumption, and cost overruns.
1. Experiment Notes: This Is an Exploratory Record, Not a Fixed-Duration Promise
This article documents an exploratory, hours-long effort to build a full-stack SaaS platform. The point is not to prove that an agent can complete all kinds of projects within a fixed time, but to answer a more general question: when a coding agent is capable of long-horizon tasks, how should developers use it for complex systems engineering through spec design, architectural constraints, and acceptance mechanisms?
A special note on framing: the actual time spent depends on spec quality, environment, and acceptance standards, and should not be read as a general promise. The term “production-ready” here should be understood cautiously as “a candidate system that is ready for further hardening, testing, and a go-live evaluation,” not a finished product validated by real operations. For real businesses such as video generation, cross-border e-commerce, and content production, developers still need to complete security audits, compliance reviews, performance load testing, cost estimation, and staged (canary) rollouts.
The value of this article is a reusable engineering method: how to keep an agent from drifting or forgetting during long-horizon tasks, how to give critical modules such as multi-tenancy, asynchronous tasks, and credit-based billing basic runnability, and how to identify risks early.
2. Why “Full-Stack SaaS Platform” as a Stress Test
Many AI coding demos stop at “generate a page” or “write a function.” But the gap between a real platform and a demo is a significant increase in system complexity. A SaaS platform aimed at real users that involves billing and content generation must at least handle the following:
- Backend services: How are endpoints organized? Synchronous or asynchronous? How is correctness guaranteed under concurrency?
- Database design: How are table structures modeled? How is multi-tenant data isolated? How are sensitive fields protected?
- Task scheduling: How are time-consuming operations such as video generation, transcoding, and rendering made asynchronous? How is status polled?
- Auth and billing: How do users log in? How are tokens issued and validated? How are credits or quotas atomically deducted?
- Risk and compliance: How are content copyright, user privacy, content moderation, and cloud resource costs controlled?
This is no longer purely a coding problem, but an architecture problem. In conventional thinking, completing such a system usually takes an architect and several developers working together for weeks. The core proposition of this exploration is: hand the overall planning of system architecture and engineering implementation to a coding agent capable of long-horizon tasks, while the human developer defines the spec, reviews results, and controls risk.
3. Methodology: Spec-Driven Development (SDD)
Blindly telling an agent to “just start writing” is the main reason long-horizon tasks fail. It tends to fall into local optima: each piece of code looks reasonable, but the whole lacks consistency. A more reliable approach is Spec-Driven Development (SDD), which forces the agent to advance through a fixed workflow:
Research -> Architecture -> Development
3.1 Three-Phase Checklist
| Phase | Input | Key Deliverables | Acceptance |
|---|---|---|---|
| Research | Business goals, user roles, core flows, constraints | Requirements list, user stories, risk list | Do requirements cover billing, permissions, async, and exception scenarios? |
| Architecture | Confirmed requirements | Module breakdown, data models, interface contracts, task state machine | Can it support subsequent coding and integration? |
| Development | Frozen architecture | Runnable endpoints, database scripts, test scripts | Do they pass self-tests, contract tests, and critical-path acceptance? |
3.2 Prompt Structure
In prompt design, the key is to make the “role, workflow, constraints, acceptance criteria” explicit. A representative structure is:
Role: You are a senior full-stack architect.Workflow: Strictly follow the order Research -> Architecture -> Development. Produce a document at each phase and have me confirm it before moving to the next step.Constraints:- Multi-tenant data must be isolated; sensitive fields must be encrypted or masked.- All time-consuming tasks must be made asynchronous; no synchronous blocking in the request thread.- Billing/quota deductions must guarantee atomicity and idempotency.- Dependency versions must be locked to avoid environment drift.Acceptance: Each module must provide runnable endpoints, self-check test cases, and a risk description.
The clearer the spec, the less the agent “drifts” during long-horizon tasks. The logic behind this: the upper bound of long-horizon task capability depends largely on the quality of the spec the human provides, not the model’s one-sided “cleverness.”
4. Full-Stack SaaS Architecture Breakdown
The following sections cover four key areas: backend services, database and row-level security, asynchronous task scheduling, and auth plus credit-based billing.
4.1 Backend Services: Light Request Thread, Heavy Work Pushed Down
The backend is typically built on a mainstream async web framework. The core principle: the HTTP request is only responsible for validation, authentication, enqueueing, and returning a task ID; it does not execute time-consuming work directly. Operations such as video generation, rendering, and transcoding should be handled by background worker nodes.
Representative code:
@app.post("/api/v1/videos")async def create_video(payload: VideoRequest, user=Depends(current_user)):task = await task_queue.enqueue(generate_video,user_id=user.id,params=payload,idempotency_key=payload.request_id,)return {"task_id": task.id, "status": "queued"}
There is no single correct choice for the task queue, but it should be evaluated against the following criteria:
| Direction | Suitable Scenario | Key Capabilities |
|---|---|---|
| Lightweight queue + background worker | Small-to-medium scale, fast validation | Simple to implement, but attention to persistence and retries is required |
| Message queue | High concurrency, strong reliability | Retries, dead letters, ordering control, backlog monitoring |
| Cloud-hosted task service | Cloud-native deployment | Elastic scaling, log monitoring, permission integration |
Whatever is chosen, ensure each task has a unique identifier, a state machine, a failure retry strategy, and observable logs.
4.2 Database Modeling and Row-Level Security
The core of multi-tenant SaaS is data isolation. There are three common approaches:
| Approach | Isolation Strength | Cost | Ops Complexity | Suitable Scenario |
|---|---|---|---|---|
| Separate database | High | High | High | Strong isolation, high compliance requirements |
| Separate schema | Medium | Medium | Medium | Many tenants but higher isolation requirements |
| Shared table + tenant ID column | Medium, depends on RLS hardening | Low | Medium | Cost-sensitive, large tenant volume |
For the shared-table approach, the database layer should enable Row-Level Security (RLS) as a last line of defense beyond application-layer access control.
Representative SQL:
ALTER TABLE videos ENABLE ROW LEVEL SECURITY;CREATE POLICY tenant_isolation ON videosUSING (tenant_id = current_setting('app.tenant_id', true)::uuid);
A security boundary must be added here: the app.tenant_id in current_setting('app.tenant_id', true) must be set by a trusted middleware, for example an auth middleware, a gateway, or a trusted service layer in the backend. Application code must not accept an arbitrary tenant ID passed directly from the client. When the tenant context is empty, invalid, or missing, the request should be rejected rather than allowing data access to continue. At the same time, the application account should not hold BYPASSRLS or superuser privileges, otherwise the row-level security policy may be bypassed. Database migration accounts, admin accounts, and ordinary application accounts should be managed separately.
In addition, sensitive fields such as phone numbers, payment information, and keys should be stored encrypted; amount or quota fields are best stored as high-precision fixed-point types to avoid floating-point errors; all critical data operations should retain audit logs, but logs must not contain sensitive information in plaintext.
4.3 Async Task Scheduling and Status Polling
Time-consuming tasks require a reliable asynchronous pipeline:
Enqueue -> buffer in message queue -> worker consumes -> write back result -> frontend polls or receives push
The design should focus on three things:
- Idempotency: Repeated consumption of the same task produces no side effects, for example duplicate generation or duplicate charging.
- Failure retries: Distinguish retryable errors, such as network jitter, from non-retryable errors, such as invalid parameters.
- Status visibility: A task needs a clear state machine, for example queued, running, succeeded, failed, canceled, so the frontend can display progress accordingly.
Video-generation SaaS also needs to pay extra attention to business risk and compliance risk:
- Copyright risk: Generated content may involve licensing issues for images, music, fonts, video assets, model training data, and so on; establish records of asset sources and licenses.
- Privacy risk: If it involves portraits, voices, or user-uploaded files, apply masking, minimize collection, and enforce access control.
- Content moderation: Input prompts, generated results, and published content may all need review to prevent violating content from entering production.
- Cloud resource costs: Object storage, transcoding, inference, bandwidth, and log storage can all incur costs; set budget alerts, quota limits, and abnormal-usage notifications.
Engineering recommendations: use private buckets with least privilege for object storage; use short-lived signed URLs for external access; clean up temporary files promptly; never log sensitive fields such as tokens, phone numbers, or keys; on critical task failure, retain a traceable error code without leaking internal details.
4.4 Auth, Credits, and Billing
The hard part of a billing system is not “deducting,” but “deducting correctly.” Key points include:
- Stateless token auth: Issue tokens with an expiration; validate them uniformly at the gateway or server to reduce service coupling.
- Atomic deduction: Quota deduction must complete within a single transaction, or use a conditional atomic update, to prevent over-deduction under concurrency.
- Reconciliation and idempotency: Generate a unique serial number or idempotency key for each deduction; when a repeated request hits the same serial, return the original result.
- Audit and rollback: Failures, refunds, and compensations must all be traceable.
The following statement alone is not enough:
UPDATE accountsSET credits = credits - :costWHERE user_id = :uid AND credits >= :cost;
“An affected row count of 0” only indicates that this conditional update did not succeed; it cannot, by itself, tell whether the cause is insufficient balance, a concurrency conflict, or some other error. A more robust approach is to handle the idempotency key, transaction boundary, and account deduction within the same transaction.
Representative SQL:
BEGIN;INSERT INTO credit_deductions (idempotency_key,user_id,cost,status,created_at) VALUES (:idempotency_key,:uid,:cost,'pending',now())ON CONFLICT (idempotency_key) DO NOTHING;UPDATE accountsSET credits = credits - :costWHERE user_id = :uid AND credits >= :cost;-- If the UPDATE affected 0 rows, ROLLBACK and report insufficient balance.-- If the INSERT added nothing but a successful serial already exists, return the original result directly to avoid duplicate deduction.COMMIT;
In real engineering, the following rules should also apply:
- The idempotency key is usually generated from a client request ID or a business order number and has a unique index.
- Create the serial record before deduction, ensuring repeated requests do not enter a new deduction flow.
- On deduction failure, roll back the transaction to avoid deducting money without creating a record.
- Scheduled jobs can reconcile: account balance, total serial amount, total recharge amount, and total refund amount should stay consistent.
- Under high concurrency, optimistic locking, distributed locks, or database atomic updates can be considered, but non-atomic “read-then-write” logic must be avoided.
5. Exploratory Experiment Log: Timeline, Key Deliverables, and Fixes
The following are the phase divisions of this exploratory record. This timeline illustrates the process and does not constitute a fixed-duration promise.
5.1 Phase 1: Research and Spec Freeze
This phase took a relatively large share of the early effort. The main goal was to have the agent produce structured requirements rather than write code directly. Key deliverables included:
- User roles: ordinary user, paid user, admin, reviewer.
- Core flows: login, create video task, query progress, download result, deduct charge, refund or compensate.
- Non-functional requirements: multi-tenant isolation, async execution, idempotent billing, audit logs, dependency locking.
- Risk list: content copyright, privacy, cloud costs, unauthorized access, duplicate charging.
Failures and fixes in this phase: 0. The main issue was not technical, but whether the requirement boundaries were clear.
5.2 Phase 2: Architecture Freeze
After requirements were confirmed, the agent was required to produce the architecture first without entering coding. Key deliverables included:
- Module breakdown: user module, task module, file module, billing module, audit module.
- Data models: user table, tenant table, task table, video asset table, credit serial table.
- Interface contracts: REST endpoints, error codes, task status enums.
- Task state machine: queued, running, succeeded, failed, canceled.
- Permission policy: application-layer auth + database RLS + least-privilege accounts.
Failures and fixes in this phase: 1. The failure was that the source of the RLS tenant context was not specified. The fix was to add trusted middleware to the architecture: all requests inject the tenant ID before entering the business layer, and are rejected directly if it is missing or invalid.
5.3 Phase 3: Coding Implementation
Based on the frozen architecture, the agent began implementing module by module. Key deliverables included:
- Backend APIs and basic validation.
- Task enqueue and status query endpoints.
- Database table creation scripts and RLS policies.
- Idempotent credit deduction logic.
- A simple frontend page or command-line self-check script.
Failures and fixes in this phase: 1. The failure was dependency version drift, which caused the code to run locally but error out in the test environment. The fix was to lock dependency versions, generate a lock file, and use a container image with a fixed runtime environment.
5.4 Phase 4: Integration and Acceptance
The final phase mainly verified interface contracts, critical paths, and risk controls. Key deliverables included:
- Login and auth self-tests.
- Create task, query task, and failure-retry self-tests.
- Multi-tenant unauthorized access tests.
- Duplicate deduction and insufficient-balance tests.
- Log masking and object storage permission checks.
- Cloud cost alert configuration recommendations.
Failures and fixes in this phase: 1. The failure was that a frontend timeout retry caused the same request to be deducted twice. The fix was to introduce a unique idempotency key, a serial table, and transactional deduction logic.
Overall, this exploration recorded 3 typical failures and fixes: unclear RLS tenant context source, dependency version drift, and duplicate-deduction risk. These problems illustrate precisely that an agent is not incapable of completing complex engineering, but that humans need to constrain the spec, architecture, and acceptance criteria clearly in advance.
6. Real-World Challenges and a Troubleshooting Checklist for Long-Horizon Tasks
Even when an agent is capable of long-horizon tasks, the actual process will still expose typical problems. Developers are advised to check them off one by one with the following list.
| Problem Type | Common Symptom | Fix |
|---|---|---|
| Dependency drift | Runs locally, errors in the environment | Lock dependency versions, use a lock file, use a fixed container image |
| Interface contract mismatch | Frontend and backend fields do not match | Constrain interfaces with OpenAPI or JSON Schema |
| Duplicate task consumption | The same task executes multiple times | Idempotency key, consumption acknowledgment, unique task ID |
| Lost RLS tenant context | Cannot query data, or unauthorized-access risk | Inject tenant ID via trusted middleware; reject empty values |
| Billing over-deduction or duplicate deduction | Abnormal balance, duplicate serials | Transactions, conditional updates, unique idempotency key, reconciliation |
| Uncontrolled cloud costs | Sudden spike in resource calls | Budget alerts, quota limits, usage monitoring |
| Log leakage | Sensitive fields appear in logs | Masking, field filtering, access control |
During long-horizon tasks, early constraints are the easiest to “forget,” so you should not rely only on conversational memory. Key specs should be solidified into documents, config files, database constraints, interface contracts, and acceptance scripts, so that the agent and humans share the same source of truth.
7. Common Q&A: Practical Notes on Long-Tail Issues
How do you do long-horizon tasks with an AI coding agent?
The core method is Spec-Driven Development. First clarify the business goals, user roles, technical constraints, and acceptance criteria, then have the agent move into architecture design, and only then into coding. Each step should produce a document or code that can be checked, confirmed, and rolled back.
How does multi-tenant SaaS prevent unauthorized access?
Do not rely on application-layer judgment alone. Use application auth, tenant-context injection, database row-level security, least-privilege accounts, and audit logs together. The database account should not hold BYPASSRLS or superuser privileges.
How do you prevent credit over-deduction?
Use atomic updates, transaction boundaries, a unique idempotency key, and a serial table. Do not simply “query the balance, then deduct the balance.” When a conditional update affects 0 rows, further combine transaction state and idempotency records to determine the failure cause.
What risks should a video-generation SaaS watch for?
At minimum, watch for copyright licensing, user privacy, content moderation, cloud resource costs, and object storage security. Set up budget alerts, private buckets, short-lived signed URLs, log masking, and temporary-file cleanup mechanisms.
How do you judge whether an agent’s output is usable for production?
It needs to pass interface contract tests, permission tests, concurrency tests, failure-retry tests, idempotency tests, log-masking checks, dependency audits, and security assessments. An agent can accelerate implementation, but it cannot replace validation in a real environment.
8. Conclusion: The Agent Does Not Replace the Architect, It Restructures the Human-Machine Division of Labor
The biggest takeaway from this exploration is not “how powerful a certain tool is,” but the restructuring of the human-machine division of labor:
- Humans define the problem: business goals, constraints, boundaries, and acceptance criteria must be clear.
- Humans make architecture decisions: isolation approaches, transaction boundaries, permission models, and risk trade-offs still require human judgment.
- The agent handles solution expansion and bulk implementation: under a clear spec, it can take on large amounts of structured, repetitive engineering work.
- Humans handle final acceptance: security, compliance, performance, cost, and user experience cannot simply be handed to the generated result.
A coding agent does not replace the architect; it frees the architect from heavy implementation details so they can focus more on specs, decisions, and risk control. For developers, the core competency is shifting from “knowing how to write code” to “knowing how to define problems, govern architecture, and make trade-offs.”
For teams that want to ship a production-grade system, the pragmatic path is: first tame long-horizon tasks with a clear spec, then constrain generation quality with a solid architecture, and finally use a system of testing, monitoring, and acceptance to let the agent take on scaled implementation. Technology will keep getting stronger, but the ability to define problems clearly remains the hardest moat for an engineer to be replaced.
