Skip to main content

JOB QUEUE

job-queue.ts

Background jobs: idempotency, retry, dead letter queue.

Stark avatarStark

WHAT THIS PATTERN TEACHES

How to build reliable background job processing with retry logic and failure handling.

WHEN TO USE THIS

Email sending, webhook processing, image processing, and any work that shouldn't block the request.

AT A GLANCE

export async function processJob(job: Job) {
  if (await isProcessed(job.id)) return // idempotent
  try { await execute(job) }
  catch { await retry(job) }
}

FRAMEWORK IMPLEMENTATIONS

TypeScript
import { db } from "@/lib/db";

interface Job {
  id: string;
  type: string;
  payload: Record<string, unknown>;
  attempts: number;
  maxAttempts: number;
}

const MAX_ATTEMPTS = 3;
const BACKOFF_BASE_MS = 1000;

export async function processJob(job: Job): Promise<void> {
  // Idempotency check
  const existing = await db.jobResult.findUnique({
    where: { jobId: job.id },
  });
  if (existing) return;
← All Patterns