Skip to content

Getting started

This guide walks you through adding a durable background queue to your Layeron backend application. You will declare a queue, register it, publish a message from a route handler, and write a consumer to process messages in the background.

Import queue from @layeron/modules. Declare the queue inside your application code with a stable logical name and register it with your backend app using app.use().

Terminal window
import { backend } from "@layeron/core"
import { queue } from "@layeron/modules"
const app = backend()
// Declare the queue
const reportsQueue = queue({
name: "report-generation",
retry: {
maxAttempts: 3,
backoff: "exponential",
},
})
// Register the queue as an application capability
app.use(reportsQueue)

Layeron stores queue state, retries, dead letters, and idempotency records through your Database product.

Use the queue.send(...) method inside any HTTP route handler to push a serializable JSON payload into the queue. The route can respond to the user immediately, offloading the heavy work.

Terminal window
app.post("/reports", async (request) => {
const body = await request.json() as { reportId: string; format: string }
// Send the message payload to the queue
const result = await reportsQueue.send({
reportId: body.reportId,
format: body.format,
requestedAt: new Date().toISOString(),
})
// Respond immediately with the messageId and HTTP 202 (Accepted)
return Response.json({
status: "queued",
messageId: result.messageId,
}, { status: 202 })
})

To process your queued messages, register a consumer using queue.consume(). Layeron runs this callback in the background when messages are delivered.

Terminal window
reportsQueue.consume(async (message, context) => {
const { reportId, format } = message.payload
console.log(`[Queue] Processing report ${reportId} in format ${format}...`)
// Perform the heavy work
await generateAndUploadReport(reportId, format)
console.log(`[Queue] Report ${reportId} processed successfully!`)
})

You do not need to manually acknowledge messages. Layeron automatically handles acknowledgment flow:

  • Success (ack): If your .consume() handler completes without throwing an error, Layeron acknowledges the message and deletes it from the queue.
  • Failure (nack): If your handler throws an error, Layeron rejects the message and schedules a retry according to your queue’s configured retry policy.

  • Guarantees and limits: Understand at-least-once delivery, idempotency, payload size, retention, DLQs, consumers, and retry backoff.
  • Examples: Adapt webhook backgrounding, delayed reminders, batch processing, and DLQ redrive patterns.
  • Webhook deduplication: Pair Queue with webhook idempotency keys.
  • DLQ and redrive: Inspect failed messages and redrive them safely.
  • API reference: Review queue options, retry settings, consumers, send options, and result contracts.