← Back to the journal

Why Your API Can Return Success Even When a Background Job Fails

An HTTP success response is not necessarily a successful business operation. Here is how to design asynchronous APIs that tell the difference.

On this page

Why Your API Can Return Success Even When a Background Job Fails

Reading position1 / 14
Editorial illustration for Why Your API Can Return Success Even When a Background Job Fails
AI-generated editorial illustration

Imagine clicking Export report in an analytics dashboard. The application immediately displays a green notification: “Report generated successfully.”

Five minutes later, there is still no report. Somewhere on the server, a background worker has failed to connect to the database. Its final retry has already been exhausted.

The frontend saw a successful HTTP response. The backend successfully submitted a job. The worker failed to produce the report.

All three observations can be true at the same time.

This is a surprisingly easy mistake to make when moving expensive work out of an HTTP request and into a background queue. The queue improves responsiveness, but it also changes what the API can truthfully promise its callers.

Let's build an asynchronous report export API with Node.js, Fastify, BullMQ and Redis, and examine the design decisions that make the difference between accepting work and actually completing it.

1. A successful API request does not mean the job succeeded

Consider this Fastify route:

app.post('/reports', async (request, reply) => {
  await reportQueue.add('generate-report', {
    userId: request.user.id
  });

  return reply.send({
    success: true,
    message: 'Report generated successfully'
  });
});

The route awaits queue.add(), not the report generation itself. The promise resolves when the enqueue operation succeeds. The worker may not have started yet.

There is nothing inherently wrong with returning an HTTP success status here. The problem is the meaning of the response body: it describes a report that does not exist yet.

Removing the await is even worse. The server could acknowledge a request before discovering that Redis is unreachable and the enqueue operation failed.

There are at least three distinct milestones:

MilestoneWhat has happened
AcceptedThe service has recorded or queued the request
ProcessingA worker is attempting the operation
CompletedThe promised business result is available

A job can also fail, retry or remain queued for longer than expected. A healthy HTTP server is not proof that the worker fleet is healthy.

Article illustration
SVG source
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 760 270" width="760" height="270" role="img" aria-label="Two independent lifecycles">
<rect x="0" y="0" width="760" height="270" rx="7" fill="#f6f4ee"/><text x="24" y="34" font-family="Arial, sans-serif" font-size="20" fill="#242b25" text-anchor="start" font-weight="600">Two independent lifecycles</text>
<rect x="24" y="65" width="170" height="50" rx="7" fill="#fffef9" stroke="#d9ddd2"/><text x="109.0" y="95.0" font-family="Arial, sans-serif" font-size="15" fill="#242b25" text-anchor="middle" font-weight="600">POST /reports</text><line x1="194" y1="90" x2="280" y2="90" stroke="#6d7268" stroke-width="1.5"/><polygon points="280,90 271.00,94.00 271.00,86.00" fill="#6d7268"/><rect x="280" y="65" width="190" height="50" rx="7" fill="#e6eadd" stroke="#d9ddd2"/><text x="375.0" y="95.0" font-family="Arial, sans-serif" font-size="15" fill="#242b25" text-anchor="middle" font-weight="600">Job accepted</text><line x1="470" y1="90" x2="550" y2="90" stroke="#6d7268" stroke-width="1.5"/><polygon points="550,90 541.00,94.00 541.00,86.00" fill="#6d7268"/><rect x="550" y="65" width="186" height="50" rx="7" fill="#e6eadd" stroke="#d9ddd2"/><text x="643.0" y="95.0" font-family="Arial, sans-serif" font-size="15" fill="#242b25" text-anchor="middle" font-weight="600">HTTP 202</text><line x1="375" y1="115" x2="375" y2="158" stroke="#6d7268" stroke-width="1.5"/><polygon points="375,158 371.00,149.00 379.00,149.00" fill="#6d7268"/><rect x="280" y="158" width="190" height="50" rx="7" fill="#fffef9" stroke="#d9ddd2"/><text x="375.0" y="188.0" font-family="Arial, sans-serif" font-size="15" fill="#242b25" text-anchor="middle" font-weight="600">Worker runs</text><line x1="470" y1="183" x2="550" y2="183" stroke="#ab4932" stroke-width="1.5"/><polygon points="550,183 541.00,187.00 541.00,179.00" fill="#ab4932"/><rect x="550" y="158" width="186" height="50" rx="7" fill="#fffef9" stroke="#ab4932"/><text x="643.0" y="188.0" font-family="Arial, sans-serif" font-size="15" fill="#242b25" text-anchor="middle" font-weight="600">Job fails</text><text x="380" y="245" font-family="Arial, sans-serif" font-size="15" fill="#6d7268" text-anchor="middle">Acceptance and completion are different outcomes.</text>
</svg>
Download SVG

Caption: The HTTP response and the background job have independent lifecycles. A successful submission can be followed by a failed operation.

The distinction matters for more than reports. It applies to sending emails, generating invoices, processing uploaded files, importing CSV records and synchronising data with external services.

2. Return an honest HTTP response: 202 Accepted

HTTP already has a status code for this situation. RFC 9110, section 15.3.3, defines 202 Accepted for requests accepted for processing whose work has not finished. It also recommends providing information about how to monitor the operation [1].

A response could look like this:

HTTP/1.1 202 Accepted
Location: /reports/jobs/7b8e2f
Retry-After: 2
Cache-Control: no-store
Content-Type: application/json

{
  "jobId": "7b8e2f",
  "status": "accepted",
  "statusUrl": "/reports/jobs/7b8e2f"
}

The Location header identifies the status resource. Here, Retry-After is a polling hint in seconds, following the asynchronous request-reply pattern described in Microsoft's architecture documentation [2]. Clients need to implement that convention; a browser will not automatically poll simply because it receives these headers.

accepted describes the submission, not necessarily the worker's current state. A fast worker could already have completed the job before the client receives this response.

Should we always use 202?

Not necessarily. A 201 Created response can be appropriate when the requested resource is the operation record itself and that record has already been created. A 200 OK response may also be valid if the documented contract only promises submission.

But if the caller asks for a report that will be produced later, 202 makes the deferred nature of that operation particularly clear.

The important part is the contract, not merely the status code.

A more useful submission endpoint

The following examples are parts of an application rather than a complete runnable server. Assume an authenticated Fastify plugin supplies request.user.id, input validation is configured, and the API and worker share a Redis-backed queue. The report storage adapter introduced below is application-specific.

// queue.js
import { Queue } from 'bullmq';

export const connection = {
  host: process.env.REDIS_HOST ?? '127.0.0.1',
  port: Number(process.env.REDIS_PORT ?? 6379),
  maxRetriesPerRequest: 1,
  enableOfflineQueue: false
};

export const reportQueue = new Queue('reports', {
  connection
});

For a request-facing producer, failing promptly when Redis is unavailable is usually preferable to waiting indefinitely. Connection retry settings alone are not a guaranteed end-to-end deadline; configure and monitor the complete request path. Workers need a separate connection policy suitable for long-running background processing.

// routes.js
import { randomUUID } from 'node:crypto';
import { reportQueue } from './queue.js';

export function registerReportRoutes(app) {
  app.post('/reports', async (request, reply) => {
    const jobId = randomUUID();

    try {
      await reportQueue.add('generate-report', {
        userId: request.user.id
      }, {
        jobId,
        attempts: 3,
        backoff: {
          type: 'exponential',
          delay: 1000
        },
        removeOnComplete: { age: 86400, count: 10000 },
        removeOnFail: { age: 604800, count: 10000 }
      });
    } catch (error) {
      request.log.error({ err: error, jobId }, 'Enqueue failed');

      return reply.code(503).send({
        message: 'Unable to confirm report submission'
      });
    }

    const statusUrl = `/reports/jobs/${jobId}`;

    return reply.code(202)
      .header('Location', statusUrl)
      .header('Retry-After', '2')
      .header('Cache-Control', 'no-store')
      .send({ jobId, status: 'accepted', statusUrl });
  });
}

Notice the wording of the error: unable to confirm submission. A network failure can occur after Redis has accepted a command but before the producer receives its acknowledgement. A 503 is therefore not definitive proof that no job exists.

The random ID in this first example is deliberately simple. If the client retries the POST after losing the response, a new UUID could create another export. We will address that later.

3. A retry is not the same thing as a permanent failure

Suppose the report worker cannot read from the database on its first attempt. BullMQ can retry failed jobs according to their configured attempts and backoff [3].

If we immediately display “Report failed” after the first exception, we may mislead the user again. A second attempt could succeed a few seconds later.

We need to distinguish an unsuccessful attempt from a terminal job failure.

// worker.js
import { Worker } from 'bullmq';
import { generateAndStoreReport } from './report-service.js';

const worker = new Worker('reports', async job => {
  await job.updateProgress(10);

  // Application-specific adapter. It must be safe to repeat
  // the same operation after a crash or retry.
  const report = await generateAndStoreReport({
    userId: job.data.userId,
    operationId: job.id
  });

  await job.updateProgress(100);

  return { reportId: report.id };
}, {
  connection: {
    host: process.env.REDIS_HOST ?? '127.0.0.1',
    port: Number(process.env.REDIS_PORT ?? 6379),
    maxRetriesPerRequest: null
  },
  concurrency: 4
});

worker.on('error', error => {
  console.error('Worker infrastructure error:', error);
});

The report service is intentionally left as an integration point: it must store the report durably, associate it with its owner, and reuse or safely replace the result for the same operation ID. Returning an ID is not enough if the underlying file is only stored on an ephemeral container filesystem.

There is another small trap here. A progress value of 100 is not itself proof that BullMQ has recorded the completed state. The worker could crash between the progress update and completion. Treat progress as an indication, not an authoritative success signal.

Give the client a stable vocabulary

BullMQ statePublic API state
waiting, prioritized, waiting-childrenqueued
activeprocessing
delayedscheduled
completedsucceeded
failedfailed
unknownunavailable

A delayed job may be waiting for a retry or simply scheduled for later. Do not infer the exact reason from delayed alone.

Article illustration
SVG source
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 760 300" width="760" height="300" role="img" aria-label="Background job lifecycle">
<rect x="0" y="0" width="760" height="300" rx="7" fill="#f6f4ee"/><text x="24" y="34" font-family="Arial, sans-serif" font-size="20" fill="#242b25" text-anchor="start" font-weight="600">Background job lifecycle</text>
<rect x="24" y="85" width="140" height="52" rx="7" fill="#fffef9" stroke="#d9ddd2"/><text x="94.0" y="116.0" font-family="Arial, sans-serif" font-size="15" fill="#242b25" text-anchor="middle" font-weight="600">Queued</text><line x1="164" y1="111" x2="230" y2="111" stroke="#6d7268" stroke-width="1.5"/><polygon points="230,111 221.00,115.00 221.00,107.00" fill="#6d7268"/><rect x="230" y="85" width="160" height="52" rx="7" fill="#e6eadd" stroke="#d9ddd2"/><text x="310.0" y="116.0" font-family="Arial, sans-serif" font-size="15" fill="#242b25" text-anchor="middle" font-weight="600">Processing</text><line x1="390" y1="111" x2="540" y2="111" stroke="#6d7268" stroke-width="1.5"/><polygon points="540,111 531.00,115.00 531.00,107.00" fill="#6d7268"/><rect x="540" y="85" width="196" height="52" rx="7" fill="#e6eadd" stroke="#d9ddd2"/><text x="638.0" y="116.0" font-family="Arial, sans-serif" font-size="15" fill="#242b25" text-anchor="middle" font-weight="600">Succeeded</text><line x1="310" y1="137" x2="310" y2="194" stroke="#ab4932" stroke-width="1.5"/><polygon points="310,194 306.00,185.00 314.00,185.00" fill="#ab4932"/><rect x="230" y="194" width="160" height="52" rx="7" fill="#fffef9" stroke="#ab4932"/><text x="310.0" y="225.0" font-family="Arial, sans-serif" font-size="15" fill="#242b25" text-anchor="middle" font-weight="600">Attempt fails</text><line x1="390" y1="220" x2="540" y2="220" stroke="#ab4932" stroke-width="1.5"/><polygon points="540,220 531.00,224.00 531.00,216.00" fill="#ab4932"/><rect x="540" y="194" width="196" height="52" rx="7" fill="#fffef9" stroke="#ab4932"/><text x="638.0" y="225.0" font-family="Arial, sans-serif" font-size="15" fill="#242b25" text-anchor="middle" font-weight="600">Failed</text><text x="465" y="210" font-family="Arial, sans-serif" font-size="12" fill="#ab4932" text-anchor="middle">Exhausted</text><line x1="230" y1="220" x2="94" y2="220" stroke="#6d7268" stroke-width="1.5"/><polygon points="94,220 103.00,216.00 103.00,224.00" fill="#6d7268"/><rect x="24" y="194" width="140" height="52" rx="7" fill="#fffef9" stroke="#d9ddd2"/><text x="94.0" y="225.0" font-family="Arial, sans-serif" font-size="15" fill="#242b25" text-anchor="middle" font-weight="600">Scheduled</text><line x1="94" y1="194" x2="94" y2="137" stroke="#6d7268" stroke-width="1.5"/><polygon points="94,137 98.00,146.00 90.00,146.00" fill="#6d7268"/><text x="160" y="210" font-family="Arial, sans-serif" font-size="12" fill="#6d7268" text-anchor="middle">Retry</text><text x="380" y="278" font-family="Arial, sans-serif" font-size="14" fill="#6d7268" text-anchor="middle">An attempt failure is not necessarily a terminal failure.</text>
</svg>
Download SVG

Caption: An unsuccessful attempt may lead to another scheduled attempt. Only a terminal outcome should be presented as a final result.

4. Build a status endpoint, not a guessing mechanism

Once the API returns a job identifier, the client needs somewhere to retrieve its outcome.

For short-lived operations, we can read the job directly from BullMQ:

const publicStates = {
  waiting: 'queued',
  prioritized: 'queued',
  'waiting-children': 'queued',
  active: 'processing',
  delayed: 'scheduled',
  completed: 'succeeded',
  failed: 'failed',
  unknown: 'unavailable'
};

app.get('/reports/jobs/:jobId', async (request, reply) => {
  const { jobId } = request.params;
  reply.header('Cache-Control', 'no-store');

  const job = await reportQueue.getJob(jobId);

  // Never expose another user's job merely because
  // the caller knows its identifier.
  if (!job || job.data.userId !== request.user.id) {
    return reply.code(404).send({
      message: 'Operation not found'
    });
  }

  const state = await job.getState();
  const status = publicStates[state] ?? 'unavailable';

  if (status === 'unavailable') {
    return reply.code(503).send({
      message: 'Operation status temporarily unavailable'
    });
  }

  if (status === 'succeeded') {
    // Reload after checking state, because the original
    // Job object may predate the completion transition.
    const completedJob = await reportQueue.getJob(jobId);

    if (!completedJob || !completedJob.returnvalue?.reportId) {
      return reply.code(503).send({
        message: 'Operation result unavailable'
      });
    }

    return { status, reportId: completedJob.returnvalue.reportId };
  }

  if (status === 'failed') {
    return {
      status,
      error: {
        code: 'REPORT_GENERATION_FAILED',
        message: 'We could not generate your report.'
      }
    };
  }

  reply.header('Retry-After', '2');

  return {
    status,
    progress: typeof job.progress === 'number'
      ? job.progress
      : null
  };
});

Register this handler alongside the submission handler in the authenticated API. The queue reads above can themselves fail if Redis is unavailable; an application-level Fastify error handler should translate known dependency failures to a controlled 503 and log the internal exception. Do not expose internal stack traces or raw BullMQ failure reasons to clients.

The status lookup and job result read are not a single atomic snapshot. This example assumes jobs are not manually retried after terminal completion. If jobs can be reopened or removed concurrently, use a durable operation record with versioned transitions instead.

A failed job may produce a 200 OK response from this endpoint. That is intentional: reading the status was successful, even though generating the report was not.

The report download route must independently enforce authorization; possessing a report ID is not authorization.

Queue records have a limited lifetime

The retention options in our submission example allow old jobs to be removed. BullMQ also supports limiting retained job counts. Consequently, a 404 does not prove a job never existed or never succeeded. It may have been removed.

For an operation users need to inspect days or weeks later, store its public status, timestamps and result reference in a database. Use the queue as an execution mechanism, not the only durable history of business outcomes.

5. Polling should not create another background problem

The simplest client can repeatedly query the status endpoint. However, if we use an asynchronous setInterval() callback, slow responses can overlap, creating the same problem we examined in our earlier timer article.

Instead, wait for each status request to complete before scheduling the next one.

function sleep(ms, signal) {
  return new Promise((resolve, reject) => {
    signal.throwIfAborted();

    const timer = setTimeout(() => {
      signal.removeEventListener('abort', onAbort);
      resolve();
    }, ms);

    function onAbort() {
      clearTimeout(timer);
      reject(signal.reason);
    }

    signal.addEventListener('abort', onAbort, { once: true });
  });
}

export async function waitForReport(statusUrl, {
  signal,
  onStatus = () => {}
} = {}) {
  const deadline = AbortSignal.timeout(120_000);
  const operationSignal = signal
    ? AbortSignal.any([signal, deadline])
    : deadline;

  while (true) {
    operationSignal.throwIfAborted();

    const response = await fetch(statusUrl, {
      signal: AbortSignal.any([
        operationSignal,
        AbortSignal.timeout(10_000)
      ]),
      cache: 'no-store'
    });

    if (!response.ok) {
      throw new Error(`Status lookup failed: ${response.status}`);
    }

    const result = await response.json();
    operationSignal.throwIfAborted();
    onStatus(result);

    if (result.status === 'succeeded' || result.status === 'failed') {
      return result;
    }

    // This API emits Retry-After as integer seconds.
    const header = response.headers.get('Retry-After');
    const delay = header && /^\d+$/.test(header)
      ? Math.max(1000, Number(header) * 1000)
      : 2000;

    // Do not shorten a very long server-requested delay.
    // Leave the operation running and let the UI resume later.
    if (!Number.isFinite(delay) || delay > 120_000) {
      throw new Error('Resume checking later');
    }

    await sleep(delay, operationSignal);
  }
}

This example assumes a modern runtime supporting AbortSignal.any() and AbortSignal.timeout(). It deliberately stops on status lookup errors instead of implementing another retry policy. Production clients can retry temporary lookup failures with bounded backoff and jitter.

If the two-minute waiting budget expires, the report has not necessarily failed. The client has simply stopped monitoring. The UI should say something like “Still processing — check again later,” retain the operation URL, and allow monitoring to resume.

Likewise, aborting the polling request does not cancel the background job. Job cancellation requires its own endpoint, authorization and cooperative worker logic. Some effects cannot be reversed after they have occurred.

What about WebSockets and webhooks?

ApproachGood fitImportant limitation
PollingSimple dashboards and short operationsRepeated status traffic
Server-Sent EventsOne-way browser progress updatesReconnect and reconcile missed events
WebSocketsInteractive applications with existing connectionsConnection lifecycle and authorization
WebhooksServer-to-server completion notificationsDelivery retries, verification and deduplication

Push notifications can improve responsiveness. They should not be the only source of truth. A disconnected browser or an unavailable webhook receiver can miss a completion message. Reconnecting clients should retrieve the authoritative operation status.

6. The queue and the database can disagree

Let's say we want a permanent history of exports. We create an operation record in MongoDB and then submit a job to Redis.

await operations.insertOne({
  _id: operationId,
  userId,
  status: 'accepted'
});

await reportQueue.add('generate-report', {
  userId,
  operationId
}, { jobId: operationId });

What happens if the application crashes between these two statements? The operation exists, but no worker knows about it. Reversing the statements simply creates the opposite failure mode: a queued job without a matching operation record.

MongoDB and Redis do not share a transaction. A MongoDB transaction cannot make an independent Redis command atomic.

One solution is the transactional outbox pattern [4]. Record both the operation and the intention to enqueue it in the same database transaction. A separate dispatcher reads unpublished outbox entries and submits the corresponding jobs.

// MongoDB replica set or sharded cluster required for
// multi-document transactions. client is a MongoClient.
await client.withSession(async session => {
  await session.withTransaction(async () => {
    await operations.insertOne({
      _id: operationId,
      userId,
      status: 'accepted',
      createdAt: new Date()
    }, { session });

    await outbox.insertOne({
      _id: operationId,
      type: 'generate-report',
      userId,
      publishedAt: null
    }, { session });
  });
});

Once the transaction commits, the API can acknowledge durable acceptance even if Redis is temporarily unavailable. The dispatcher can resume publication later.

Here is the basic dispatch sequence for a single selected outbox item:

await reportQueue.add(event.type, {
  userId: event.userId,
  operationId: event._id
}, {
  jobId: event._id,
  attempts: 3
});

await outbox.updateOne(
  { _id: event._id, publishedAt: null },
  { $set: { publishedAt: new Date() } }
);

This is a sketch, not a complete dispatcher. Production implementations need safe claiming or leases, bounded retry policies and recovery of unpublished records. A crash after publication but before marking the outbox entry as published can cause another delivery attempt.

BullMQ custom job IDs help suppress duplicates while the corresponding job still exists [5]. Once a job is removed, that protection no longer applies. Make the worker's business operation idempotent independently of the queue.

Article illustration
SVG source
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 760 285" width="760" height="285" role="img" aria-label="Recoverable job submission">
<rect x="0" y="0" width="760" height="285" rx="7" fill="#f6f4ee"/><text x="24" y="34" font-family="Arial, sans-serif" font-size="20" fill="#242b25" text-anchor="start" font-weight="600">Recoverable job submission</text>
<rect x="24" y="64" width="320" height="160" rx="7" fill="#e6eadd" stroke="#242b25"/><text x="184" y="88" font-family="Arial, sans-serif" font-size="16" fill="#242b25" text-anchor="middle" font-weight="600">One MongoDB transaction</text><rect x="44" y="104" width="280" height="44" rx="7" fill="#fffef9" stroke="#d9ddd2"/><text x="184.0" y="131.0" font-family="Arial, sans-serif" font-size="15" fill="#242b25" text-anchor="middle" font-weight="600">Operation record</text><rect x="44" y="163" width="280" height="44" rx="7" fill="#fffef9" stroke="#d9ddd2"/><text x="184.0" y="190.0" font-family="Arial, sans-serif" font-size="15" fill="#242b25" text-anchor="middle" font-weight="600">Outbox entry</text><line x1="344" y1="184" x2="400" y2="184" stroke="#6d7268" stroke-width="1.5"/><polygon points="400,184 391.00,188.00 391.00,180.00" fill="#6d7268"/><rect x="400" y="160" width="144" height="48" rx="7" fill="#fffef9" stroke="#d9ddd2"/><text x="472.0" y="189.0" font-family="Arial, sans-serif" font-size="15" fill="#242b25" text-anchor="middle" font-weight="600">Dispatcher</text><line x1="544" y1="184" x2="590" y2="184" stroke="#6d7268" stroke-width="1.5"/><polygon points="590,184 581.00,188.00 581.00,180.00" fill="#6d7268"/><rect x="590" y="160" width="146" height="48" rx="7" fill="#fffef9" stroke="#d9ddd2"/><text x="663.0" y="189.0" font-family="Arial, sans-serif" font-size="15" fill="#242b25" text-anchor="middle" font-weight="600">Redis queue</text><text x="568" y="142" font-family="Arial, sans-serif" font-size="12" fill="#6d7268" text-anchor="middle">Publish</text><text x="380" y="263" font-family="Arial, sans-serif" font-size="14" fill="#6d7268" text-anchor="middle">Retry publication safely; keep the worker idempotent.</text>
</svg>
Download SVG

Caption: Recording the operation and outbox entry atomically allows queue publication to recover after an interruption.

The worker should persist the report result before marking the operation as succeeded. If the report is stored outside MongoDB, the storage adapter must tolerate retries, and the operation record must not refer to a file that has not been durably written. A reconciliation process should detect operations stuck in intermediate states and repair or escalate them.

7. The client might retry the submission itself

Imagine the export was accepted, but the HTTP response disappeared when the user's connection dropped. The user clicks Export again. The server creates another job.

The client needs a stable identifier for the logical operation. For example, generate a UUID once and send it in an application-defined Idempotency-Key header on every retry of the same submission.

const key = crypto.randomUUID();

async function submitExport() {
  return fetch('/reports', {
    method: 'POST',
    headers: {
      'Idempotency-Key': key,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ format: 'csv' })
  });
}

Keep the same key for repeated attempts at this operation, not for every future export. Persist it client-side if recovery across reloads is necessary.

The server must implement the contract: scope the key to the authenticated principal, enforce uniqueness atomically, associate it with an immutable request fingerprint, and return the original operation identifier on matching retries. Reject reuse with conflicting parameters. Define retention explicitly.

An idempotency header by itself does nothing. A unique compound MongoDB index over the principal and key is one possible foundation. A transactional outbox can then make the accepted operation recoverable.

8. Monitor the operation, not just the HTTP request

An API dashboard reporting a 99.9% HTTP success rate could coexist with a substantial backlog of failed reports. Those are different measurements.

MetricWhat it reveals
Submission success rateWhether the API can accept work
Queue ageHow long jobs wait before starting
Attempt failure rateWhether workers are encountering transient problems
Terminal failure rateHow often accepted operations ultimately fail
End-to-end completion latencyHow long users wait for a useful result
Oldest unpublished outbox entryWhether dispatch is falling behind
Stuck operation countWhether reconciliation is needed

Use a common operation ID in API logs, worker logs and traces. Record timestamps at acceptance, start and terminal completion. Avoid logging sensitive job payloads or report contents.

BullMQ QueueEvents can help observe completed and failed jobs, but the processor should persist authoritative business results itself [6]. Event consumers should be prepared for replay, interruption and finite event retention. Treat notifications as a way to discover changes, not a replacement for durable state.

Article illustration
SVG source
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 760 312" width="760" height="312" role="img" aria-label="HTTP success is not business success">
<rect x="0" y="0" width="760" height="312" rx="7" fill="#f6f4ee"/><text x="24" y="34" font-family="Arial, sans-serif" font-size="20" fill="#242b25" text-anchor="start" font-weight="600">HTTP success is not business success</text>
<text x="24" y="85" font-family="Arial, sans-serif" font-size="15" fill="#242b25" text-anchor="start">Accepted submissions</text><rect x="24" y="97" width="650" height="22" rx="7" fill="#fffef9" stroke="#d9ddd2"/><rect x="24" y="97" width="650.0" height="22" rx="7" fill="#e6eadd"/><text x="735" y="114" font-family="Arial, sans-serif" font-size="15" fill="#242b25" text-anchor="end" font-weight="600">1000</text><text x="24" y="155" font-family="Arial, sans-serif" font-size="15" fill="#242b25" text-anchor="start">Completed exports</text><rect x="24" y="167" width="650" height="22" rx="7" fill="#fffef9" stroke="#d9ddd2"/><rect x="24" y="167" width="552.5" height="22" rx="7" fill="#e6eadd"/><text x="735" y="184" font-family="Arial, sans-serif" font-size="15" fill="#242b25" text-anchor="end" font-weight="600">850</text><text x="24" y="225" font-family="Arial, sans-serif" font-size="15" fill="#242b25" text-anchor="start">Failed exports</text><rect x="24" y="237" width="650" height="22" rx="7" fill="#fffef9" stroke="#d9ddd2"/><rect x="24" y="237" width="97.5" height="22" rx="7" fill="#ab4932"/><text x="735" y="254" font-family="Arial, sans-serif" font-size="15" fill="#ab4932" text-anchor="end" font-weight="600">150</text><text x="24" y="292" font-family="Arial, sans-serif" font-size="12" fill="#6d7268" text-anchor="start">Hypothetical example: all 1,000 accepted jobs have reached a terminal state.</text>
</svg>
Download SVG

Caption: In this hypothetical workload, successful submissions and successful exports tell very different stories.

Final thoughts

Background jobs are a useful way to make APIs responsive. But moving work into a queue changes the meaning of a successful response.

The API can promise that an operation has been accepted. The worker can report that it completed. The application must give the caller a reliable way to discover the difference.

Return an honest response, expose a status resource, persist important outcomes, and make retries safe. Then measure the time from the user's request to the actual result, not merely the time it takes to send an HTTP response.

A fast response is valuable. A fast response that tells the user something untrue is not.

THE CONVERSATION

Comments

Add your perspective ↓

Questions, useful examples and different approaches are welcome. Keep the discussion thoughtful and on topic.

Loading comments…

    Add your perspective

    All comments are reviewed before publication. Your name and comment will be public after approval; your email stays private and is used for account access or moderation, not a mailing list.

    Checking sign-in…