PDF VectorPDF Vector
Back to all articles

Document Processing Architecture for SaaS

A practical pipeline for SaaS document processing: ingest, queue, parse or extract, validate, store. Idempotency, retries, callbacks, tier costs and tenants.

Document Processing Architecture for SaaS

A document processing architecture for a SaaS product has five stages: ingest the file, queue a job, call the parsing or extraction API, validate the result, and store it with enough metadata to debug and bill. The parsing model gets most of the attention, but production problems usually come from the parts around it: duplicate uploads, retries that charge twice, webhooks that arrive for a job nobody remembers, one tenant's backlog starving everyone else, and costs nobody can attribute. This guide lays out a design that handles those, using PDF Vector as the processing layer, with code for the worker, the webhook receiver and the validation step.

The pipeline at a glance

 sources                ingest                 queue               process                  validate           store / notify
 ─────────              ──────                 ─────               ───────                  ────────           ──────────────
 web upload  ─┐
 email inbox ─┼─>  object storage +   ─>  job per document  ─>  parse / extract /   ─>  schema + rules  ─>  DB rows, search
 cloud drive ─┤    documents row          (tenant-aware)        ask via API            pass / review       index, webhooks,
 customer API ┘    (status, hash)                               (sync or callback)                         UI updates

Two ideas hold it together:

  1. One ingestion path for every source. Uploads, forwarded emails, synced drive folders and your public API all end in the same place: the original file in object storage and a documents row. Everything after that is source-agnostic, so adding a new source never means touching parsing code.
  2. One internal service owns the document API. Call it a document gateway: it holds the API keys, decides which operation and tier to use, retries, records credits per tenant, and is the only code that talks to PDF Vector. Product features ask the gateway for "the invoice fields of document 123", not for a specific model.

Stage 1: ingest

When a file arrives:

  • Store the original in object storage under a key you control (tenant/{tenantId}/documents/{documentId}/original.pdf). Never rely on the uploader's URL staying valid.
  • Create the documents row with id, tenant_id, source, filename, content_type, byte_size, sha256, status = 'received'.
  • Deduplicate by hash. If the same tenant already has a processed document with the same sha256, link to the existing result instead of paying to process it again. Email rules that fire twice and users who upload the same statement twice are common.
  • Reject early what the API will reject. Check size and type against the tier you plan to use. nano, mini and pro accept files up to 40 MB and 30 pages; max and auto accept up to 500 MB and 2,000 pages. Images (PNG, JPG, TIFF, BMP, HEIF) need pro, max or auto. Password-protected PDFs are rejected, so ask the user to remove the password at upload time instead of failing later.

Supported inputs cover PDF, Word, Excel, PowerPoint (and the older DOC/XLS/PPT), OpenDocument, CSV, TXT/Markdown/TSV/XML, HTML, RTF, EPUB and images, so most SaaS products can route everything through one path.

Stage 2: queue

Never call the document API inside the upload request. Put a job on a queue keyed by the document:

create table document_jobs (
  id              bigserial primary key,
  document_id     text not null,
  tenant_id       text not null,
  operation       text not null,          -- 'invoice.extract', 'document.parse', ...
  schema_version  int not null default 0,  -- 0 for operations without a schema (parse)
  model           text not null default 'auto',
  status          text not null,          -- queued | running | waiting_callback | done | review | failed | blocked
  attempts        int not null default 0,
  callback_token  text unique,
  request_id      bigint,                 -- PDF Vector requestId of the last attempt
  credits         int,
  error_code      text,
  created_at      timestamptz not null default now(),
  unique (document_id, operation, schema_version)
);

The unique constraint is your idempotency guarantee: enqueueing the same document for the same operation twice is a no-op. This matters because the API itself does not deduplicate. documentId (sent as the x-pdfvector-document-id header or a documentId body field) is an attribution label that comes back in the response and in usage records; sending the same documentId twice runs and bills the work twice.

Make the queue tenant-aware. A simple approach is a per-tenant concurrency cap (for example, at most N running jobs per tenant) so one customer importing 5,000 PDFs does not delay everyone else's single upload.

Stage 3: process

Pick the operation by what consumes the output

ConsumerOperationNotes
Your code (fields, records, calculations)Extract (/api/document/extract, /api/invoice/extract, /api/bankStatement/extract, /api/identity/extract)You send a prompt and a JSON schema; you get data in that shape
Search, RAG, previews, human readingParse (/api/document/parse and the type-specific parse endpoints)Returns markdown; includePages: true adds per-page Markdown; max also returns html
One question per documentAskReturns an answer in markdown

Use the type-specific endpoints for invoices, bank statements and identity documents, and Document Extract for everything else (contracts, purchase orders, applications, resumes). Version your schemas (schema_version above) so a stored result always says which shape it has.

Synchronous worker with retries

For most documents a synchronous call from a worker is simplest. The TypeScript SDK throws typed errors with fields that tell you what to do next: retryable, retryableWithHigherModel, userError, requestId and, on 429, retryAfterSeconds.

import {
  createClient,
  isPDFVectorError,
  PaymentRequiredError,
  TooManyRequestsError,
} from "@pdfvector/client";

const client = createClient({ apiKey: process.env.PDFVECTOR_API_KEY });

type Model = "auto" | "nano" | "mini" | "pro" | "max";
const nextTier: Partial<Record<Model, Model>> = { nano: "mini", mini: "pro", pro: "max" };

type Job = {
  documentId: string;
  tenantId: string;
  fileUrl: string; // short-lived signed URL to the original in object storage
  model: Model;
  attempts: number;
};

type Outcome =
  | { kind: "done"; data: unknown; credits: number; model: string; requestId: number }
  | { kind: "retry"; delaySeconds: number; model?: Model }
  | { kind: "blocked"; reason: string }
  | { kind: "failed"; code: string; message: string; requestId?: number };

const backoff = (attempts: number) => Math.min(30 * 2 ** attempts, 3600);

export async function runInvoiceExtract(job: Job, prompt: string, schema: Record<string, unknown>): Promise<Outcome> {
  try {
    const result = await client.invoice.extract(
      { url: job.fileUrl, prompt, schema, model: job.model },
      { context: { documentId: `${job.tenantId}:${job.documentId}` } },
    );
    return {
      kind: "done",
      data: result.data,
      credits: result.credits,
      model: result.model,
      requestId: result.requestId,
    };
  } catch (error) {
    if (error instanceof PaymentRequiredError) {
      // Out of credits or a billing hold: pause the queue and alert, don't retry.
      return { kind: "blocked", reason: error.reasonCode ?? "PAYMENT_REQUIRED" };
    }
    if (error instanceof TooManyRequestsError) {
      return { kind: "retry", delaySeconds: error.retryAfterSeconds ?? 30 };
    }
    if (isPDFVectorError(error)) {
      const higher = nextTier[job.model];
      if (error.retryableWithHigherModel && higher) {
        return { kind: "retry", delaySeconds: 0, model: higher };
      }
      if (error.retryable && !error.retryableWithHigherModel && job.attempts < 5) {
        return { kind: "retry", delaySeconds: backoff(job.attempts) };
      }
      return { kind: "failed", code: error.code, message: error.message, requestId: error.requestId };
    }
    // Network errors (DNS, connection reset, timeout) are not PDFVectorErrors.
    return job.attempts < 5
      ? { kind: "retry", delaySeconds: backoff(job.attempts) }
      : { kind: "failed", code: "NETWORK", message: String(error) };
  }
}

Points worth copying:

  • Failed requests are not charged, so retrying a 5xx or a 429 costs nothing. A request that succeeded but whose response you lost (a network timeout on your side) was charged; retrying it charges again. Keep client timeouts generous, and use the callback mode for long files.
  • User errors go back to the user. userError: true (password-protected file, unsupported format, an expired link) means the document needs fixing, so show error.title and error.suggestion in your UI instead of paging an engineer.
  • URL download failures from the source site (reasonCode: "UPSTREAM_FETCH_FAILED") are marked retryable. Sending the bytes yourself (file or base64) avoids them entirely; if you pass signed URLs from your own storage, give them a lifetime longer than your maximum queue delay.
  • 402 stops the line. PaymentRequiredError tells you whether credits ran out (isCreditsExhausted, resetsAt) or billing is on hold (isBillingHold). Pause the queue rather than burning retries.

Async mode with callback for long documents

A 600-page contract bundle on max can take longer than your worker or load balancer wants to hold a connection. Every document operation accepts callback: { url }: the API answers 202 {"status": "processing"} immediately and POSTs the full result to your URL when done.

import { randomBytes } from "node:crypto";

export async function submitParseWithCallback(job: { documentId: string; tenantId: string; fileUrl: string }) {
  const token = randomBytes(24).toString("hex");
  await db.documentJobs.update(job.documentId, { status: "waiting_callback", callbackToken: token });

  const res = await fetch("https://global.pdfvector.com/api/document/parse", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${process.env.PDFVECTOR_API_KEY}`,
      "Content-Type": "application/json",
      "x-pdfvector-document-id": `${job.tenantId}:${job.documentId}`,
    },
    body: JSON.stringify({
      url: job.fileUrl,
      model: "max",
      includePages: true,
      callback: { url: `https://api.example.com/hooks/pdfvector?token=${token}` },
    }),
  });
  if (res.status !== 202) {
    throw new Error(`Submit failed: ${res.status} ${await res.text()}`);
  }
}

The receiver should do almost nothing synchronously:

export async function handlePdfVectorCallback(request: Request): Promise<Response> {
  const token = new URL(request.url).searchParams.get("token");
  const job = token ? await db.documentJobs.findByCallbackToken(token) : null;
  if (!job) return new Response("unknown job", { status: 404 });

  const failed = request.headers.get("x-pdfvector-callback-failed") === "true";
  const body = await request.json();
  // Store the raw payload and hand off to the validation stage asynchronously.
  await db.callbackInbox.insert({ jobId: job.id, failed, body, receivedAt: new Date() });
  return new Response(null, { status: 204 });
}

(db stands for your own data layer.) What the code accounts for:

  • Callbacks are not signed. Anyone who knows the URL could post to it, so the unguessable per-job token in the URL is the authentication. Reject unknown tokens and ignore a second callback for a job that is already done.
  • JSON only. The callback is read from a JSON request body, so send url or base64, not a multipart upload.
  • Public HTTPS endpoint, single delivery. The callback URL must resolve to a public address. The result is POSTed once with a 30-second timeout, so acknowledge quickly and process from your inbox table.
  • Failures arrive as callbacks too, with X-Pdfvector-Callback-Failed: true and a body of message, code and (when available) requestId.
  • Have a sweeper. If a job sits in waiting_callback far longer than its size justifies, mark it for manual review or resubmit it, accepting that a resubmit may bill again if the first run actually completed.

Stage 4: validate

An extraction can be well-formed and still wrong. Validate in two layers before anything reaches your product's tables.

Layer 1, shape. Check data against the same JSON Schema you sent. Ajv does this in a few lines:

import Ajv from "ajv";

const ajv = new Ajv({ allErrors: true });
const validateInvoice = ajv.compile(INVOICE_SCHEMA); // the same schema object you send to the API

export function checkShape(data: unknown): string[] {
  return validateInvoice(data)
    ? []
    : (validateInvoice.errors ?? []).map((e) => `${e.instancePath || "/"} ${e.message}`);
}

Layer 2, business rules. These catch the errors that matter:

  • Invoices: line items sum to the subtotal; subtotal plus tax equals total; due date on or after the invoice date; no duplicate of vendor plus invoice number for the tenant.
  • Bank statements: opening balance plus credits minus debits equals the closing balance; transaction dates inside the statement period.
  • Identity documents: expiry date in the future; the name matches the account holder within your tolerance.

Decide per rule what a failure does: retry on a higher tier (cheap, often fixes scans), send to a review queue in your app, or reject back to the user. The invoice validation guide and the bank statement guide have complete rule sets.

Stage 5: store and notify

Store more than the extracted fields:

KeepWhy
Extracted data and schema_versionThe product's source of truth, tied to the shape it was extracted with
Parsed markdown (and pages if requested)Search, RAG, re-extraction later without another parse
model, credits, pageCount, requestIdCost attribution, debugging, support tickets
warnings from parse responsesBest-effort accuracy notes worth surfacing to reviewers
Validation results and who approved overridesAudit trail

Then publish an internal event (document.processed, document.needs_review) so the UI, search indexer and customer-facing webhooks react without knowing anything about parsing.

Cost control by tier

Credits are charged per page, and the tier sets the rate:

APInanominipromax
Document Parse1248
Document Ask / Extract24816
Invoice / Identity / Bank Statement Parse––610
Invoice / Identity / Bank Statement Ask / Extract6101418

Pages are counted per PDF or TIFF page, per slide for PowerPoint, one per image, and per 3,000 characters for Word, Excel, CSV, HTML and text files.

Policies that keep the bill predictable:

  • Default to auto. It picks a tier per document, bills the tier it ran, and bills at most mini when a text PDF or Office file is read without OCR.
  • Start cheap where validation is strong. Invoices and statements have arithmetic checks, so you can run nano or mini first and escalate only the documents that fail. Documents without a built-in checksum (contracts, applications) deserve a higher default tier.
  • Parse once, extract many. If several features need different fields from the same document, store the Markdown and decide whether a second extraction is worth its per-page cost.

A worked month for one product: 1,000 invoices averaging 2 pages through Invoice Extract on mini cost 1,000 × 2 × 10 = 20,000 credits. If 5% fail validation and are re-run on max, that adds 50 × 2 × 18 = 1,800 credits. Parsing the same 2,000 pages for search on auto, where they are text PDFs billed at mini rates, adds 2,000 × 2 = 4,000 credits. Total: 25,800 credits, which fits the Pro plan ($97 per month for 100,000 credits). See pricing for all plans.

Multi-tenant attribution

  • Encode the tenant in documentId. tenantId:documentId (up to 512 characters) makes every usage record and every response traceable to a customer.
  • Meter from responses. Every successful response includes credits. Write it to a per-tenant ledger at the moment you store the result; that ledger drives usage-based pricing, plan limits inside your product, and margin reports.
  • Enforce budgets before calling the API. Check the tenant's remaining allowance in the gateway, using pageCount estimates from your own pre-check, so one customer can't drain the shared credit pool.
  • Separate keys per environment. Staging and production should never share an API key or a credit balance.
  • Data residency. The shared instance runs in the US. Enterprise plans add dedicated instances in the UK, EU, US, Japan, Australia or Asia Pacific; the gateway can route each tenant to the instance in its region by switching the base URL.

Build or buy the processing layer

You could run your own OCR, layout analysis, table reconstruction and LLM extraction. The architecture above does not change if you do; only the process stage does. The questions are whether you want to maintain model hosting, per-format converters and OCR quality yourself, and whether your volume justifies it. If you need things this API does not offer, such as bounding boxes for every value, on-premises deployment or a built-in human review UI, compare options on the comparison pages before you commit.

FAQ

Does documentId make requests idempotent?

No. It labels a request for usage attribution and is echoed in the response. Idempotency belongs in your job table, for example a unique key on document, operation and schema version.

Should I use synchronous calls or callbacks?

Synchronous calls from a background worker are simplest for typical documents. Use callback for long documents or when your infrastructure cannot hold a connection open for the processing time.

How do I secure the callback endpoint?

Put an unguessable per-job token in the callback URL, reject unknown tokens, accept only the first callback per job, and process the payload asynchronously after returning a 2xx.

Which errors should be retried?

Retry 429 (after retryAfterSeconds), 5xx, network errors and anything with retryable: true. Retry on a higher tier when retryableWithHigherModel is true. Do not retry user errors or 402.

Can each tenant have its own credit balance?

Credits belong to your PDF Vector account. Track per-tenant usage yourself from the credits field in each response, keyed by the documentId you send.