Claude Code for RabbitMQ: Message Queues and Work Queues — Claude Skills 360 Blog
Blog / AI / Claude Code for RabbitMQ: Message Queues and Work Queues
AI

Claude Code for RabbitMQ: Message Queues and Work Queues

Published: August 3, 2027
Read time: 5 min read
By: Claude Skills 360

RabbitMQ is the battle-tested message broker for work queues and pub/sub — amqp.connect(url) from amqplib creates a connection. conn.createChannel() opens a channel. channel.assertQueue(name, { durable: true }) creates a persistent queue. channel.sendToQueue(queue, Buffer.from(JSON.stringify(msg)), { persistent: true }) publishes a persistent message. Consumer: channel.consume(queue, handler, { noAck: false }), call channel.ack(msg) on success or channel.nack(msg, false, requeue) on failure. channel.prefetch(n) limits un-acked messages per consumer — enables fair work distribution. Exchange patterns: fanout broadcasts to all bound queues; topic routes by routingKey pattern (orders.#, orders.created); direct routes by exact key. Dead letter exchange: channel.assertQueue("jobs", { durable: true, arguments: { "x-dead-letter-exchange": "dlx", "x-dead-letter-routing-key": "failed" } }). Publisher confirms: await channel.confirmSelect(), then channel.publish(...) returns false if buffer is full — channel.waitForConfirms() resolves when broker confirms all. RPC: set replyTo: "amq.rabbitmq.reply-to" and a unique correlationId, then consume the reply queue. tls: { ca, cert, key } for TLS connections. Claude Code generates RabbitMQ work queues, topic routing, DLX patterns, and reliable job processors.

CLAUDE.md for RabbitMQ (amqplib)

## RabbitMQ Stack
- Version: amqplib >= 0.10
- Connect: const conn = await amqp.connect(process.env.RABBITMQ_URL!); const ch = await conn.createChannel()
- Queue: await ch.assertQueue("jobs", { durable: true }) — durable survives broker restart
- Publish: ch.sendToQueue("jobs", Buffer.from(JSON.stringify(payload)), { persistent: true })
- Consume: ch.consume("jobs", msg => { if (!msg) return; process(msg); ch.ack(msg) }, { noAck: false })
- Prefetch: ch.prefetch(10) — at most 10 unacknowledged messages per consumer
- Exchange: ch.assertExchange("events", "topic"); ch.bindQueue("orders-queue", "events", "orders.#")
- DLX: assertQueue("jobs", { arguments: { "x-dead-letter-exchange": "dlx" } })

RabbitMQ Connection Manager

// lib/rabbitmq/connection.ts — connection with auto-reconnect
import amqp, { type Connection, type Channel, type Options } from "amqplib"

type ManagedConnection = {
  connection: Connection
  channel:    Channel
}

let managed: ManagedConnection | null = null

async function createConnection(): Promise<ManagedConnection> {
  const url = process.env.RABBITMQ_URL ?? "amqp://localhost"
  const connection = await amqp.connect(url)
  const channel = await connection.createChannel()

  connection.on("error", (err) => {
    console.error("[RabbitMQ] Connection error:", err.message)
    managed = null
  })

  connection.on("close", () => {
    console.warn("[RabbitMQ] Connection closed — will reconnect on next use")
    managed = null
  })

  return { connection, channel }
}

export async function getChannel(): Promise<Channel> {
  if (!managed) {
    managed = await createConnection()
  }
  return managed.channel
}

export async function closeConnection(): Promise<void> {
  if (managed) {
    await managed.connection.close()
    managed = null
  }
}

process.once("SIGTERM", closeConnection)
process.once("SIGINT",  closeConnection)

Publisher

// lib/rabbitmq/publisher.ts — typed reliable publisher
import { getChannel } from "./connection"

export type JobPayload<T> = {
  jobType:    string
  jobId:      string
  createdAt:  string
  payload:    T
  retryCount?: number
}

const EXCHANGE    = "app-events"
const JOBS_QUEUE  = "jobs"
const DELAY_QUEUE = "jobs-delayed"

export async function setupExchanges(): Promise<void> {
  const ch = await getChannel()

  // Topic exchange for pub/sub events
  await ch.assertExchange(EXCHANGE, "topic", { durable: true })

  // Dead letter exchange
  await ch.assertExchange("dlx", "direct", { durable: true })
  await ch.assertQueue("jobs-failed", { durable: true })
  await ch.bindQueue("jobs-failed", "dlx", "failed")

  // Main work queue with DLX
  await ch.assertQueue(JOBS_QUEUE, {
    durable: true,
    arguments: {
      "x-dead-letter-exchange":    "dlx",
      "x-dead-letter-routing-key": "failed",
      "x-message-ttl":             30 * 60 * 1000,  // 30 min max job time
    },
  })
}

/** Publish a job to the work queue */
export async function publishJob<T>(
  jobType: string,
  payload: T,
  options: { priority?: number; expiration?: number } = {},
): Promise<string> {
  const ch = await getChannel()
  const jobId = `${jobType}-${Date.now()}-${Math.random().toString(36).slice(2)}`

  const job: JobPayload<T> = {
    jobType,
    jobId,
    createdAt: new Date().toISOString(),
    payload,
    retryCount: 0,
  }

  const publishOptions: Options.Publish = {
    persistent:  true,
    contentType: "application/json",
    ...(options.priority   ? { priority:   options.priority }                        : {}),
    ...(options.expiration ? { expiration: String(options.expiration) }              : {}),
  }

  ch.sendToQueue(JOBS_QUEUE, Buffer.from(JSON.stringify(job)), publishOptions)
  return jobId
}

/** Publish an event to the topic exchange */
export async function publishEvent<T>(
  routingKey: string,
  payload:    T,
): Promise<void> {
  const ch = await getChannel()
  ch.publish(
    EXCHANGE,
    routingKey,
    Buffer.from(JSON.stringify({ routingKey, payload, timestamp: Date.now() })),
    { persistent: true, contentType: "application/json" },
  )
}

Worker Consumer

// lib/rabbitmq/worker.ts — reliable job consumer with retry and DLQ
import { getChannel } from "./connection"
import type { JobPayload } from "./publisher"
import type { ConsumeMessage } from "amqplib"

const JOBS_QUEUE = "jobs"
const MAX_RETRIES = 3

export type JobHandler<T> = (payload: T, meta: { jobId: string; attempt: number }) => Promise<void>

type HandlerMap = Record<string, JobHandler<unknown>>

export async function startWorker(
  handlers:    HandlerMap,
  concurrency = 5,
): Promise<() => Promise<void>> {
  const ch = await getChannel()
  ch.prefetch(concurrency)

  await ch.consume(JOBS_QUEUE, async (msg: ConsumeMessage | null) => {
    if (!msg) return

    let job: JobPayload<unknown>
    try {
      job = JSON.parse(msg.content.toString()) as JobPayload<unknown>
    } catch {
      console.error("[Worker] Malformed message — rejecting without requeue")
      ch.nack(msg, false, false)
      return
    }

    const handler = handlers[job.jobType]

    if (!handler) {
      console.warn(`[Worker] No handler for jobType: ${job.jobType}`)
      ch.nack(msg, false, false)  // DLQ the unknown job type
      return
    }

    const attempt = (job.retryCount ?? 0) + 1

    try {
      await handler(job.payload, { jobId: job.jobId, attempt })
      ch.ack(msg)
    } catch (err) {
      console.error(`[Worker] Job ${job.jobId} failed (attempt ${attempt}):`, (err as Error).message)

      if (attempt >= MAX_RETRIES) {
        console.error(`[Worker] Job ${job.jobId} exhausted retries — sending to DLQ`)
        ch.nack(msg, false, false)  // Will be routed to DLX → jobs-failed
      } else {
        // Requeue with incremented retry count — small delay via setTimeout
        ch.nack(msg, false, false)  // Reject, let DLX handle or requeue separately
        await new Promise((r) => setTimeout(r, 1000 * 2 ** attempt))
        const { publishJob } = await import("./publisher")
        await publishJob(job.jobType, job.payload, {})
      }
    }
  })

  const stop = async () => {
    await ch.close()
    await closeConnection()
  }

  const { closeConnection } = await import("./connection")
  process.once("SIGTERM", stop)
  process.once("SIGINT",  stop)

  return stop
}

Next.js API + Worker

// app/api/emails/route.ts — enqueue email job via RabbitMQ
import { NextResponse } from "next/server"
import { z } from "zod"
import { publishJob } from "@/lib/rabbitmq/publisher"
import { auth } from "@/lib/auth"

const EmailSchema = z.object({
  to:       z.string().email(),
  template: z.string(),
  data:     z.record(z.unknown()),
})

export async function POST(req: Request) {
  const session = await auth()
  if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })

  const body = EmailSchema.parse(await req.json())
  const jobId = await publishJob("send-email", { ...body, userId: session.user.id })

  return NextResponse.json({ jobId }, { status: 202 })
}

// worker/index.ts — long-running worker process
// import { startWorker } from "@/lib/rabbitmq/worker"
// import { setupExchanges } from "@/lib/rabbitmq/publisher"
// 
// async function main() {
//   await setupExchanges()
//   await startWorker({
//     "send-email": async ({ to, template, data }) => {
//       await sendEmail({ to, template, data })
//     },
//     "generate-report": async ({ userId, type }) => {
//       await generateReport(userId, type)
//     },
//   }, 10)
//   console.log("[Worker] Listening for jobs...")
// }
// main().catch(console.error)

For the Kafka alternative when needing durable event streaming with partitioned topics, ordered message delivery within a partition, consumer group replay from any offset, and horizontal scaling to billions of events — Kafka is the standard for high-throughput durable event logs while RabbitMQ is optimized for work queues with flexible routing (topic, fanout, headers), priority queues, and low-latency task dispatch, see the Kafka guide. For the BullMQ/Redis alternative when wanting a simpler queue implementation backed by Redis (no separate broker), job rate limiting, delayed jobs, repeatable jobs, and a built-in admin dashboard with Bull Board — BullMQ is easier to operate for Node.js-centric stacks while RabbitMQ provides more robust protocol-level routing, federation, and cross-language support, see the BullMQ guide. The Claude Skills 360 bundle includes RabbitMQ skill sets covering work queues, topic routing, and reliable job processors. Start with the free tier to try message queue generation.

Keep Reading

AI

Claude Code for email.contentmanager: Python Email Content Accessors

Read and write EmailMessage body content with Python's email.contentmanager module and Claude Code — email contentmanager ContentManager for the class that maps content types to get and set handler functions allowing EmailMessage to support get_content and set_content with type-specific behaviour, email contentmanager raw_data_manager for the ContentManager instance that handles raw bytes and str payloads without any conversion, email contentmanager content_manager for the standard ContentManager instance used by email.policy.default that intelligently handles text plain text html multipart and binary content types, email contentmanager get_content_text for the handler that returns the decoded text payload of a text-star message part as a str, email contentmanager get_content_binary for the handler that returns the raw decoded bytes payload of a non-text message part, email contentmanager get_data_manager for the get-handler lookup used by EmailMessage get_content to find the right reader function for the content type, email contentmanager set_content text for the handler that creates and sets a text part correctly choosing charset and transfer encoding, email contentmanager set_content bytes for the handler that creates and sets a binary part with base64 encoding and optional filename Content-Disposition, email contentmanager EmailMessage get_content for the method that reads the message body using the registered content manager handlers, email contentmanager EmailMessage set_content for the method that sets the message body and MIME headers in one call, email contentmanager EmailMessage make_alternative make_mixed make_related for the methods that convert a simple message into a multipart container, email contentmanager EmailMessage add_attachment for the method that attaches a file or bytes to a multipart message, and email contentmanager integration with email.message and email.policy and email.mime and io for building high-level email readers attachment extractors text body accessors HTML readers and policy-aware MIME construction pipelines.

5 min read Feb 12, 2029
AI

Claude Code for email.charset: Python Email Charset Encoding

Control header and body encoding for international email with Python's email.charset module and Claude Code — email charset Charset for the class that wraps a character set name with the encoding rules for header encoding and body encoding describing how to encode text for that charset in email messages, email charset Charset header_encoding for the attribute specifying whether headers using this charset should use QP quoted-printable encoding BASE64 encoding or no encoding, email charset Charset body_encoding for the attribute specifying the Content-Transfer-Encoding to use for message bodies in this charset such as QP or BASE64, email charset Charset output_codec for the attribute giving the Python codec name used to encode the string to bytes for the wire format, email charset Charset input_codec for the attribute giving the Python codec name used to decode incoming bytes to str, email charset Charset get_output_charset for returning the output charset name, email charset Charset header_encode for encoding a header string using the charset's header_encoding method, email charset Charset body_encode for encoding body content using the charset's body_encoding, email charset Charset convert for converting a string from the input_codec to the output_codec, email charset add_charset for registering a new charset with custom encoding rules in the global charset registry, email charset add_alias for adding an alias name that maps to an existing registered charset, email charset add_codec for registering a codec name mapping for use by the charset machinery, and email charset integration with email.message and email.mime and email.policy and email.encoders for building international email senders non-ASCII header encoders Content-Transfer-Encoding selectors charset-aware message constructors and MIME encoding pipelines.

5 min read Feb 11, 2029
AI

Claude Code for email.utils: Python Email Address and Header Utilities

Parse and format RFC 2822 email addresses and dates with Python's email.utils module and Claude Code — email utils parseaddr for splitting a display-name plus angle-bracket address string into a realname and email address tuple, email utils formataddr for combining a realname and address string into a properly quoted RFC 2822 address with angle brackets, email utils getaddresses for parsing a list of raw address header strings each potentially containing multiple comma-separated addresses into a list of realname address tuples, email utils parsedate for parsing an RFC 2822 date string into a nine-tuple compatible with time.mktime, email utils parsedate_tz for parsing an RFC 2822 date string into a ten-tuple that includes the UTC offset timezone in seconds, email utils parsedate_to_datetime for parsing an RFC 2822 date string into an aware datetime object with timezone, email utils formatdate for formatting a POSIX timestamp or the current time as an RFC 2822 date string with optional usegmt and localtime flags, email utils format_datetime for formatting a datetime object as an RFC 2822 date string, email utils make_msgid for generating a globally unique Message-ID string with optional idstring and domain components, email utils decode_rfc2231 for decoding an RFC 2231 encoded parameter value into a tuple of charset language and value, email utils encode_rfc2231 for encoding a string as an RFC 2231 encoded parameter value, email utils collapse_rfc2231_value for collapsing a decoded RFC 2231 tuple to a Unicode string, and email utils integration with email.message and email.headerregistry and datetime and time for building address parsers date formatters message-id generators header extractors and RFC-compliant email construction utilities.

5 min read Feb 10, 2029

Put these ideas into practice

Claude Skills 360 gives you production-ready skills for everything in this article — and 2,350+ more. Start free or go all-in.

Back to Blog

Get 360 skills free