AI Coding Enters the Long-Task Era: Building a Video Generation SaaS in 3 Hours
This article examines whether AI coding tools can handle multi-hour, system-level tasks rather than just fast, single-file completion. Using a from-scratch SaaS that turns image assets into auto-generated marketing short videos as the test case, it walks through the core engineering decisions behind the build: an append-only credit ledger with balance as cache, an idempotent asynchronous job pipeline, pre-charge/settle billing, and defense-in-depth multi-tenant isolation. It explains how spec-driven development keeps a model on track during long tasks, shares a practical list of failure modes encountered along the way, and draws an honest boundary: a few hours yields a runnable skeleton, not a production-ready product—leaving security review, load testing, compliance, and observability to humans.
1. Why Pick a “Seemingly Impossible” Problem
Over the past year, the capability narrative around AI coding tools has centered on two things: completion speed and the generation quality of a single file. These capabilities solve “writing fast,” not “writing correctly.” What actually determines whether a system can go to production is the contracts between modules, the handling of failure paths, and data consistency.
So the boundary this hands-on test set out to verify wasn’t “can it generate a good-looking page,” but three harder questions:
- Can it keep architectural decisions consistent across hours of uninterrupted work?
- Can it proactively ask questions when requirements are ambiguous, instead of inventing parameters to paper over the gaps?
- Can it localize its own errors after a failure, rather than piling on new code to bury the problem?
For these three points to mean anything, the problem had to be genuinely “systematic.” The final choice was to build a SaaS platform from scratch that turns image assets into auto-generated marketing short videos. It naturally covers six categories of engineering problems—frontend, backend, database, async tasks, authentication, and billing—and if any one of them is cut short, the system can only stay at demo status.
2. Requirements Background: Turning a “Tool” into a “Result”
The problem wasn’t chosen just because it’s hard, but because it reflects a real demand mismatch.
For a while, much of the technical discussion has concentrated on “workflow orchestration”: how to string multiple nodes together, how to tune parameters, how to shape the shots you want. But the real target users—cross-border sellers and small and medium merchants—have highly convergent needs that boil down to three things:
- Is the all-in cost of a single video a few cents or a few dollars?
- Can it reliably produce thousands per day?
- Does it require training to get started?
In other words, they don’t need a production tool with a learning curve; they need a result-oriented service where “one click produces a video.” This judgment directly determined the product form: pull all the complexity inside the system and expose only four actions externally—upload assets, choose a template, submit a job, download the finished video.
This step is actually the most critical architectural decision in the whole experiment, and it explains why it’s worth handing to AI: clear requirements, well-defined boundaries, and verifiable outcomes—exactly the scenario where long-range tasks are easiest to validate.
3. Difficulty Assessment: A Systems Engineering Problem
Broken down, the workload isn’t in “writing code” but in “coordinating multiple constraints”:
| Layer | Key Problem | Direct Consequence of Getting It Wrong |
|---|---|---|
| Frontend | Routing architecture, auth-state management, generation-progress display | State lost on page refresh, duplicate submissions |
| Backend | Async job submission and query, idempotency, rate limiting | Same request charged twice |
| Data | Multi-tenant isolation, ledger consistency | Users can see others’ projects |
| Tasks | Queue, retries, timeouts, dead letters | Jobs stuck permanently in “generating” |
| Cost | Limited inference resources, per-item cost must be controllable | Budget blown by a few users |
The two categories most easily overlooked in AI generation are exactly the last two: failure paths and cost control. Because in a feature demo, everything succeeds.
4. Methodology: Constraining Long-Task Work with Spec-Driven Development
The biggest risk of a long task isn’t insufficient capability, but goal drift. To keep the model from falling apart during long generation, the work used spec-driven development, forcing it to split the flow into three stages, each producing a document first and code second:
Stage 1 — Research. Output the target-user profile, core flows, acceptance criteria, and explicit non-goals (which features are not being done this round).
Stage 2 — Architecture. Output technology choices, module boundaries, data model, failure-mode list, and the input/output contracts of key interfaces.
Stage 3 — Development. Implement module by module in small steps; each module must pass compilation and basic tests before moving to the next.
The prompt structure was roughly as follows (illustrative):
Role: senior full-stack architectGoal: implement a multi-tenant SaaS that turns "upload image assets → asynchronously generate marketing short videos"Hard constraints:1. The video generation endpoint must return a job ID immediately and must not wait synchronously within the request;2. Billing uses "pre-charge + settle"; failed jobs must release the pre-charge;3. Multi-tenant data isolation must be backstopped by database row-level security policies, not rely solely on application-layer filtering;4. For any uncertain technical details, first write them into a "questions to confirm" list; do not assume interface parameters on your own.Flow: research → architecture → development, output a document at each stage, and wait for my confirmation before entering the next stage.
The 4th constraint deserves special emphasis. The most typical failure mode of a model during long generation is that when it hits uncertain information, it refuses to stop and instead “invents” a plausible-looking interface and set of parameters. Explicitly requiring it to list questions first turns this kind of hallucination from a “silent error” into a “visible to-do,” which lowers the later fix cost by an order of magnitude.
5. Key Design Breakdown
5.1 Data Model: Append-Only Ledger, Balance as Cache Only
The core schema has five tables: users, projects, assets, video jobs, and the credit ledger. The single most important design principle is this: the credit ledger is append-only and never modified; the balance field serves only as a cache to speed up queries.
create table credit_ledger (id bigserial primary key,user_id bigint not null,delta integer not null, -- positive for top-up/refund, negative for chargesreason text not null,job_id bigint,created_at timestamptz not null default now());create unique index uniq_job_charge on credit_ledger (job_id)where reason = 'job_charge';
With this unique index, even if a job is retried or a callback arrives repeatedly, the charge for the same job succeeds only once—far more reliable than writing a pile of if checks in the application layer.
5.2 Async Tasks: Fast Submission, Queryable Status, Convergent Failures
Generation jobs usually take minutes or longer, and any synchronous-waiting scheme collapses against gateway timeouts. The correct structure is three-part:
# 1) Submit: validate, persist, enqueue only, and return immediately@app.post("/v1/jobs")async def create_job(req: JobCreate, user = Depends(current_user)):job = await jobs.create(user_id=user.id,request_key=req.idempotency_key,spec=req.spec,status="queued",)await queue.publish("video.generate", {"job_id": job.id})return {"job_id": job.id, "status": "queued"}# 2) Consume: the worker advances the state machine and writes each step to an events table# 3) Query: the frontend polls /v1/jobs/{id}, or subscribes to the event stream
Four companion details are all indispensable:
- Idempotency key: generated by the client with a server-side unique index, to prevent duplicate jobs from a user double-clicking;
- Retry limit and backoff: exponential backoff; once the limit is exceeded, move the job to a dead-letter queue rather than retrying forever;
- Explicit state machine:
queued → running → succeeded / failed, with illegal transitions rejected outright, avoiding dirty states like “already failed but still running”; - Polling backoff: the frontend progressively lengthens its polling interval, and the server rate-limits the query endpoint, so thousands of clients don’t hammer the database at once.
5.3 Credit Billing: Pre-Charge, Settle, Rollback
The key to billing correctness is not to “run first, charge later.” The sensible order is: pre-charge on submission, convert to a formal charge on success, and release on failure:
async with db.transaction():await db.execute("select id from users where id = :uid for update")balance = await credits.balance_of(user_id)if balance < estimated_cost:raise InsufficientCredit()await credits.append(user_id, -estimated_cost, "job_hold", job_id)
Row locking combined with ledger appends solves two problems at once: concurrent over-charging and difficult reconciliation. In addition, there should be a scheduled reconciliation job that scans tasks stuck in running for a long time and, per a timeout policy, forcibly marks them failed and releases the pre-charge—this is the backstop that guarantees “credits never get permanently occupied.”
5.4 Multi-Tenant Isolation: Application-Layer Filtering + Database Backstop
Relying only on where user_id = ? is fragile; one missed clause causes a data-access violation. A more robust approach lets the database participate in isolation:
alter table video_jobs enable row level security;create policy tenant_isolation on video_jobsusing (tenant_id = current_setting('app.tenant_id')::bigint);
There’s a pitfall to watch for with connection pooling: session variables linger as connections are reused, so each request must explicitly clear them before finishing—otherwise the previous tenant’s context may carry over into the next request. Cross-tenant operations backends, meanwhile, should run under a separate database role that bypasses the policy, rather than loosening the policy into a wildcard.
5.5 Security and Cost: The Two Most Easily Overlooked Places
Input side. Asset uploads must validate type, size, and file header; the storage bucket stays private and is accessed via short-lived signed links. If users are also allowed to pass external asset URLs directly, you must apply a domain allowlist and block internal-network address ranges, otherwise you introduce a server-side request forgery risk—this kind of vulnerability shows up quite often in AI-generated code, because it looks like nothing more than a small “download an image” function.
Cost side. Repeated generation of the same asset with the same template can be reused directly via fingerprint caching; draft-state jobs should be deduplicated; and each tenant should have concurrency and daily-quota caps. Without these three layers of control, an open generation endpoint is easily drained of budget by a small number of users.
If you need to put this architecture on the cloud, you can compose it on demand from general capability categories: object storage for assets and finished videos, a message queue for task distribution, a container platform for running the generation and backend services, and logging plus monitoring and alerting for observability. These are industry-standard capability categories, and the specific choices should be evaluated against traffic scale and the cost model.
6. Hands-On Pitfalls List
Having run the whole flow, what actually consumed the time wasn’t writing code but fixing the following kinds of problems:
- Context drift. Partway through, the model forgets the constraints set earlier (for example, quietly turning an async endpoint into a synchronous wait). The fix is to write the hard constraints as a checklist and re-paste it at the start of each stage.
- Interface-parameter hallucination. Non-existent config options or call methods appear during generation. The countermeasure is to first have it produce a to-confirm list, then use compilation and type checking to surface the problems.
- Large-scale refactoring causing compilation avalanches. After changing a dozen files at once, errors pile up beyond the point where they can be localized. The countermeasure is to force small, module-by-module steps, ensuring each step stays compilable and testable.
- Order of migrations and policies. Row-level security policies executing before the tables exist, or wrong ordering of foreign keys and indexes, both crash at the initialization stage. Require the model to treat the database setup script as a whole and output it in dependency order.
- Billing and job-state inconsistency. Jobs fail but credits aren’t released, or charges happen twice. These problems only surface under concurrency and must be covered by dedicated tests.
- Service-side speed fluctuation and quota limits. Long tasks slow down or get interrupted under concurrency-quota pressure. In practice, a more effective approach is to run in segments and save checkpoints, resuming from the checkpoint after an interruption rather than re-running the whole thing.
It’s also worth stating objectively that public discussions often feature “model X beats model Y” comparisons, but such rankings have limited value for engineering decisions—performance varies widely across different task distributions. Rather than argue over rankings, it’s better to test against your own acceptance criteria.
7. Conclusion: The Division of Labor Changed, the Responsibility Didn’t
The conclusion of this experiment is fairly clear: the center of gravity of AI coding tools is shifting from “generating code snippets” to “taking on system-level implementation.” It can complete cross-module, cross-layer implementation work in a single long task, compressing a skeleton that would otherwise take a team weeks of collaboration into hours.
But to understand the boundary of this conclusion accurately: what a few hours produces is a runnable skeleton, not a product ready for commercial use. Before going live, humans still need to do four things—security review (privilege escalation, injection, request forgery), concurrency load testing, compliance handling (personal information protection, content moderation, labeling of generated content), and integrating monitoring and alerting.
So the change in the developer’s role can be summed up as: from “writing implementations” to “defining specs, defining contracts, and doing acceptance.” The clearer the spec, the more stable the AI’s output; the more explicit the acceptance criteria, the less rework. This also explains why spec-driven development delivers far greater returns in long-task scenarios than in ordinary completion scenarios—what it constrains isn’t the code, but the goal itself.
