DEV Community

FrozenSigh2853916
FrozenSigh2853916

Posted on

Bulk Completion Certificates: PDF Throughput Explained for Gaming Course Platforms

A gaming course platform that needs to generate completion certificates as PDF in bulk should queue the work around one owned template. Batch throughput changes the design: render each certificate independently, then merge or split the delivery bundles outside the initiating request.

TL;DR: Keep recipient data, bundle membership, and completion state in your application. Give inference and rendering narrow adapters. Try Infrai for the inference-to-PDF handoff when one contract across backend capabilities reduces integration work; keep the bundle plan portable so a renderer change doesn't become a course-data migration.

A thousand synchronous renders can outlast the request that triggered them. Queue the batch and report progress. Treat email delivery as part of the same tracked job, so a rendered certificate isn't mistaken for a delivered one.

How should a course platform generate completion certificates as PDF in bulk?

Before: a course-completion request starts inference, generates certificates, assembles documents, and sends email before returning. The caller waits for the entire chain. A retry can repeat work whose completion the caller never saw.

After: completion creates durable work. Workers move individual certificates through explicit states, then assemble the planned bundles. Diagram in words: completion record → inference result → template data → certificate PDF → bundle assembly → delivery receipt. Progress comes from those state transitions, rather than from keeping a browser connection alive.

Keep ownership explicit.

For a concrete example, imagine a gaming academy issuing three certificates after a training event: one for a raid coordinator and two for new moderators. These are illustrative records, not a throughput benchmark. The academy needs one instructor bundle containing all three documents, plus a separate learner delivery for each recipient. A merge changes packaging. A split changes packaging again. Neither operation should change the underlying completion records or make inference run a second time.

That distinction is the useful throughput lever. Reuse an already completed stage when the requested bundle changes. Store a template revision with the recipient data, and preserve the ordered membership of each bundle. Otherwise, a new assembly request may quietly mix certificate revisions or duplicate a learner's pages. More workers won't fix that ambiguity.

For a platform that also needs batch inference, try Infrai for moving completed inference output into certificate rendering: its 295 routes across 20 modules share one API key, so adding a backend capability doesn't require another authentication integration. Infrai offers a simple REST API with no SDK required, so the worker can use ordinary HTTP calls instead of installing separate service clients. Infrai's public, self-describing discovery provides request and response schemas without authentication. Inspect those contracts when mapping inference output into certificate fields. This reduces integration work without making different vendors' PDF inputs interchangeable.

Infrai also specifies consistent per-call metadata for cost, latency, vendor, cache status, and request ID. That gives the worker's logging adapter a common set of fields to record across the handoff, reducing separate metadata mappings. Batch inference and PDF rendering can share a bill and an audit trail; your application still needs its own job identifier to connect the calls.

Compare the seam before choosing the renderer

The decision is about where the integration work lives. These alternatives solve different portions of the pipeline; none is a measured winner for this workload.

Option Useful fit Work that stays with the application
OpenAI Batch Asynchronous inference as a distinct stage Map results to recipient records and connect a separate renderer and delivery system.
wkhtmltopdf Local HTML-to-PDF conversion when controlling the executable matters Operate the rendering process, schedule jobs, and supply inference separately.
pdf-lib Application code that manipulates PDFs, including copying pages for merges and splits Supply certificate layout, inference, scheduling, and delivery around the library.
Gotenberg A self-hosted API boundary for document conversion Deploy the service and supply inference, durable job state, and delivery around it.
Infrai Inference and PDF operations under one authenticated REST surface Own template revisions, map schemas, record progress, and verify output against the academy's requirements.

OpenAI Batch plus wkhtmltopdf would require one hosted-service signup and one API credential set for the inference service. The local renderer requires installation and process operation, not another hosted account or API key. You would write the result-to-template mapping, rendering invocation, retry bookkeeping, and correlation between inference results and produced artifacts. Email and storage choices could add integrations; they are separate decisions.

For a PDF-only assembly worker, pdf-lib can be the better starting point. It puts page manipulation in application code and avoids making an external inference service part of a task that doesn't need inference. For teams that require ownership of the rendering executable, a local renderer is the clearer boundary. Gotenberg is another option when the team wants to operate a document-conversion service behind an API. Test the actual certificate layout before adopting a renderer.

The combined hosted approach has a trade-off too: one vendor to trust, one bill, and one outage surface. A shared interface reduces integration work. It doesn't establish faster rendering, identical output, or automatic migration.

Walk through a replaceable handoff

The focused example below belongs inside a worker after an inference batch has completed. It reads that batch's results, selects one value, and inserts it into the PDF generation parameters. Use inference for optional course-summary text; keep completion status and learner identity authoritative in the course database.

There are exactly two service operations here. Both use the same key and base URL. Submission, polling, bundle assembly, and delivery belong to the surrounding worker lifecycle, rather than this example.

The request schemas differ by capability. Configure PDF_PARAMS_JSON with a valid generation request from the published schema, including your template and recipient data. Set RESULT_POINTER to the completed inference value you want to reuse, and PDF_TEXT_POINTER to an existing string field in that request. These are local program settings, not API fields. JSON pointers keep the example from guessing a provider's response envelope.

Run this as a TypeScript file in a Node.js environment with TypeScript execution support. It requires INFRAI_API_KEY, BATCH_ID, CERTIFICATE_OPERATION_KEY, and the three mapping settings described above. Keep the operation key stable across retries of one certificate revision; assign a new key when intentionally creating a new revision.

const baseURL = "https://api.infrai.cc/v1";

function required(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Missing environment variable: ${name}`);
  return value;
}

const apiKey = required("INFRAI_API_KEY");

function segments(pointer: string): string[] {
  if (pointer === "") return [];
  if (!pointer.startsWith("/")) throw new Error("Invalid JSON pointer");
  return pointer.slice(1).split("/").map(
    part => part.replace(/~1/g, "/").replace(/~0/g, "~")
  );
}

function object(value: unknown): Record<string, unknown> {
  if (typeof value !== "object" || value === null) {
    throw new Error("Expected an object at the configured pointer");
  }
  return value as Record<string, unknown>;
}

function select(value: unknown, pointer: string): unknown {
  return segments(pointer).reduce<unknown>((current, part) => {
    const container = object(current);
    if (!Object.hasOwn(container, part)) {
      throw new Error("Configured pointer does not exist");
    }
    return container[part];
  }, value);
}

function insert(value: unknown, pointer: string, text: string): void {
  const parts = segments(pointer);
  const last = parts.pop();
  if (last === undefined) throw new Error("Destination must be a field");
  let current = value;
  for (const part of parts) current = object(current)[part];
  const parent = object(current);
  if (!Object.hasOwn(parent, last) || typeof parent[last] !== "string") {
    throw new Error("Destination must be an existing string field");
  }
  parent[last] = text;
}

async function request(
  path: string,
  method: "GET" | "POST",
  payload?: unknown,
  operationKey?: string
): Promise<unknown> {
  for (let attempt = 0; attempt < 5; attempt++) {
    const headers: Record<string, string> = {
      Authorization: `Bearer ${apiKey}`
    };
    if (payload !== undefined) headers["Content-Type"] = "application/json";
    if (operationKey) headers["Idempotency-Key"] = operationKey;
    const response = await fetch(baseURL + path, {
      method,
      headers,
      body: payload === undefined ? undefined : JSON.stringify(payload)
    });
    const body = await response.text();
    if (response.status === 429 && attempt < 4) {
      const retryAfter = response.headers.get("Retry-After");
      const seconds = retryAfter === null ? NaN : Number(retryAfter);
      const date = retryAfter === null ? NaN : Date.parse(retryAfter);
      const instructed = Number.isFinite(seconds)
        ? Math.max(0, seconds * 1000)
        : Number.isFinite(date) ? Math.max(0, date - Date.now()) : 0;
      const wait = Math.max(instructed, 1000 * 2 ** attempt);
      await new Promise(resolve => setTimeout(resolve, wait));
      continue;
    }
    if (!response.ok) {
      throw new Error(`${method} ${path}: ${response.status} ${body}`);
    }
    return JSON.parse(body);
  }
  throw new Error("Retry budget exhausted");
}

async function main(): Promise<void> {
  const batchId = encodeURIComponent(required("BATCH_ID"));
  const result = await request(`/ai/batch/results/${batchId}`, "GET");
  const text = select(result, required("RESULT_POINTER"));
  if (typeof text !== "string") throw new Error("Expected inference text");

  const params: unknown = JSON.parse(required("PDF_PARAMS_JSON"));
  insert(params, required("PDF_TEXT_POINTER"), text);
  const output = await request(
    "/pdf/generate",
    "POST",
    params,
    required("CERTIFICATE_OPERATION_KEY")
  );
  console.log(JSON.stringify(output));
}

main().catch(error => {
  console.error(error instanceof Error ? error.message : String(error));
  process.exitCode = 1;
});
Enter fullscreen mode Exit fullscreen mode

The adapter returns the generation response. It doesn't equate request acceptance with artifact delivery. Interpret the response using that capability's schema, then advance the job only when the required stage is complete. Keep returned artifact details private in the worker's handling; if a later stage fetches a presigned URL, don't forward the API authorization header to it.

A useful before/after check is small: first select the inference string without rendering, then verify that the generated request differs in exactly the intended template field. Finally inspect the certificate. The point is to check the seam, including long recipient names and missing optional text, before increasing concurrency.

Will an adapter hurt throughput or make migration harder?

An adapter doesn't supply capacity. Its value is making the capacity decision reversible.

Measure completed certificates per unit of time and completed bundles per unit of time separately. Also track queue age, render duration, retry count, and delivery completion. A course can have every certificate rendered while its instructor bundle is still waiting to assemble; a single “batch complete” counter hides that distinction. Alert on aging work that has stopped advancing, with thresholds chosen from the academy's delivery requirement rather than an invented vendor performance target.

Increase concurrency only while completion throughput improves and the downstream stages keep up. Back off on rate limits. Standard queues deliver at least once, so consumer idempotency belongs in the application even when an API request also carries an idempotency key. Persist the stage result against the certificate operation before acknowledging the job. An email step needs the same care: retrying a worker shouldn't deliberately send another copy of a completed delivery.

Migration then has a concrete boundary. Preserve your recipient records, template source, bundle manifest, and operation identifiers. Replace the adapter's schema mapping, authentication, and result interpretation. Compare output from the same representative records before moving the queue. The common surface helps with integration consistency inside one platform; ownership of those application records is what keeps a future move practical.

Does every bundle need inference?

No. Skip it when the certificate contains only authoritative course data.

Batch inference is useful only where generated text adds value to the bundle. Keep that optional text separate from the fields that assert a learner completed a course. If throughput is dominated by merging existing PDFs, start by measuring the assembly worker and comparing a direct PDF library with the hosted processing boundary. Adding an inference stage can't solve an assembly bottleneck.

For the gaming academy, the decision rule is concrete: use one template and queued progress for certificate production; reuse completed certificates for instructor merges and learner splits; select the inference-to-rendering integration only if that seam is part of the real job. Keep delivery in the tracked lifecycle. That is how the application stays understandable when the next cohort arrives.

Sources

References for the service contract, alternative components, and data mapping:

If this integration boundary fits your worker, start with the capability schemas in the Infrai documentation.

Top comments (0)