This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: rabbitmq-amqp-resilience

RabbitMQ AMQP Resilience, Dead Letter Exchange & Manual ACK Standard

Robust asynchronous message processing with RabbitMQ. Enforces manual consumer ACKs with explicit try/catch, dead-letter exchanges (DLX) for poisoned payloads, and prefetch limits (basicQos) to prevent memory exhaustion.

Prohibited Anti-Pattern: AI sets noAck: true losing critical messages on consumer process crash, and omits DLX dead-letter queues.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: RabbitMQ AMQP Resilience, Dead Letter Exchange & Manual ACK Standard - Robust asynchronous message processing with RabbitMQ. Enforces manual consumer ACKs with explicit try/catch, dead-letter exchanges (DLX) for poisoned payloads, and prefetch limits (basicQos) to prevent memory exhaustion.
globs: **/*rabbit*.ts, **/*amqp*.ts, **/*consumer*.py
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/rabbitmq-amqp-resilience"
---

# RabbitMQ AMQP Resilience, Dead Letter Exchange & Manual ACK Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: AI sets noAck: true losing critical messages on consumer process crash, and omits DLX dead-letter queues.

## System Constraints
You are a distributed messaging systems architect. In RabbitMQ consumer implementations, NEVER use 'noAck: true'. Always handle message acknowledgments manually with try/catch blocks, configure channel.prefetch (QoS) to prevent consumer memory starvation, and bind Dead Letter Exchanges (DLX) for unprocessable messages.

## Strict Guidelines
- Never use auto-ack ('noAck: true'); acknowledge messages manually only AFTER successful business processing.
- Always configure prefetch limits (channel.prefetch(10) or basicQos) to balance load across concurrent workers and prevent consumer OOM.
- Configure Dead Letter Exchanges (x-dead-letter-exchange) on all work queues; reject poisoned messages with nack(false, false) so they land in DLQ.
- Ensure message consumer handlers are idempotent using unique messageId or correlationId deduplication.

## Bad vs Good Implementations
### Resilient Consumer with Manual ACK & Dead Lettering vs Fragile Auto-ACK

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: With noAck: true, RabbitMQ deletes messages the instant they are sent over the socket. If the worker crashes mid-execution, the transaction is lost forever.
```typescript
// ANTI-PATTERN: Auto-ACK (noAck: true) and unhandled consumer crash
import amqp from "amqplib";

async function consumeQueue() {
  const conn = await amqp.connect("amqp://localhost");
  const channel = await conn.createChannel();
  
  // CRITICAL FLAW: noAck: true immediately removes message from queue
  channel.consume("orders", async (msg) => {
    const order = JSON.parse(msg.content.toString());
    await processOrder(order);
  }, { noAck: true });
}
```

#### Production Standard (Correct)
> **Standard**: Manual ACKs guarantee at-least-once delivery; poisoned messages are safely routed to DLQ without stalling the pipeline.
```typescript
// PRODUCTION STANDARD: Manual ACK, DLX Routing, and Prefetch QoS
import amqp from "amqplib";

async function resilientConsumer() {
  const conn = await amqp.connect(process.env.RABBITMQ_URL!);
  const channel = await conn.createChannel();

  // 1. Prefetch limit: Worker only receives 10 unacked messages at a time
  await channel.prefetch(10);

  // 2. Dead Letter Exchange (DLX) declaration
  await channel.assertExchange("orders.dlx", "direct", { durable: true });
  await channel.assertQueue("orders.dlq", { durable: true });
  await channel.bindQueue("orders.dlq", "orders.dlx", "dead_order");

  // 3. Work queue with DLX forwarding configuration
  await channel.assertQueue("orders.work", {
    durable: true,
    arguments: {
      "x-dead-letter-exchange": "orders.dlx",
      "x-dead-letter-routing-key": "dead_order",
    },
  });

  channel.consume("orders.work", async (msg) => {
    if (!msg) return;
    try {
      const payload = JSON.parse(msg.content.toString());
      await processOrder(payload);
      channel.ack(msg);
    } catch (err) {
      console.error("Order processing failed, routing to DLQ:", err);
      channel.nack(msg, false, false);
    }
  }, { noAck: false });
}
```

### Idempotent Message Deduplication via Redis

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: AMQP guarantees at-least-once delivery; network disconnects can trigger message redelivery.
```typescript
// ANTI-PATTERN: Executing credit charge on redelivered message without check
async function onPaymentMessage(msg) {
  await chargeCard(msg.userId, msg.amount); // Double charges on redelivery!
}
```

#### Production Standard (Correct)
> **Standard**: Atomic Redis locks guarantee that network retries never trigger duplicate business actions.
```typescript
// PRODUCTION STANDARD: Deduplication key with atomic setnx
async function onPaymentMessage(channel, msg, redis) {
  const messageId = msg.properties.messageId;
  const acquired = await redis.set(`msg_lock:${messageId}`, "1", "NX", "EX", 3600);
  if (!acquired) {
    console.warn("Duplicate message detected, skipping:", messageId);
    channel.ack(msg);
    return;
  }
  await chargeCard(msg.userId, msg.amount);
  channel.ack(msg);
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: RabbitMQ AMQP Resilience, Dead Letter Exchange & Manual ACK Standard

RabbitMQ AMQP Resilience, Dead Letter Exchange & Manual ACK Standard defines an industrial-grade behavioral standard for backend engineering. Robust asynchronous message processing with RabbitMQ. Enforces manual consumer ACKs with explicit try/catch, dead-letter exchanges (DLX) for poisoned payloads, and prefetch limits (basicQos) to prevent memory exhaustion. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: AI sets noAck: true losing critical messages on consumer process crash, and omits DLX dead-letter queues. Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftAI sets noAck: true losing critical messages on consumer process crash, and omits DLX dead-letter queues.Critical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Never use auto-ack ('noAck

Never use auto-ack ('noAck: true'); acknowledge messages manually only AFTER successful business processing.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Always configure prefetch limits (channel.prefetch(10) or basicQos) to balance load across concurrent workers and prevent consumer OOM.

Always configure prefetch limits (channel.prefetch(10) or basicQos) to balance load across concurrent workers and prevent consumer OOM.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Configure Dead Letter Exchanges (x-dead-letter-exchange) on all work queues

Configure Dead Letter Exchanges (x-dead-letter-exchange) on all work queues; reject poisoned messages with nack(false, false) so they land in DLQ.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Ensure message consumer handlers are idempotent using unique messageId or correlationId deduplication.

Ensure message consumer handlers are idempotent using unique messageId or correlationId deduplication.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is RabbitMQ AMQP Resilience, Dead Letter Exchange & Manual ACK Standard critical for AI coding assistants?

Robust asynchronous message processing with RabbitMQ. Enforces manual consumer ACKs with explicit try/catch, dead-letter exchanges (DLX) for poisoned payloads, and prefetch limits (basicQos) to prevent memory exhaustion. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (AI sets noAck: true losing critical messages on consumer process crash, and omits DLX dead-letter queues.) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

1 Rule in Stack

RabbitMQ