---
name: rabbitmq-development-dcbe2b86ce36
description: Best practices and guidelines for RabbitMQ message queue development with AMQP protocol
metadata:
  maintainer: Mindrally
  source: https://github.com/Mindrally/skills
---

# RabbitMQ Development

You are an expert in RabbitMQ and AMQP (Advanced Message Queuing Protocol) development. Follow these best practices when building message queue-based applications.

## Core Principles

- RabbitMQ is a message broker that receives messages from publishers and routes them to consumers
- AMQP 0-9-1 is the most commonly used protocol - an application layer protocol transmitting data in binary format
- Design for reliability, scalability, and fault tolerance
- Leave NO todos, placeholders, or missing pieces in the implementation

## Architecture Components

### Exchanges

- **Direct Exchange**: Routes based on exact routing key match - use for unicast routing
- **Fanout Exchange**: Routes to all bound queues regardless of routing key - use for broadcast
- **Topic Exchange**: Routes based on wildcard pattern matching - use for multicast routing
- **Headers Exchange**: Routes based on message header attributes - use for complex routing logic

### Queues

- Queues store messages until consumed
- Can be durable (survives broker restart) or transient (in-memory only)
- Metadata of durable queues is stored on disk
- Metadata of transient queues is stored in memory when possible

### Bindings

- Connect exchanges to queues with routing rules
- Binding keys determine which messages reach which queues
- Multiple bindings can connect the same exchange to multiple queues

## Queue Management Best Practices

### Queue Size

- Keep queue sizes small - large queues put heavy load on RAM usage
- RabbitMQ flushes messages to disk when RAM is constrained, impacting performance
- Monitor queue depth and implement backpressure mechanisms
- Use TTL (Time-To-Live) to automatically remove old messages

### Queue Types

#### Classic Queues

- Traditional RabbitMQ queue implementation
- Good for most use cases
- Supports all features (lazy queues, priorities, etc.)

#### Quorum Queues (Recommended)

- Introduced in RabbitMQ 3.8
- Replicated queue type for high availability and data safety
- Declare with `x-queue-type: quorum`
- Use for queues requiring durability and fault tolerance
- Cannot be set via policy - must be declared by client

### Performance Optimization

- Use transient messages for fastest throughput when durability isn't required
- Persistent messages are written to disk immediately, affecting throughput
- Queues are single-threaded - one queue handles up to ~50,000 messages
- Use multiple queues for better throughput on multi-core systems
- Have as many queues as cores on the underlying nodes

## Connection and Channel Management

### Connections

- Each connection uses approximately 100 KB of RAM (more with TLS)
- Thousands of connections can burden the server significantly
- Implement connection pooling in your applications
- Reuse connections where possible

### Channels

- Channels are lightweight connections multiplexing a single TCP connection
- Publishing and consuming happens over channels
- Create channels per thread/operation, not per message
- Close channels when no longer needed to free resources

## Prefetch and Consumer Configuration

### Prefetch (QoS)

- Prefetch defines how many unacknowledged messages a consumer receives at once
- Setting prefetch optimizes consumer throughput
- Low prefetch (1-10): Fair distribution, good for slow consumers
- High prefetch (100+): Better throughput, risk of uneven distribution
- Start with a moderate value (50-100) and tune based on metrics

### Acknowledgments

- **Auto-ack**: Higher throughput, least guarantees on failures
- **Manual-ack**: Lower throughput, better reliability
- Consider manual acknowledgment mode first as a rule of thumb
- Acknowledge promptly after processing to release server resources

## Message Handling

### Message Properties

- Set `delivery_mode=2` for persistent messages (survives broker restart)
- Use `content_type` to indicate payload format
- Include `correlation_id` for request/response patterns
- Set `expiration` for time-sensitive messages

### Publishing Best Practices

- Use publisher confirms for reliable publishing
- Handle returned messages (mandatory flag) appropriately
- Batch messages when possible for better throughput
- Consider message size - large messages impact performance

## Error Handling

### Dead Letter Exchanges

- Configure DLX for handling failed messages
- Messages routed to DLX when: rejected with requeue=false, TTL expires, queue length exceeded
- Process dead-lettered messages separately for analysis and retry

### Retry Queues Pattern

- Don't requeue failed messages to the same queue indefinitely
- Risk of self-inflicted DoS attack with continuous retry loops
- Implement retry queues with increasing delays
- Forward problematic messages to a "timeout" queue
- Example delays: 1s, 5s, 30s, then dead letter

### Circuit Breaker

- Implement circuit breaker pattern for downstream failures
- Prevent queue buildup when consumers can't process messages
- Use exponential backoff for reconnection attempts

## High Availability

### Clustering

- Deploy RabbitMQ in a cluster for high availability
- Use quorum queues for replicated, durable queues
- Configure appropriate number of replicas

### Mirroring (Classic Queues)

- Use `ha-mode` policy for classic queue mirroring
- Prefer quorum queues over mirrored classic queues for new deployments

## Security

### Authentication

- Use strong passwords and rotate regularly
- Consider LDAP or OAuth2 integration for enterprise deployments
- Enable TLS for encrypted connections
- Use separate credentials per application/service

### Authorization

- Implement vhost-based isolation for multi-tenant scenarios
- Grant minimum necessary permissions (configure, write, read)
- Use permission patterns to restrict access to specific resources

## Monitoring and Observability

### Key Metrics

- Queue depth (messages ready, messages unacknowledged)
- Message rates (publish, deliver, acknowledge)
- Connection and channel counts
- Memory and disk usage
- Consumer utilization

### Management Plugin

- Enable the management plugin for monitoring UI
- Use HTTP API for programmatic monitoring
- Export metrics to Prometheus/Grafana

### Alerts

- Alert on queue depth exceeding thresholds
- Monitor memory and disk alarms
- Track consumer disconnections
- Watch for message rate anomalies

## Testing

### Unit Testing

- Mock RabbitMQ client for isolated testing
- Test message serialization/deserialization
- Verify exchange and queue declarations

### Integration Testing

- Use containerized RabbitMQ for tests
- Test failure scenarios (connection loss, broker restart)
- Verify message acknowledgment behavior
- Load test with realistic message rates

## Common Patterns

### Work Queues (Task Distribution)

- Multiple consumers on single queue for load distribution
- Use prefetch to ensure fair distribution
- Acknowledge after task completion

### Publish/Subscribe

- Use fanout exchange for broadcasting
- Each subscriber gets its own queue bound to the exchange
- Consider topic exchange for filtered subscriptions

### RPC (Request/Response)

- Use correlation_id to match requests and responses
- Create exclusive reply queue per client
- Implement timeouts for pending requests

### Event Sourcing

- Use exchanges for event distribution
- Multiple services can independently consume events
- Maintain event ordering within partitions


---
Source attribution: Mindrally
Original project: https://github.com/Mindrally/skills/blob/7682ca77710e0971eab4e0ae5dddfa281aea0ba5/rabbitmq-development/SKILL.md
License: Apache-2.0
License information: https://www.apache.org/licenses/LICENSE-2.0
Original upstream instructions; downloaded from Mega AI Hub.

## Upstream license notice

                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "[]"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright [yyyy] [name of copyright owner]

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.



# Mega AI Hub resource metadata

Creator / publisher: Mindrally
Original project: https://github.com/Mindrally/skills/blob/7682ca77710e0971eab4e0ae5dddfa281aea0ba5/rabbitmq-development/SKILL.md
Attribution basis: Source repository record

Fields of work: Development & Engineering
Roles: Backend Developer, Data Engineer, DevOps / SRE
Specialties: Backend
Tools: Rabbitmq
Country applicability: Country not specified
Classification basis: Source catalog labels
Instruction SHA-256: a4bdc91267d380b3da86f42577aefbdfdfa49ff5289c20539ba4c2da0e44c2b4
