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.

    1. app/
    2. layout.tsx Root layout with global styles
    3. (auth)/login/page.tsx Login page
    4. (app)/layout.tsx Authenticated layout; calls /api/v1/me
    5. (app)/jobs/page.tsx Job list
    6. (app)/jobs/[id]/page.tsx Job details and progress
    7. (app)/jobs/[id]/loading.tsx Loading skeleton for the details page
    8. components/
    9. upload-zone.tsx Asset upload
    10. job-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:

    1. POST /api/v1/jobs
    2. Authorization: Bearer <access_token> Issued by the server; tenant and user identity are extracted from it
    3. Idempotency-Key: <client-generated UUID> Idempotency key
    4. X-Request-Id: <trace identifier> Request tracing identifier

    The request body supplied by the frontend is:

    1. {
    2. "title": "Spring promotion video",
    3. "material_ids": ["m_01", "m_02"],
    4. "template": "promo_basic",
    5. "duration_seconds": 30
    6. }

    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:

    1. {
    2. "job_id": "j_7f3a9c",
    3. "status": "queued",
    4. "credit_cost": 10,
    5. "created_at": "2026-11-19T21:30:31Z"
    6. }

    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:

    1. Validate the token and extract the tenant and user identity.
    2. Validate the format of the request body.
    3. 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.
    4. Query for an existing job using (tenant_id, Idempotency-Key). If a record exists with the same hash, return the original job_id without enqueueing another task or freezing credits again. If the hashes differ, return 409.
    5. Verify that every material_id belongs to the tenant, then check and freeze the required credits.
    6. 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.
    7. 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_id on 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

    1. CREATE TABLE jobs (
    2. id BIGSERIAL PRIMARY KEY,
    3. tenant_id BIGINT NOT NULL,
    4. user_id BIGINT NOT NULL,
    5. public_id VARCHAR(32) NOT NULL,
    6. status VARCHAR(16) NOT NULL,
    7. idempotency_key VARCHAR(64),
    8. request_hash CHAR(64) NOT NULL,
    9. credit_cost INT NOT NULL CHECK (credit_cost > 0),
    10. attempt INT NOT NULL DEFAULT 0,
    11. lease_until TIMESTAMPTZ,
    12. created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    13. CONSTRAINT uq_jobs_tenant_public UNIQUE (tenant_id, public_id),
    14. CONSTRAINT uq_jobs_tenant_idem UNIQUE (tenant_id, idempotency_key)
    15. );
    16. 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):

    1. ALTER TABLE jobs ENABLE ROW LEVEL SECURITY;
    2. ALTER TABLE jobs FORCE ROW LEVEL SECURITY;
    3. CREATE POLICY tenant_isolation ON jobs
    4. USING (tenant_id = NULLIF(current_setting('app.tenant_id', true), '')::bigint)
    5. 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) returns NULL rather than raising an error when the setting is missing. NULLIF also converts an empty string to NULL. The comparison therefore evaluates to NULL, filtering out all rows and returning zero results.
    • If NULLIF is removed and the value is cast directly, an empty string causes a bigint conversion error. Neither behavior permits cross-tenant access, but test expectations must match the policy implementation. This article uses the NULLIF form.
    • WITH CHECK restricts the rows written by INSERT and UPDATE. If it is omitted, PostgreSQL reuses the USING expression, but declaring it explicitly makes the policy easier to review.
    • FORCE ROW LEVEL SECURITY also subjects the table owner to the policy. Superusers and roles with the BYPASSRLS attribute 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:

    1. BEGIN;
    2. SELECT set_config('app.tenant_id', $1, true);
    3. -- Business statements
    4. COMMIT;

    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.