---
title: "Integrate AI Video Generation in Your App: Architecture | imaginary.app"
description: "Architecture for adding Veo 3.1 video generation to your app: a job table, a polling worker, rate-limit-aware queueing, safe retries and MP4 storage."
url: https://www.imaginary.app/blog/integrate-ai-video-generation-in-your-app
---

Updated November 2026

# Integrate AI Video Generation in Your App: A Production Architecture

Treat each video as a background job. Your backend writes a row to a job table. A worker submits it to `POST /api/generate`, polls `GET /api/status/:taskId` every 10 seconds, copies the finished MP4 to your own storage, and then notifies the user. There are no webhooks, so the worker owns polling, queueing under the concurrency limit, and safe retries.

Key takeaways

- The API key lives only in your backend and worker, never in a browser or mobile app.
- A job table is your source of truth. Store the `taskId` the moment you get it.
- Cap in-flight jobs under the default of 10 per account, and requeue on HTTP 429.
- Never blind-retry a POST that timed out. Look the job up in `/api/logs` first. A random `seed` makes the lookup exact.
- Download results to your own storage. Failed jobs refund their credits automatically.

Veo 3.1 in your product

Add video generation without running Google Cloud

One API key for Veo 3.1 Lite, Fast and Quality. Prepaid credits, refunds on failed generations.

[Get API Access](https://www.imaginary.app/api)[Read the Docs](https://www.imaginary.app/api-docs)

Sign in with Google to create an account; buy credits only when you need them.

## Why video needs a job architecture

A Veo 3.1 clip takes minutes, not milliseconds. The API reports typical times of 1–2 minutes on Lite, 1–3 on Fast and 2–5 on Quality. Our backend waits up to about 8 minutes on Lite and Fast and about 10 minutes on Quality before it fails a job and refunds it. You can't hold an HTTP request open that long, and you shouldn't make users keep a tab open. So the request returns at once with HTTP 202 and a `taskId`, and the rest happens in the background. Video generation also costs real money (10 credits, about $2.13–$2.50, for an 8-second Fast 1080p clip with audio), which is why duplicate submissions and lost results are expensive bugs.

New to the API? Send one request by hand with the [five-step quick start](https://www.imaginary.app/blog/getting-started-veo-3-api) first. Every endpoint and limit is listed in [Veo 3.1 API access](https://www.imaginary.app/blog/veo-3-1-api-access).

## The architecture

```
  Browser / mobile app
        │  POST /videos (your API, your auth)
        ▼
  Your backend ──insert──▶ video_jobs table (status = queued)
                                 │
                                 ▼
  Worker loop (every 10 s)
   1. reconcile  : jobs stuck in "submitting" ──▶ GET  /api/logs
   2. drainQueue : queued jobs, max 8 in flight ──▶ POST /api/generate   (202 + taskId)
   3. pollActive : pending/processing jobs ─────▶ GET  /api/status/:taskId
                    completed ─▶ download MP4 ─▶ your storage (S3, GCS, R2…)
        │
        ▼
  Notify your user (SSE, WebSocket, push, email) ─ or let the client poll your API
```

1. ### Your API accepts the request and writes a row

   Authenticate your user, check the prompt (1–2,000 characters; the developer API rejects empty prompts), check their quota in your own app, and insert a `queued` job. Return your own job id. The user never sees our task id or key.

2. ### A worker submits jobs under the limits

   One process drains the queue. By default an account can run 10 generations at once and send 100 generate requests per hour per key. On `429` (`CONCURRENT_LIMIT_EXCEEDED` or `RATE_LIMIT_EXCEEDED`), put the job back and wait. A `400` is final: the `errorType` and `field` tell you why.

3. ### The worker polls and stores results

   Poll each running task about every 10 seconds, which is the interval the API suggests. When it completes, download `result.videoUrl` and upload it to your bucket. We don't publish a retention period for result URLs, so don't serve them to users directly.

4. ### Your app tells the user

   Since we don't send webhooks, the worker is where "done" happens. Emit your own event from there: a server-sent event, WebSocket message, push notification or email. Or let the client poll your own `GET /videos/:id`, which is cheap because it only reads your database.

## Reference implementation (Node.js)

Two small files share a SQLite database. Swap SQLite for Postgres and the local `videos/` folder for object storage, and the shape stays the same.

### The web API

```
// app.mjs: your web API only writes a row. It never calls the video API directly.
import express from 'express';
import Database from 'better-sqlite3';
import { randomInt } from 'node:crypto';

const db = new Database('jobs.db');
db.exec(
  'CREATE TABLE IF NOT EXISTS video_jobs (' +
  ' id INTEGER PRIMARY KEY, user_id TEXT NOT NULL, prompt TEXT NOT NULL,' +
  ' model TEXT NOT NULL, seed INTEGER NOT NULL, status TEXT NOT NULL,' +
  ' task_id TEXT, credits INTEGER, file_path TEXT, error TEXT, submitted_at TEXT,' +
  " created_at TEXT DEFAULT (datetime('now')))"
);

const app = express();
app.use(express.json());

app.post('/videos', (req, res) => {
  const prompt = String(req.body.prompt ?? '').trim();
  if (!prompt || prompt.length > 2000) return res.status(400).json({ error: 'prompt: 1-2000 chars' });
  // The seed is part of the request, and it doubles as our correlation id (see reconcile()).
  const seed = randomInt(0, 4294967295);
  const { lastInsertRowid } = db
    .prepare("INSERT INTO video_jobs (user_id, prompt, model, seed, status) VALUES (?, ?, 'veo3-fast', ?, 'queued')")
    .run(req.get('x-user-id') ?? 'demo', prompt, seed);   // use your real auth here
  res.status(202).json({ jobId: Number(lastInsertRowid) });
});

app.get('/videos/:id', (req, res) => {
  const job = db.prepare('SELECT id, status, file_path, error FROM video_jobs WHERE id = ?').get(req.params.id);
  return job ? res.json(job) : res.sendStatus(404);
});

app.listen(3000);
```

### The worker

```
// worker.mjs: Node 18+. npm install better-sqlite3
import Database from 'better-sqlite3';
import { mkdir, writeFile } from 'node:fs/promises';

const BASE = process.env.IMAGINARY_API_BASE ?? 'https://api.veo3gen.app'; // api.imaginary.app is an alias
const KEY = process.env.IMAGINARY_API_KEY;
const MAX_IN_FLIGHT = 8;                          // the account default allows 10 concurrent jobs
const db = new Database('jobs.db');              // same file as app.mjs

async function api(path, init = {}) {
  const res = await fetch(BASE + path, {
    ...init,
    headers: { Authorization: 'Bearer ' + KEY, 'Content-Type': 'application/json' },
  });
  return { status: res.status, body: await res.json().catch(() => ({})) };
}

const set = (id, fields) => {
  const keys = Object.keys(fields);
  db.prepare('UPDATE video_jobs SET ' + keys.map((k) => k + ' = ?').join(', ') + ' WHERE id = ?')
    .run(...keys.map((k) => fields[k]), id);
};

// 1. A POST that never got a response may still have created a task. Look it up by seed.
async function reconcile() {
  const cutoff = new Date(Date.now() - 2 * 60_000).toISOString();
  const stuck = db.prepare("SELECT * FROM video_jobs WHERE status = 'submitting' AND submitted_at < ?").all(cutoff);
  for (const job of stuck) {
    const since = new Date(Date.parse(job.submitted_at) - 60_000).toISOString();
    const { status, body } = await api('/api/logs?limit=100&startDate=' + encodeURIComponent(since));
    if (status !== 200) continue;
    const hit = body.logs.find((l) => l.options?.seed === job.seed && l.model === job.model);
    if (hit) set(job.id, { task_id: hit.taskId, status: 'pending' });   // pollActive takes it from here
    else set(job.id, { status: 'queued' });                              // never reached the API: safe to resend
  }
}

// 2. Submit queued jobs without exceeding the concurrency limit.
async function drainQueue() {
  const { n } = db.prepare("SELECT COUNT(*) AS n FROM video_jobs WHERE status IN ('submitting','pending','processing')").get();
  const batch = db.prepare("SELECT * FROM video_jobs WHERE status = 'queued' ORDER BY id LIMIT ?").all(Math.max(0, MAX_IN_FLIGHT - n));
  for (const job of batch) {
    set(job.id, { status: 'submitting', submitted_at: new Date().toISOString() });
    let r;
    try {
      r = await api('/api/generate', {
        method: 'POST',
        body: JSON.stringify({
          model: job.model, prompt: job.prompt, audio: true,
          options: { resolution: '1080p', aspectRatio: '9:16', duration: 8, seed: job.seed },
        }),
      });
    } catch {
      continue;                     // no response: leave as 'submitting' for reconcile(), never blind-retry
    }
    if (r.status === 202) set(job.id, { task_id: r.body.taskId, credits: r.body.creditsRequired, status: 'pending' });
    else if (r.status === 429) { set(job.id, { status: 'queued' }); return; }   // back off until next tick
    else if (r.body.errorType === 'INSUFFICIENT_CREDITS') {
      set(job.id, { status: 'queued' });           // keep the job; top up and it resumes
      console.error('Out of credits: need', r.body.required, 'have', r.body.available);
      return;
    }
    else set(job.id, { status: 'rejected', error: r.body.errorType + ': ' + r.body.error });
  }
}

// 3. Poll running jobs, and copy finished videos to storage you control.
async function pollActive() {
  const active = db.prepare("SELECT * FROM video_jobs WHERE status IN ('pending','processing')").all();
  for (const job of active) {
    const { status, body } = await api('/api/status/' + job.task_id);
    if (status !== 200) continue;
    if (body.status === 'completed') {
      const mp4 = Buffer.from(await (await fetch(body.result.videoUrl)).arrayBuffer());
      await mkdir('videos', { recursive: true });
      const file = 'videos/' + job.task_id + '.mp4';    // replace with an S3/GCS upload in production
      await writeFile(file, mp4);
      set(job.id, { status: 'completed', file_path: file });
    } else if (['failed', 'timeout', 'cancelled'].includes(body.status)) {
      set(job.id, { status: 'failed', error: body.error.type + ': ' + body.error.message }); // credits auto-refunded
    } else if (body.status !== job.status) {
      set(job.id, { status: body.status });
    }
  }
}

for (;;) {
  try { await reconcile(); await drainQueue(); await pollActive(); }
  catch (err) { console.error(err); }
  await new Promise((r) => setTimeout(r, 10_000));
}
```

Run one worker instance. If you need several, claim jobs with a row lock (for example `SELECT … FOR UPDATE SKIP LOCKED` in Postgres) so two workers never submit the same row.

## Failure handling that matches the API

| Situation                         | What the API does                                               | What your worker should do                           |
| --------------------------------- | --------------------------------------------------------------- | ---------------------------------------------------- |
| Prompt rejected by the pre-check  | 400 CONTENT\_POLICY\_VIOLATION; no credits taken                | Mark the job rejected; tell the user to rephrase     |
| Not enough credits                | 400 INSUFFICIENT\_CREDITS with required and available           | Pause the queue and alert yourself; do not drop jobs |
| Too many jobs or requests         | 429 CONCURRENT\_LIMIT\_EXCEEDED or RATE\_LIMIT\_EXCEEDED        | Requeue and retry on a later tick                    |
| POST timed out, no response       | A job may or may not exist                                      | Find it in /api/logs by seed before resending        |
| Generation failed or was filtered | Status failed; error.type and error.retryable; credits refunded | Resubmit only if retryable is true                   |
| Refund still processing           | recoveryState: "refund\_pending"; retried automatically         | Show "failed, refund pending"; no action needed      |
| Worker crashed mid-job            | The task keeps running on our side                              | On restart, resume polling every stored taskId       |

Keep the key server-side

Store `IMAGINARY_API_KEY` in your secrets manager. Use a separate key per environment (you can have up to 10), and rotate it from the [API page](https://www.imaginary.app/api) if it leaks. Don't forward `GET /api/status/:taskId/details` responses to end users: they include your account email.

## Cost controls inside your app

Every generate response returns `creditsRequired`, and every status response reports `charged` and `refunded`. Save these on the job row and you have per-user cost accounting for free. To show a price before the user submits, read the public `GET /api/pricing` catalog (the [pay-as-you-go pricing guide](https://www.imaginary.app/blog/cheap-ai-video-api-pay-as-you-go) has a snippet), or try combinations in the [cost calculator](https://www.imaginary.app/tools/veo-3-1-cost-calculator). A cheap default for previews is a 4-second silent Lite 720p clip at 1 credit. Render on Fast or Quality only when the user commits.

One more design note: keep the provider behind a small interface (`submit`, `status`, `fetchResult`). Google Cloud's Veo API uses the same submit-and-poll shape, so if your volume later justifies [moving to Google Cloud](https://www.imaginary.app/blog/veo-3-api-vs-google-vertex-ai), you only swap one module. That matters this year: Google shut down the Gemini API Veo previews on October 22, 2026, which forced every app built on them to change provider. With the provider behind one module, that kind of change stays small.

## Frequently asked questions

### Does the API send webhooks when a video is ready?

No. Completion is reported only through GET /api/status/{taskId}. Run a worker that polls about every 10 seconds; status checks have their own limit of 120 per minute per key, so polling does not eat into your generation quota. Your app can then send its own webhook or push notification to your users.

### Can I call the API directly from the browser?

No. Cross-origin browser requests are blocked, and a key in front-end code can be copied and used to spend your credits. Call the API from your backend and give your users your own endpoints.

### Is it safe to retry POST /api/generate?

Retry freely on 429 and on 4xx responses after fixing the request, because those never create a job. If the request timed out with no response, a job may exist. The API has no idempotency key, so look the job up in GET /api/logs before you resend. Sending a random seed with each job and matching on it makes this reliable.

### How long are video URLs valid?

We do not publish a retention period for result URLs. Download each finished MP4 to your own storage when the job completes, and serve it from there.

### How many jobs can run at once?

By default 10 per account, plus 100 generate requests per hour per key. Keep a queue in your own database and cap in-flight jobs a little under 10, as the worker on this page does.

How we checked: response fields, limits and log filters in the code above were compared with our backend's developer generate, status and logs routes on November 8, 2026. The sample code has not been load-tested. Treat it as a starting point.

## Sources

Prices, model specs and dates on this page were checked on November 8, 2026. Third-party prices change; check the source before you rely on a number.

- [Google AI for Developers — Gemini API deprecations](https://aistudio.google.com/docs/deprecations)
- [imaginary.app pricing](https://www.imaginary.app/pricing)

Ship the feature

## Get a key and wire up your first job

Packs from $9.99, no subscription. Full reference in the API docs.

[Get API Access](https://www.imaginary.app/api)[Read the Docs](https://www.imaginary.app/api-docs)

Sign in with Google to create an account; buy credits only when you need them.
