Message queue patterns

From FerroxLabs/wayland · View interactive version

Message queue patterns is an AI agent skill from the GitHub repository FerroxLabs/wayland. Guides expert-level message queue patterns implementation: architecture and automation decision frameworks, production-ready patterns, and concrete templates for message queue patterns workflows. Use when the user asks about message queue patterns, message queue patterns configuration, or backend be

How to use this skill

Skill file

Message Queue Patterns

When to Use

Use this skill when:

Do NOT use this skill when:


Process

1. Identify the Core Delivery Requirement

Start by pinning down the delivery semantics the system actually needs. This determines which brokers and patterns are even viable.

2. Map the Communication Topology

Identify which structural pattern matches the system's needs before selecting a broker:

3. Select the Right Broker

Match broker capabilities to the delivery and topology requirements identified in steps 1 and 2:

4. Design for Idempotency and Deduplication

Every production message consumer must be idempotent. This is non-negotiable with at-least-once delivery.

5. Implement the Transactional Outbox Pattern (When Required)

Use this pattern whenever a service must atomically update its own database AND publish a message. The dual-write problem (DB commit succeeds, publish fails -- or vice versa) causes data inconsistency without this pattern.

6. Design the Dead Letter Queue and Retry Strategy

Every queue needs a DLQ and a documented retry policy before the first consumer is deployed.

7. Implement Saga Pattern for Distributed Transactions

When a business operation spans multiple services, use the Saga pattern instead of distributed (2PC) transactions.

8. Validate, Monitor, and Tune

Production message queue systems require ongoing operational visibility.


Output Format

## Message Queue Pattern Design: [System Name]

### Delivery Requirements
| Requirement          | Value                    | Rationale                         |
|----------------------|--------------------------|-----------------------------------|
| Delivery guarantee   | at-least-once            | Consumer is idempotent             |
| Ordering requirement | Per-entity (partition)   | Entity updates must be sequential |
| Max acceptable lag   | 30 seconds P99           | SLA requirement                   |
| Retention            | 7 days                   | Replay and audit requirement      |

### Broker Selection
**Selected:** [Broker Name]
**Alternatives considered:** [Broker A] -- rejected because [specific reason]; [Broker B] -- rejected because [specific reason]
**Rationale:** [2-4 sentences on why this broker's semantics match the requirements]

### Topology Diagram (text)
[Producer Service]
      |
      | publishes OrderPlaced event
      v
[orders topic / exchange]
      |--- [Partition 0] --> [Inventory Service Consumer Group]
      |--- [Partition 1] --> [Inventory Service Consumer Group]
      |--- [Fanout]      --> [Audit Log Service]
                         --> [Notification Service]

### Queue/Topic Configuration
| Queue/Topic Name     | Partitions | Retention | DLQ Name              | Max Retries | Backoff       |
|----------------------|------------|-----------|----------------------|-------------|---------------|
| orders.placed        | 12         | 7 days    | orders.placed.dlq    | 5           | exp, 1s--5min |
| orders.payment.cmd   | 6          | 1 day     | orders.payment.dlq   | 3           | exp, 1s--2min |

### Consumer Design
**Consumer Group:** [group-name]
**Prefetch / max.poll.records:** [value]
**Idempotency mechanism:** [message ID + Redis SET NX / DB unique constraint / optimistic lock]
**Concurrency model:** [N threads / async coroutines / process pool]

### Message Envelope Schema

{

"id": "ulid or uuid-v4",

"type": "OrderPlaced",

"version": "1.0",

"source": "order-service",

"timestamp": "2024-03-15T10:30:00Z",

"correlation_id": "trace-propagation-id",

"payload": { ... },

"metadata": {

"retry_count": 0,

"original_queue": null

}

}


### Retry & DLQ Policy
| Error Type           | Action             | Max Attempts | Backoff Strategy       |
|----------------------|--------------------|--------------|------------------------|
| Network timeout      | Retry              | 5            | Exp, base 1s, cap 300s |
| Deserialization fail | DLQ immediately    | 1            | None                   |
| Business rule fail   | DLQ immediately    | 1            | None                   |
| DB connection error  | Retry              | 3            | Exp, base 2s, cap 60s  |

### Transactional Outbox (if applicable)
- Outbox table: [schema.outbox_events]
- Relay mechanism: [Debezium CDC / polling relay, interval Xs]
- Retention: [24h processed, 7d archived]

### Saga Design (if applicable)
- Saga type: [choreography / orchestration]
- Steps: [step1 -> step2 -> step3]
- Compensation: [step3_compensate -> step2_compensate -> step1_compensate]
- Timeout: [30 minutes]
- State table: [schema.saga_state]

### Monitoring & Alerting
| Metric                    | Warning Threshold | Critical Threshold | Tool              |
|---------------------------|-------------------|--------------------|-------------------|
| Consumer lag (seconds)    | >30s              | >120s              | Prometheus/Burrow |
| DLQ depth                 | >0                | >50                | CloudWatch/DD     |
| Message age P99           | >10s              | >60s               | Custom metric     |
| Consumer error rate       | >1%               | >5%                | APM               |

### Implementation Notes
- [Specific gotcha or non-obvious configuration detail]
- [Schema evolution policy]
- [Local development setup -- e.g., Docker Compose with broker]

Rules

  1. Never perform a dual-write without the Transactional Outbox pattern. Writing to a database and publishing to a message broker in two separate operations will eventually produce inconsistency. This is not a theoretical risk -- it will happen in production during network partitions, application restarts, and GC pauses.
  1. Every queue in production must have a corresponding Dead Letter Queue configured before the queue is used. Deploying a queue without a DLQ means failed messages are silently dropped or endlessly requeued, causing invisible data loss or runaway retry storms.
  1. Never consume without acknowledging explicitly. Auto-ack modes in RabbitMQ and implicit offset commits in Kafka (with enable.auto.commit=true) cause message loss when consumers crash between processing and commit. Always use manual acknowledgment and commit only after the processing operation is durably complete.
  1. Partition count is effectively immutable in Kafka -- size it correctly the first time. Increasing partitions is possible but triggers consumer group rebalance, invalidates key-based ordering for existing keys, and disrupts stateful stream processing. Use the formula: partitions = max(desired_throughput / single_partition_throughput, target_consumer_count * 2), minimum 3 for fault tolerance.
  1. Never use a message queue to synchronously block a request-response cycle longer than 2 seconds. Request/Reply over queues becomes a liability at that latency. Users notice. If you need synchronous semantics, use a direct HTTP/gRPC call. Queues are for decoupling, not replacing synchronous communication with hidden latency.
  1. Message payload schemas must be versioned and backward compatible. Adding a new required field to a message schema without a version bump will silently break all existing consumers. Use schema evolution rules: add optional fields only, never remove fields, never change field types. Increment the version field in the envelope and support N-1 versions in consumers during rolling deployments.
  1. Consumer concurrency must not exceed the safe concurrency level of downstream dependencies. Spinning up 50 consumer threads that all query the same Postgres instance will cause connection exhaustion. Calculate: max_consumers = (db_connection_pool_size * 0.8) / connections_per_consumer_thread. For external APIs, apply rate limiting at the consumer level.
  1. Never log or store message payloads containing PII, credentials, or PCI data in DLQs, outbox tables, or monitoring systems without field-level encryption or tokenization. Dead letter queues are often less secured than primary queues. Audit access controls on DLQs separately from operational queues.
  1. Saga compensating transactions must be idempotent and must always succeed. A compensation that can fail leaves the saga in an unresolvable stuck state. Design compensations to be terminal -- they may log a failure if the forward action was never applied, but they must always complete the state machine transition. Use the "saga log" as the source of truth, not the state of external services.
  1. Consumer lag alerts must be time-based, not count-based, for variable-throughput systems. 10,000 messages of lag means nothing without knowing throughput. At 50,000 msg/s that is 200ms of lag (fine). At 100 msg/s that is 100 seconds of lag (alert). Convert lag counts to time by dividing by the rolling average consumption rate over the last 5 minutes.

Edge Cases

Poison Message Handling

A poison message is one that consistently causes the consumer to crash or throw an unhandled exception. Without protection, the message is requeued indefinitely, crashing consumers in a loop.

Consumer Group Rebalancing Storms (Kafka)

When new consumers join or leave a consumer group, Kafka triggers a rebalance, during which all consumers stop processing. Frequent rebalances cause throughput collapse.

Schema Evolution Breaking Changes

A consumer deployed before a producer sends a new mandatory field will fail with a deserialization error.

High-Volume Fan-out to Slow Consumers

When a topic has 50 subscribers and one subscriber is consistently slow, the slow subscriber's lag grows unboundedly while fast subscribers are current.

Exactly-Once Processing Without Broker Transactions

When using a broker that does not natively support transactions (SQS Standard, older RabbitMQ without quorum queues), achieve effectively-once semantics at the application level.

Ordering Guarantees with Multiple Producers

When multiple service instances produce to the same Kafka topic, partition-key-based ordering can be violated if different instances produce messages for the same entity out of order due to network delay.

Broker Outage and Producer Resilience

When the message broker is unavailable, naive producers either drop messages or block indefinitely.


Example

Input: "We're building an e-commerce order processing system. When an order is placed, we need to: reserve inventory, charge the customer's card, send a confirmation email, and update the analytics warehouse. Services are in Python and Node.js. We're on AWS. What message queue pattern should we use and how should we set it up?"

Output:

Message Queue Pattern Design: E-Commerce Order Processing

Delivery Requirements

| Requirement | Value | Rationale |

|--------------------|--------------------------------|-----------------------------------------------------------------|

| Delivery guarantee | At-least-once | All consumers will be idempotent; simpler than exactly-once |

| Ordering | Per-order (not global) | Inventory and payment events for the same order must be ordered |

| Max acceptable lag | 5 seconds P99 (payment/inv), 60s (email/analytics) | Payment SLA is strict; email and analytics are best-effort |

| Retention | 7 days | Replay for analytics backfill; audit requirement |

Broker Selection

Selected: Amazon SQS + Amazon SNS (fan-out topology)

Alternatives considered:

Rationale: SNS publishes the OrderPlaced event to a single topic. Four SQS queues subscribe to that SNS topic -- one per downstream concern. This decouples the order service from all four consumers. SQS FIFO is used for inventory and payment (where order-per-entity matters and we need deduplication); SQS Standard is used for email and analytics (where ordering is irrelevant and higher throughput is preferred). All queues are managed by AWS -- zero broker operations.

Topology Diagram

[Order Service (Python)]
         |
         | INSERT into outbox_events table (same DB transaction as order record)
         |
[Outbox Relay (Lambda, polls every 5s)]
         |
         | SNS Publish: OrderPlaced event
         v
[SNS Topic: ecommerce-order-events]
         |
         |--- [SQS FIFO: inventory-reservation.fifo]     --> [Inventory Service (Python)]
         |--- [SQS FIFO: payment-processing.fifo]        --> [Payment Service (Node.js)]
         |--- [SQS Standard: email-notifications]        --> [Email Service (Node.js)]
         |--- [SQS Standard: analytics-ingest]           --> [Analytics Worker (Python)]
         |
         Each SQS queue has a corresponding DLQ:
         inventory-reservation.fifo         --> inventory-reservation-dlq.fifo
         payment-processing.fifo            --> payment-processing-dlq.fifo
         email-notifications                --> email-notifications-dlq
         analytics-ingest                   --> analytics-ingest-dlq

Queue Configuration

| Queue Name | Type | Visibility Timeout | Retention | DLQ | Max Receives | Dedup Window |

|-------------------------------|----------|--------------------|-------------|------------------------------|--------------|--------------|

| inventory-reservation.fifo | FIFO | 30s | 7 days | inventory-reservation-dlq | 5 | 5 minutes |

| payment-processing.fifo | FIFO | 60s | 7 days | payment-processing-dlq | 3 | 5 minutes |

| email-notifications | Standard | 30s | 4 days | email-notifications-dlq | 5 | N/A |

| analytics-ingest | Standard | 120s | 14 days | analytics-ingest-dlq | 10 | N/A |

Notes:

Message Envelope Schema

{
  "id": "01HV3QKZPJ5W8BXNQF2GTRDME7",
  "type": "OrderPlaced",
  "version": "1.0",
  "source": "order-service",
  "timestamp": "2024-03-15T10:30:00.000Z",
  "correlation_id": "req-7f3a9b2c-1d4e-4f5a-8c6b-9d0e1f2a3b4c",
  "payload": {
    "order_id": "ord_9f8e7d6c5b4a",
    "customer_id": "cust_1a2b3c4d",
    "items": [
      { "sku": "WIDGET-001", "quantity": 2, "unit_price_cents": 1999 }
    ],
    "subtotal_cents": 3998,
    "currency": "USD"
  },
  "metadata": {
    "retry_count": 0,
    "original_queue": null
  }
}

Note: Customer PII (name, email address) is NOT in the event payload. The email service fetches it from the customer service using customer_id. This prevents PII exposure in queue messages, DLQs, and CloudWatch logs.

Transactional Outbox Implementation

The order service cannot safely call SNS.publish() in the same request that commits the order to the database -- a crash between the two operations would lose the event or create a phantom event.

Outbox table (PostgreSQL):

CREATE TABLE outbox_events (
    id          UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    event_type  VARCHAR(100) NOT NULL,
    aggregate_id UUID NOT NULL,
    payload     JSONB NOT NULL,
    sns_topic_arn VARCHAR(200) NOT NULL,
    created_at  TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    processed_at TIMESTAMPTZ NULL,
    error_message TEXT NULL
);

CREATE INDEX idx_outbox_unprocessed
    ON outbox_events (created_at)
    WHERE processed_at IS NULL;

Order service (Python) -- within the order placement transaction:

async def place_order(conn, order_data: dict) -> str:
    async with conn.transaction():
        order_id = await conn.fetchval(
            "INSERT INTO orders (...) VALUES (...) RETURNING id",
            *order_data.values()
        )
        event_payload = build_order_placed_event(order_id, order_data)
        await conn.execute(
            """INSERT INTO outbox_events
               (event_type, aggregate_id, payload, sns_topic_arn)
               VALUES ($1, $2, $3, $4)""",
            "OrderPlaced",
            order_id,
            json.dumps(event_payload),
            os.environ["SNS_ORDER_EVENTS_ARN"]
        )
    return order_id

Outbox relay (Lambda, triggered on 5-second EventBridge schedule):

def handler(event, context):
    rows = db.execute("""
        SELECT id, payload, sns_topic_arn
        FROM outbox_events
        WHERE processed_at IS NULL
        ORDER BY created_at
        LIMIT 50
        FOR UPDATE SKIP LOCKED
    """)
    for row in rows:
        try:
            sns.publish(
                TopicArn=row["sns_topic_arn"],
                Message=row["payload"],
                MessageGroupId=json.loads(row["payload"])["payload"]["order_id"],
                MessageDeduplicationId=row["id"]
            )
            db.execute(
                "UPDATE outbox_events SET processed_at = NOW() WHERE id = $1",
                row["id"]
            )
        except Exception as e:
            db.execute(
                "UPDATE outbox_events SET error_message = $1 WHERE id = $2",
                str(e), row["id"]
            )

Saga Design: Payment + Inventory (Orchestration)

Payment and inventory reservation must be atomic at the business level. If payment fails, inventory must be released. If inventory is unavailable, payment must not be charged.

Saga type: Orchestration (dedicated Order Saga Lambda)

Steps and compensation:

Forward:
  1. ReserveInventory  --> InventoryService.reserve(order_id, items)
  2. ChargePayment     --> PaymentService.charge(order_id, amount, payment_method)
  3. ConfirmOrder      --> OrderService.confirm(order_id)

Compensation (executed in reverse):
  3. [No compensation for confirm -- emit OrderFailed event instead]
  2. RefundPayment     --> PaymentService.refund(order_id)  [idempotent: check refund_idempotency_key]
  1. ReleaseInventory  --> InventoryService.release(order_id)  [idempotent: check reservation status]

Saga state table:

CREATE TABLE order_saga_state (
    saga_id      UUID PRIMARY KEY,
    order_id     UUID NOT NULL UNIQUE,
    current_step VARCHAR(50) NOT NULL,
    status       VARCHAR(20) NOT NULL CHECK (status IN
                     ('STARTED','IN_PROGRESS','COMPLETED','COMPENSATING','FAILED')),
    payload      JSONB NOT NULL,
    created_at   TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at   TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    timeout_at   TIMESTAMPTZ NOT NULL DEFAULT NOW() + INTERVAL '30 minutes'
);

Timeout enforcement: EventBridge rule runs every 5 minutes, queries WHERE status NOT IN ('COMPLETED','FAILED') AND timeout_at < NOW(), and triggers compensation for each timed-out saga.

Idempotency Implementation (Inventory Service Example)

async def reserve_inventory(order_id: str, items: list) -> bool:
    # Idempotency check -- prevents duplicate reservation on retry
    existing = await db.fetchrow(
        "SELECT status FROM inventory_reservations WHERE order_id = $1",
        order_id
    )
    if existing:
        return existing["status"] == "RESERVED"  # Already done, return cached result

    # Attempt reservation
    async with db.transaction():
        for item in items:
            updated = await db.fetchval("""
                UPDATE inventory
                SET reserved_qty = reserved_qty + $1
                WHERE sku = $2
                  AND (available_qty - reserved_qty) >= $1
                RETURNING id
            """, item["quantity"], item["sku"])
            if not updated:
                raise InsufficientInventoryError(item["sku"])

        await db.execute("""
            INSERT INTO inventory_reservations (order_id, items, status, created_at)
            VALUES ($1, $2, 'RESERVED', NOW())
        """, order_id, json.dumps(items))

    return True

Retry & DLQ Policy

| Consumer | Error Type | Action | Max Attempts | Backoff |

|------------------|-----------------------------|-----------------|--------------|----------------------------|

| Inventory | DB connection error | Retry | 5 | Exp 1s, cap 30s, jitter 25% |

| Inventory | InsufficientInventoryError | DLQ immediately | 1 | None -- business failure |

| Payment | Stripe timeout | Retry | 3 | Exp 2s, cap 60s |

| Payment | Stripe card_declined | DLQ immediately | 1 | None -- trigger compensation |

| Email | SMTP connection error | Retry | 5 | Exp 1s, cap 120s |

| Analytics | Warehouse connection error | Retry | 10 | Exp 5s, cap 300s |

Monitoring & Alerting

| Metric | Warning | Critical | Tool |

|-------------------------------------|------------|------------|-------------------------------|

| inventory-reservation queue depth | >100 msgs | >500 msgs | CloudWatch SQS metrics |

| payment-processing queue depth | >50 msgs | >200 msgs | CloudWatch SQS metrics |

| Any DLQ depth | >0 | >10 | CloudWatch Alarm -> PagerDuty |

| Saga timeout rate (per hour) | >5 | >20 | Custom CloudWatch metric |

| Outbox relay lag (unprocessed rows) | >50 | >200 | RDS query -> CloudWatch |

| Order saga P99 completion time | >60s | >180s | X-Ray trace percentile |

Local Development Setup

# docker-compose.yml
services:
  localstack:
    image: localstack/localstack:3.2
    ports: ["4566:4566"]
    environment:
      SERVICES: sqs,sns
      DEFAULT_REGION: us-east-1
    volumes:
      - ./localstack-init:/etc/localstack/init/ready.d

  postgres:
    image: postgres:16
    environment:
      POSTGRES_DB: orders
      POSTGRES_USER: app
      POSTGRES_PASSWORD: localdev
    ports: ["5432:5432"]
# localstack-init/01-queues.sh -- runs on container start
awslocal sns create-topic --name ecommerce-order-events
awslocal sqs create-queue --queue-name inventory-reservation.fifo \
  --attributes FifoQueue=true,ContentBasedDeduplication=false
awslocal sns subscribe \
  --topic-arn arn:aws:sns:us-east-1:000000000000:ecommerce-order-events \
  --protocol sqs \
  --notification-endpoint arn:aws:sqs:us-east-1:000000000000:inventory-reservation.fifo

Implementation Notes

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.