Skip to content

Menu

Tutorials

Durable LLM Jobs with Inngest: Steps and Retries

AIDToolStack EditorialNovember 30, 20266 min read
InngestBackground jobsNext.jsTypeScript
Share:Twitter

Generating a long report with an LLM inside an HTTP request handler works right up until it doesn't. The model takes 90 seconds, the platform kills the request at 60, the user clicks again, and now you're paying for two half-finished reports. Or the provider returns a 529 on the third of five calls and the first two calls' work is lost.

The fix is to move the job into a background function that's durable: broken into steps, each step's result saved, failed steps retried on their own. Inngest is one way to get that without running your own queue workers. This post builds a report job in a Next.js App Router project with the Inngest TypeScript SDK, following the Inngest docs as of November 2026. (I picked Inngest over Trigger.dev, which solves the same problem and is covered in our post on background jobs in Node.js.)

Set up the client and the dev server

From the Next.js quick start:

npm install inngest

Create a client in src/inngest/client.ts:

import { Inngest } from "inngest";

export const inngest = new Inngest({ id: "my-app" });

Then run the app and Inngest's local Dev Server side by side. The quick start uses the v4 SDK and starts the app with INNGEST_DEV=1 so it talks to the local server:

INNGEST_DEV=1 npm run dev
npx inngest-cli@latest dev

The Dev Server UI is at http://localhost:8288. You'll use it constantly: every run, every step, every retry shows up there.

Expose the functions to Inngest

Inngest calls your functions over HTTP, so you mount a handler. In src/app/api/inngest/route.ts:

import { serve } from "inngest/next";
import { inngest } from "@/inngest/client";
import { generateReport } from "@/inngest/functions";

export const { GET, POST, PUT } = serve({
  client: inngest,
  functions: [generateReport],
});

This is the part that makes it feel different from a queue library. There's no worker process to deploy; the work runs in your app's route, and Inngest calls it.

Write the job as steps

Here's the report function. The shape of createFunction follows the v4 signature from the retries docs: id, triggers and retries go in the first argument.

import { NonRetriableError } from "inngest";
import OpenAI from "openai";
import { inngest } from "./client";
import { db } from "@/lib/db";

const openai = new OpenAI();

export const generateReport = inngest.createFunction(
  {
    id: "generate-report",
    triggers: { event: "app/report.requested" },
    retries: 4,
  },
  async ({ event, step }) => {
    const input = await step.run("fetch-input", async () => {
      const doc = await db.document.findUnique({ where: { id: event.data.documentId } });
      if (!doc) throw new NonRetriableError("Document not found");
      return { text: doc.text };
    });

    const summary = await step.run("call-llm", async () => {
      const res = await openai.chat.completions.create({
        model: process.env.MODEL!,
        messages: [
          { role: "system", content: "Summarise the document as a short report." },
          { role: "user", content: input.text },
        ],
      });
      return res.choices[0].message.content ?? "";
    });

    await step.run("save-result", async () => {
      await db.report.upsert({
        where: { documentId: event.data.documentId },
        create: { documentId: event.data.documentId, body: summary },
        update: { body: summary },
      });
    });

    return { ok: true };
  }
);
Diagram: an app/report.requested event starts the function; step fetch-input is saved, step call-llm is retried on error, and step save-result runs once the earlier steps are done
Diagram: an app/report.requested event starts the function; step fetch-input is saved, step call-llm is retried on error, and step save-result runs once the earlier steps are done

What actually happens when the model call fails

This is the whole point, so here's what the retries page says:

  • The default is four retries after the initial attempt; retries sets it per function, and in the v4 TypeScript SDK valid values are 0 to 20. retries: 0 turns retries off.
  • Each step.run() has its own retry counter. If fetch-input succeeded and call-llm failed, Inngest reuses the saved result of fetch-input and retries only call-llm.
  • Retries use backoff with jitter by default.
  • Your handler receives a zero-indexed attempt that counts retries and resets after a successful step.

So a flaky provider costs you a retried LLM call, not a re-run of the whole pipeline. For a job with five LLM calls in a row, that's the difference between paying for one extra call and paying for up to five.

Return values are what get saved, which has a consequence: return plain, serialisable data from a step (strings, numbers, plain objects), not class instances or database handles.

Tell Inngest which errors are worth retrying

Not every failure should retry. The errors reference gives you two tools:

SituationThrowEffect
Network blip, 5xx from the providera normal Errorretried with backoff
Bad input, missing recordNonRetriableErrorno more retries
Provider says "try again in 30s"RetryAfterErrorretried after that delay

NonRetriableError is imported from "inngest" and takes an optional cause so the original error shows in the logs. RetryAfterError takes the delay as milliseconds, a string like "30m", or a Date. That fits LLM rate limits well: if the provider's error tells you when to retry, pass that through instead of guessing.

In the function above, a missing document throws NonRetriableError. Retrying four times won't make the row appear.

For the rate-limit case, wrap the model call and translate the provider's hint. The exact error shape depends on your provider SDK, so treat retryAfterMs below as a placeholder for however yours reports it:

import { RetryAfterError } from "inngest";

const summary = await step.run("call-llm", async () => {
  try {
    return await callModel(input.text);
  } catch (err) {
    const retryAfterMs = getRetryAfterMs(err); // your provider-specific helper
    if (retryAfterMs) {
      throw new RetryAfterError("LLM rate limited", retryAfterMs);
    }
    throw err; // anything else: normal retry with backoff
  }
});

The attempt value is useful here too. Because it starts at 0 and counts up on each retry, you can log it with every model call, or switch to a cheaper fallback model on the last attempt instead of failing outright. Whether that's acceptable depends on the report; for some jobs a worse answer is better than none, for others it isn't.

Watch a failure on purpose

Before trusting any of this, break it. Point MODEL at a name that doesn't exist, send the event, and open the Dev Server at http://localhost:8288. You should see fetch-input complete once and call-llm fail and retry while the earlier step stays done. Then fix the model name and confirm a fresh run goes through all three steps. Ten minutes of this tells you more about the retry behaviour than any amount of reading.

Kick it off from your app

From a route handler or server action, send the event and return straight away:

await inngest.send({
  name: "app/report.requested",
  data: { documentId: "doc_123" },
});

The user gets an immediate response ("your report is being generated"), and your UI polls or subscribes for the saved result. Nothing about the LLM's latency touches the request anymore.

Gotchas

  • Make side-effecting steps idempotent. The retries page recommends using the same idempotency key on every attempt, so a retry after a lost response doesn't write twice. The upsert keyed on documentId above is the cheap version of that.
  • Keep billable work inside named steps. The retries page notes that an error thrown outside a named step can also trigger a function retry, so a model call sitting outside step.run loses the per-step protection.
  • Retries cost tokens. A step that fails after the model responded (say, your JSON parse throws) re-runs the model call. Parse and validate in a separate step from the call if the call is expensive.

When this is overkill

If a job finishes in a few seconds and losing it occasionally is fine, a plain async call is simpler. Reach for durable steps when a job runs longer than your request timeout, makes several paid calls in a row, or must not silently disappear. If the job is really a schedule rather than a reaction to user actions, our cron best practices post covers the scheduling traps.

AE

Written by AIDToolStack Editorial

Researched from official documentation, specifications and vendor pages, listed under Sources below. Last checked November 2026.

Sources

  1. inngest.com /docs/getting-started/nextjs-quick-start
  2. inngest.com /docs/features/inngest-functions/error-retries/retries
  3. inngest.com /docs/reference/typescript/functions/errors

Related Posts

Reviews and commentsShow

Reviews

Sign in to leave a review.

Loading reviews…

Comments

Sign in to leave a comment.

Loading comments…