Video SaaS Architecture Breakdown: An Acceptance Checklist from APIs to Billing
This technical guide presents a system-level acceptance checklist for a short-video SaaS platform, covering frontend structure, API contracts, idempotent job creation, multi-tenant data isolation, PostgreSQL row-level security, asynchronous task delivery, and credit handling. The examples use Next.js, FastAPI, PostgreSQL, Redis, and object storage, with all field names, statuses, and error codes treated as implementation examples rather than fixed standards.
1. Why Perform a System-Level Breakdown?
The capability boundaries of an AI-powered programming tool depend on whether it can maintain consistency across multiple modules. Generating a single page is relatively straightforward. A short-video generation SaaS platform involves the frontend, APIs, database, task queue, and billing system. Any change in one area can affect the others, making this type of system a useful evaluation target.
This article is a design breakdown, not a retrospective of a real project. It does not document tool versions, task durations, or failure rates. All conclusions are based on the stated design assumptions. Field names, status values, and error codes are examples and should be adapted to the team’s conventions during implementation.
The assumed technology stack is:
- Frontend: Next.js 15 with the App Router.
- Backend: FastAPI with an asynchronous database driver.
- Database: PostgreSQL 16. The example SQL uses syntax compatible with this version.
- Queue: Redis or another message queue for distributing asynchronous tasks.
- Asset storage: Object storage. The database stores only asset references.
Version numbers should be determined by the project lock files, such as package-lock.json, uv.lock, or poetry.lock. Before release, verify the syntax and behavior of each version against its official documentation.
2. Frontend and API Contracts
2.1 Frontend Structure and Session Validation
The frontend is organized by routes and layouts. The authenticated layout validates the user session, and the page requests the current user’s information from the server during loading.
app/layout.tsx Root layout with global styles(auth)/login/page.tsx Login page(app)/layout.tsx Authenticated layout; calls /api/v1/me(app)/jobs/page.tsx Job list(app)/jobs/[id]/page.tsx Job details and progress(app)/jobs/[id]/loading.tsx Loading skeleton for the details pagecomponents/upload-zone.tsx Asset uploadjob-progress.tsx Progress polling
Streaming rendering is implemented with loading.tsx and Suspense. The page displays its structural shell first and fills in the job data when it becomes available.
The frontend must not determine the tenant identity. The server extracts the tenant context from the access token. Even if a request includes a tenant parameter from the frontend, the server must ignore it.
2.2 Video Job Creation API
The request headers are:
POST /api/v1/jobsAuthorization: Bearer <access_token> Issued by the server; tenant and user identity are extracted from itIdempotency-Key: <client-generated UUID> Idempotency keyX-Request-Id: <trace identifier> Request tracing identifier
The request body supplied by the frontend is:
{"title": "Spring promotion video","material_ids": ["m_01", "m_02"],"template": "promo_basic","duration_seconds": 30}
The following fields are controlled by the server and must not be accepted from the frontend:
tenant_id, user_id, job_id, status, credit_cost, and created_at.
On success, the API returns HTTP 202:
{"job_id": "j_7f3a9c","status": "queued","credit_cost": 10,"created_at": "2026-11-19T21:30:31Z"}
2.3 Error Codes
| HTTP status | Error code | Meaning |
|---|---|---|
| 400 | invalid_param |
A field is missing or has an invalid format |
| 401 | token_invalid |
The token is invalid or expired |
| 402 | insufficient_credits |
The available credit balance is insufficient |
| 404 | material_not_found |
The asset does not exist or does not belong to the current tenant |
| 409 | idempotency_conflict |
The same idempotency key was used with a different request body |
| 429 | rate_limited |
Requests are being sent too frequently |
| 503 | queue_unavailable |
The queue is temporarily unavailable |
HTTP 402 is a reserved status code in the HTTP specification. If the team already has a unified error-code convention, it should be replaced with the team’s standard. The frontend should display an “Insufficient credits” message for this error and provide a route to purchase additional credits.
2.4 Idempotency Processing Order
The server processes the request in the following order:
- Validate the token and extract the tenant and user identity.
- Validate the format of the request body.
- Normalize the request body by sorting keys and removing unnecessary whitespace. Calculate its SHA-256 hash as a 64-character hexadecimal string and store it in
request_hash. - Query for an existing job using
(tenant_id, Idempotency-Key). If a record exists with the same hash, return the originaljob_idwithout enqueueing another task or freezing credits again. If the hashes differ, return409. - Verify that every
material_idbelongs to the tenant, then check and freeze the required credits. - Write the job record and the outbox record in the same transaction. After the transaction commits, a delivery process publishes the message to the queue.
- If a unique-constraint conflict occurs during the write, another concurrent request completed first. Reload the record and return to step 4.
The idempotency key is scoped to a tenant. Its retention period should be determined by the team based on the retry window, such as 24 hours.
If the gateway does not receive an X-Request-Id, it generates one automatically. When a value is provided, the gateway validates its length and character set, returns it unchanged in the response header, and writes it to the request_id field in logs and queue messages. Tokens and secrets must never be recorded in logs.
Every material_id must be checked for tenant ownership. Hiding a button in the frontend is not a substitute for server-side authorization.
Secrets, database passwords, and token-signing keys must be stored only in environment variables or a secret-management service. They must not be placed in source code, sample configuration files, or logs.
3. Multi-Tenant Data Isolation
3.1 Choosing an Isolation Model
There are three common approaches:
- Shared database and shared tables, with a
tenant_idon every row: This has the lowest cost, but isolation depends entirely on the correctness of application code and database policies. - Shared database with a separate schema for each tenant: The isolation boundary is clearer, but migrations must be executed for each tenant.
- A separate database for each tenant: This provides the strongest isolation, but has the highest operational cost.
This article uses the first approach. It is suitable for small and medium-sized SaaS platforms, but it must be combined with mandatory tenant filtering and row-level security.
3.2 Example Table Definition
CREATE TABLE jobs (id BIGSERIAL PRIMARY KEY,tenant_id BIGINT NOT NULL,user_id BIGINT NOT NULL,public_id VARCHAR(32) NOT NULL,status VARCHAR(16) NOT NULL,idempotency_key VARCHAR(64),request_hash CHAR(64) NOT NULL,credit_cost INT NOT NULL CHECK (credit_cost > 0),attempt INT NOT NULL DEFAULT 0,lease_until TIMESTAMPTZ,created_at TIMESTAMPTZ NOT NULL DEFAULT now(),CONSTRAINT uq_jobs_tenant_public UNIQUE (tenant_id, public_id),CONSTRAINT uq_jobs_tenant_idem UNIQUE (tenant_id, idempotency_key));CREATE INDEX idx_jobs_tenant_status ON jobs (tenant_id, status, created_at);
public_id is exposed externally, while id is used only for internal relationships. Both unique constraints use tenant_id as the leading column, allowing different tenants to use the same idempotency key or public identifier without interfering with one another.
Jobs created through the API must include an Idempotency-Key; the application layer is responsible for ensuring that the field is present. Internal jobs may use NULL. PostgreSQL unique constraints allow multiple NULL values by default, so internal jobs will not conflict with one another.
After the retention period expires, the application can set the expired job’s idempotency_key to NULL, removing it from unique-constraint checks while retaining the job record itself.
3.3 Mandatory Tenant Filtering and Row-Level Security
Every repository method must receive a tenant_id parameter. Raw queries without tenant filtering are prohibited.
Enable row-level security (RLS):
ALTER TABLE jobs ENABLE ROW LEVEL SECURITY;ALTER TABLE jobs FORCE ROW LEVEL SECURITY;CREATE POLICY tenant_isolation ON jobsUSING (tenant_id = NULLIF(current_setting('app.tenant_id', true), '')::bigint)WITH CHECK (tenant_id = NULLIF(current_setting('app.tenant_id', true), '')::bigint);
Several details of this policy are important:
current_setting('app.tenant_id', true)returnsNULLrather than raising an error when the setting is missing.NULLIFalso converts an empty string toNULL. The comparison therefore evaluates toNULL, filtering out all rows and returning zero results.- If
NULLIFis removed and the value is cast directly, an empty string causes abigintconversion error. Neither behavior permits cross-tenant access, but test expectations must match the policy implementation. This article uses theNULLIFform. WITH CHECKrestricts the rows written byINSERTandUPDATE. If it is omitted, PostgreSQL reuses theUSINGexpression, but declaring it explicitly makes the policy easier to review.FORCE ROW LEVEL SECURITYalso subjects the table owner to the policy. Superusers and roles with theBYPASSRLSattribute always bypass RLS, so the application role must not have either privilege.
Set the tenant context at the start of every transaction and keep it in the same transaction as the business statements:
BEGIN;SELECT set_config('app.tenant_id', $1, true);-- Business statementsCOMMIT;
When the third argument is true, the setting is valid only for the current transaction and is cleared after commit or rollback. Because connection pools reuse connections, this prevents one request’s tenant context from leaking into the next request.
If set_config is executed separately in autocommit mode, its effect is limited to that statement, and subsequent business statements will not see the tenant context. Do not use a session-level SET without LOCAL to configure the tenant, because the value would remain active for the entire database session.
The tenant ID must come from the token, never from the request body.
3.4 Cross-Tenant Authorization Test Case
Prepare tenant A with ID 1 and tenant B with ID 2, each with its own test data. Verify that a request authenticated as tenant A cannot read, update, or reference jobs and materials belonging to tenant B.
