К основному содержанию
скилл CX Codex

rabbitmq-development — скилл для Claude Code: правила работы

Набор правил для ИИ-агента: как проектировать обменники, очереди и потребителей RabbitMQ без типичных ошибок.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add Mindrally/skills --skill rabbitmq-development -a claude-code
Открыть на GitHub

Что делает rabbitmq-development

Скилл задаёт агенту рамки при работе с RabbitMQ и протоколом AMQP 0-9-1. Он подсказывает, какой тип обменника выбрать под задачу: direct для точечной маршрутизации, fanout для рассылки всем очередям, topic для маршрутизации по шаблону, headers для сложной логики по заголовкам сообщения. Очереди при этом описываются как durable или transient, а для отказоустойчивых сценариев агент предложит quorum-очереди, которые объявляются на стороне клиента через x-queue-type: quorum.

Отдельный блок — про производительность и соединения. Очередь однопоточная, поэтому для многоядерных узлов агент будет разносить нагрузку по нескольким очередям. Каналы советуется создавать на поток или операцию, а не на каждое сообщение, и закрывать, когда они больше не нужны. Prefetch агент предложит начать с умеренного значения и подстраивать по метрикам, а подтверждения — ручные, чтобы не терять сообщения при сбоях.

Ошибки разбираются через dead letter exchanges и retry-очереди с растущими задержками: бесконечный возврат сбойного сообщения в ту же очередь скилл называет риском устроить самому себе отказ в обслуживании. Есть разделы про кластеризацию, TLS, разграничение прав по vhost и метрики для мониторинга. Учтите: исходный текст обрезан на разделе про work queues, так что часть паттернов в скилле может быть раскрыта не полностью.

Какие задачи решает

  • выбрать тип обменника под схему маршрутизации сообщений
  • объявить quorum-очередь для отказоустойчивой доставки
  • настроить prefetch и ручные подтверждения под нагрузку потребителя
  • собрать retry-очереди с растущей задержкой вместо бесконечного requeue
  • разложить метрики RabbitMQ по Prometheus и Grafana

Примеры запросов агенту

  • Настрой обменники и очереди RabbitMQ под маршрутизацию заказов по регионам
  • Перепиши потребителя на ручные подтверждения и prefetch 50, объясни выбор
  • Добавь dead letter exchange и retry-очередь с задержками 1s, 5s, 30s

Как установить rabbitmq-development

1Через Skills CLI (Vercel)

npx skills add Mindrally/skills --skill rabbitmq-development -a claude-code

2Вручную: положить файлы

~/.claude/skills/rabbitmq-development/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/rabbitmq-development/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о rabbitmq-development

Как установить rabbitmq-development в Claude?

Выполните npx skills add Mindrally/skills --skill rabbitmq-development -a claude-code. После этого файл скилла появится по пути ~/.claude/skills/rabbitmq-development/SKILL.md.

Что делает rabbitmq-development?

Даёт агенту правила разработки на RabbitMQ и AMQP: выбор обменников и очередей, работа с каналами и соединениями, prefetch, подтверждения, обработка ошибок и мониторинг.

Скилл требует установленного RabbitMQ?

Скилл содержит только инструкции для агента и ничего не запускает сам. Для интеграционных тестов в нём описан вариант с RabbitMQ в контейнере.

Исходный текст

SKILL.md · Apache-2.0
---
name: rabbitmq-development
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

© Mindrally · Apache-2.0 · Mindrally/skills

Похожие скиллы

Всё по теме «Бэкенд и API» →
rabbitmq-expert martinholovsky Скилл для ИИ-агента, который разбирается в архитектуре RabbitMQ: обменники, кластеры, отказоустойчивость, мониторинг. Пригодится, когда проектируешь очереди или чинишь кластер. CX Codex +1 491установок backend-development mrgoonie Скилл ведёт агента по проектированию API, схем БД, аутентификации и CI/CD. Пригодится, когда бэкенд пишется с нуля или переезжает в прод. CX Codex +1 2 300установок cloudrun-development TencentCloudBase Правила разработки бэкенда на CloudBase Run: развёртывание сервисов с долгими соединениями, доступом к VPC-базам и разбор сбоев контейнеров. CX Codex +1 983установок expressjs-development manutej Скилл для ИИ-агента, который подсказывает, как строить Express.js-приложения: маршруты, middleware, обработка запросов и ошибок. CX Codex +1 555установок spring-boot-development manutej Скилл для ИИ-агента, который подсказывает, как писать Spring Boot: авто-конфигурация, внедрение зависимостей, REST-контроллеры, Spring Data и Spring Security. CX Codex +1 534установок django-celery affaan-m Шаблоны интеграции Celery и Django: настройка брокера, повтор сбоев и планировщик Beat. Пригодится при выносе тяжелых задач из HTTP-цикла. CX Codex +1 4 600установок

Из того же набора168

php-development Скилл задаёт агенту правила написания PHP 8+ кода: SOLID, PSR-12, строгая типизация, тесты на PHPUnit. Пригодится, когда проект на PHP растёт и хочется единый стиль. CX Codex +1 1 100установок gitlab-workflow Скилл учит ИИ-ассистента правилам GitLab: от оформления merge request до настройки конвейеров .gitlab-ci.yml. Помогает выстроить командную разработку. CX Codex +1 1 100установок ux-design Скилл задаёт агенту правила UX-проектирования: от исследования пользователей до доступности и адаптивной вёрстки. Пригодится, когда проектируешь или проверяешь интерфейс. CX Codex +1 1 100установок analytics-data-analysis Задаёт агенту правила работы с pandas, matplotlib и seaborn: как чистить датасет, строить графики и оформлять Jupyter-ноутбук. CX Codex +1 1 100установок nextauth-authentication Скилл учит агента внедрять аутентификацию через NextAuth.js (Auth.js v5) в Next.js. Помогает настроить сессии, роуты и защиту страниц. CX Codex +1 1 100установок scipy-best-practices Скилл задаёт агенту правила научных вычислений на SciPy: оптимизация, линейная алгебра, статистика, сигналы. Пригодится, когда код на Python считает числа, а не рисует интерфейсы. CX Codex +1 1 000установок kubernetes Задаёт агенту правила работы с Kubernetes, Helm, Ansible и CI/CD. Пригодится, когда манифесты и пайплайны пишет ИИ, а не человек. CX Codex +1 1 000установок quarkus Скилл задаёт агенту правила кода на Quarkus: Jakarta EE, MicroProfile, нативные сборки GraalVM и реактивные паттерны. CX Codex +1 1 000установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой