Inferensys

Prompt

Dead Letter Queue Message Replay Decision Prompt

A practical prompt playbook for using Dead Letter Queue Message Replay Decision Prompt in production AI workflows.
Developer doing prompt engineering on laptop, prompt variations visible on screen, casual coding session.
PROMPT PLAYBOOK

When to Use This Prompt

A practical guide for SREs and distributed systems engineers to automate dead letter queue triage using an LLM-driven replay-or-discard decision.

This prompt is designed for distributed systems engineers and SRE teams who need to automate the triage of messages that have landed in a dead letter queue (DLQ) after exhausting all configured retries. The core job-to-be-done is to replace manual, repetitive inspection of failed messages with a structured, consistent, and auditable decision process. The ideal user is a platform engineer building an automated recovery harness who needs the model to analyze a message's payload, its error context, and the system's current state to produce a clear, actionable classification: replay this message to its original destination, route it to a fallback handler, or permanently discard it as a poison message. This prompt is appropriate when you have a backlog of DLQ messages, need to enforce a consistent root cause taxonomy, and want to safely automate the routing of replayable messages back into processing pipelines.

You should use this prompt only when the necessary context has already been extracted and provided to the model. The prompt assumes you are feeding it a pre-fetched message payload, structured error metadata (such as the exception type, stack trace, and retry count), and relevant system state (like downstream service health or circuit breaker status). It is not designed for real-time stream processing or for making decisions without this context. Do not use this prompt when the failure mode involves a fundamental data corruption that requires upstream producer fixes, when the message payload contains sensitive data that cannot be sent to an LLM, or when the replay action itself is unsafe due to a lack of idempotency guarantees in the target handler. The prompt's value is in standardizing the triage logic, not in executing the replay, which must be handled by your application harness.

Before integrating this prompt, you must establish clear operational boundaries. The LLM's output is a decision recommendation, not an executed action. Your harness should parse the structured output, validate the decision against a set of hardcoded safety rules (e.g., never replay a message that has already been replayed more than a configured maximum), and log the decision for auditability. For high-risk systems, implement a human-in-the-loop review step for any decision classified as UNCERTAIN or for messages above a certain value threshold. The next step after reading this section is to review the prompt template, adapt the placeholders to your specific error taxonomy and system architecture, and design the validation harness that will act on the model's structured output.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Dead Letter Queue Message Replay Decision Prompt works and where it introduces risk. Use these cards to decide if this prompt fits your operational context.

01

Good Fit: Poison Message Detection

Use when: messages have exhausted all configured retries and you need a structured root-cause classification (e.g., malformed payload, schema violation, business rule conflict). Guardrail: The prompt must output a deterministic replay_strategy enum (REPLAY, DISCARD, ESCALATE) to prevent ambiguous routing.

02

Bad Fit: Real-Time Ordering Guarantees

Avoid when: strict FIFO ordering is required and replaying a single message could violate causal consistency. Guardrail: The prompt should include an ordering_dependency check that flags messages with sequence numbers or session IDs before recommending a replay action.

03

Required Inputs: Payload and Error History

Use when: you can provide the raw message payload, the full stack of delivery errors, and the retry count. Guardrail: The prompt template must require [MESSAGE_PAYLOAD], [ERROR_HISTORY], and [RETRY_COUNT] as mandatory inputs; missing fields should trigger an ESCALATE decision.

04

Operational Risk: Replay Amplification

Risk: blindly replaying a message that caused a downstream side effect (e.g., duplicate charge, double provision) can amplify damage. Guardrail: The prompt must inspect an idempotency_key field and recommend DISCARD if a duplicate is detected, with a human review flag for financial operations.

05

Operational Risk: Infinite Replay Loops

Risk: a misclassified message re-enters the queue and exhausts retries again, creating a silent loop. Guardrail: The prompt output must include a max_replay_count field, and the harness must enforce a dead-letter re-entry counter that escalates after one replay attempt.

06

Bad Fit: Low-Latency Decision Paths

Avoid when: the DLQ consumer requires sub-second decision latency and an LLM call would violate the processing SLO. Guardrail: Use this prompt for offline or asynchronous DLQ inspection; pair it with a deterministic rule engine for the hot path and reserve the LLM for ambiguous cases.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A copy-ready prompt for making a replay-or-discard decision on a dead letter queue message, including root cause classification and destination routing.

The prompt below is designed to be pasted directly into your DLQ analysis harness. It instructs the model to act as a distributed systems reliability engineer, analyzing a message that has exhausted its retry budget. The model must produce a structured decision, not just a summary. All dynamic values are represented as square-bracket placeholders, such as [MESSAGE_PAYLOAD], [ERROR_CONTEXT], and [QUEUE_CONFIG]. Replace these with actual data from your message broker and monitoring systems before sending the prompt.

text
You are a distributed systems reliability engineer analyzing a message that has been moved to a dead letter queue (DLQ). Your task is to determine whether the message should be replayed or discarded, and to provide a detailed justification.

## Input Data

**Message Payload:**
```json
[MESSAGE_PAYLOAD]

Error Context:

  • Original Queue: [ORIGINAL_QUEUE_NAME]
  • Error Message: [ERROR_MESSAGE]
  • Error Code/Type: [ERROR_TYPE]
  • Retry Attempts Exhausted: [RETRY_COUNT]
  • Timestamp of Last Failure: [LAST_FAILURE_TIMESTAMP]

System Context:

  • Consumer Group ID: [CONSUMER_GROUP_ID]
  • Downstream Service Health Status: [DOWNSTREAM_SERVICE_HEALTH]
  • Recent Deployment Events: [RECENT_DEPLOYMENT_EVENTS]
  • Message Ordering Requirements: [ORDERING_REQUIREMENTS]

Decision Criteria

  1. Poison Message Detection: Is the message itself malformed, containing invalid data that will never be processable (e.g., a missing required field, a foreign key that will never exist)?
  2. Transient vs. Persistent Error: Is the error likely temporary (e.g., a network timeout, a brief service overload) or permanent (e.g., an unrecoverable data corruption, a business rule violation)?
  3. Downstream Impact: What is the blast radius of replaying this message? Could it cause duplicate processing, violate ordering guarantees, or overload a struggling downstream service?
  4. Business Criticality: What is the importance of the data in this message? Can it be safely discarded, or does it represent a critical business event that must be processed?

Output Schema

Respond with a single, valid JSON object conforming to this schema:

json
{
  "decision": "REPLAY | DISCARD | MANUAL_REVIEW",
  "root_cause_classification": "POISON_MESSAGE | TRANSIENT_ERROR | PERSISTENT_ERROR | DEPENDENCY_FAILURE | UNKNOWN",
  "confidence_score": 0.0-1.0,
  "justification": "A concise, evidence-based explanation for the decision.",
  "replay_instructions": {
    "destination_queue": "[ORIGINAL_QUEUE_NAME | A_DIFFERENT_QUEUE_NAME]",
    "required_preconditions": ["A list of conditions that must be met before replaying, e.g., 'Deploy fix v1.2.3', 'Confirm downstream service health'"]
  },
  "discard_impact": "A brief statement of what data or business event will be lost if discarded.",
  "manual_review_reason": "If decision is MANUAL_REVIEW, explain why automated resolution is unsafe."
}

Constraints

  • Base your decision strictly on the provided Input Data. Do not invent external facts.
  • If the error context indicates a 4xx client error (excluding 429), strongly consider POISON_MESSAGE.
  • If the error context indicates a 5xx server error or a 429 rate limit, strongly consider TRANSIENT_ERROR.
  • If ORDERING_REQUIREMENTS is true, your replay instructions must address ordering guarantees.
  • If confidence_score is below 0.8, the decision must be MANUAL_REVIEW.

To adapt this template, start by mapping your DLQ metadata fields to the placeholders. The [MESSAGE_PAYLOAD] should be the full message body, serialized as a JSON string. The [ERROR_CONTEXT] fields should be pulled from your message broker's headers or your application's error logs. The most critical adaptation is the Decision Criteria section; you should update this to reflect your organization's specific operational policies, such as known poison message signatures or business-critical event types. After adapting, test the prompt against a golden dataset of 20-30 historical DLQ messages with known correct decisions to calibrate the confidence_score threshold and ensure the model's reasoning aligns with your team's judgment.

IMPLEMENTATION TABLE

Prompt Variables

Inputs the Dead Letter Queue Message Replay Decision Prompt needs to work reliably. Validate each before sending.

PlaceholderPurposeExampleValidation Notes

[MESSAGE_PAYLOAD]

The raw message body that failed processing

{"orderId": "ORD-123", "amount": 99.95, "currency": "USD"}

Must be valid JSON or parseable string. Check for truncation, encoding errors, or empty payload. Reject if null or exceeds max payload size.

[MESSAGE_HEADERS]

Metadata including message ID, enqueue timestamp, retry count, and source system

{"messageId": "msg-abc", "retryCount": 5, "source": "payment-service", "enqueuedAt": "2025-01-15T10:30:00Z"}

Must contain messageId and retryCount fields. retryCount must be a non-negative integer. Validate timestamp format is ISO 8601. Reject if headers are missing or unparseable.

[ERROR_HISTORY]

Ordered list of error codes, messages, and timestamps from each failed processing attempt

[{"attempt": 1, "errorCode": "TIMEOUT", "message": "DB connection timeout", "timestamp": "2025-01-15T10:30:05Z"}, {"attempt": 2, "errorCode": "VALIDATION_ERROR", "message": "Field 'amount' type mismatch", "timestamp": "2025-01-15T10:30:10Z"}]

Must be a non-empty array. Each entry requires attempt number, errorCode, and timestamp. Check for duplicate attempt numbers or gaps in sequence. Validate errorCode against known taxonomy.

[DLQ_CONFIG]

Dead letter queue configuration including max retries, replay destination, and poison message detection rules

{"maxRetries": 5, "replayQueue": "orders.replay", "poisonPatterns": ["VALIDATION_ERROR", "SCHEMA_MISMATCH"], "orderingGuarantee": true}

Must specify maxRetries and replayQueue. poisonPatterns must be an array of error code strings. orderingGuarantee must be boolean. Validate replayQueue exists in routing table. Reject if maxRetries is less than current retry count.

[ORDERING_CONTEXT]

Information about message ordering dependencies, sequence numbers, and sibling message states

{"sequenceNumber": 42, "groupId": "order-ORD-123", "precedingMessageStatus": "completed", "siblingMessagesPending": 0}

Required when orderingGuarantee is true. sequenceNumber must be a positive integer. precedingMessageStatus must be one of: completed, failed, pending, unknown. siblingMessagesPending must be a non-negative integer. Validate groupId matches payload correlation ID.

[DESTINATION_ROUTES]

Available replay destinations with capacity, latency profiles, and routing rules

[{"queueName": "orders.replay", "status": "available", "currentDepth": 120, "maxDepth": 1000}, {"queueName": "orders.dead", "status": "available", "currentDepth": 45, "maxDepth": 500}]

Must be a non-empty array. Each route requires queueName, status, currentDepth, and maxDepth. status must be one of: available, full, unavailable. Validate currentDepth does not exceed maxDepth. Reject if no route has status 'available'.

[POISON_MESSAGE_RULES]

Criteria for classifying a message as poison: unrecoverable payload corruption, schema violations, or business rule conflicts

{"unrecoverablePatterns": ["SCHEMA_MISMATCH", "DATA_CORRUPTION"], "maxConsecutiveIdenticalErrors": 3, "requireHumanReview": true}

unrecoverablePatterns must be an array of error codes matching ERROR_HISTORY entries. maxConsecutiveIdenticalErrors must be a positive integer. requireHumanReview must be boolean. Validate that poison classification triggers when consecutive identical errors exceed threshold.

[REPLAY_DECISION_SCHEMA]

Expected output schema for the replay-or-discard decision

{"decision": "replay|discard|escalate", "destination": "orders.replay", "rootCause": "TRANSIENT_TIMEOUT", "confidence": 0.92, "reasoning": "Timeout on attempt 1, subsequent validation errors suggest payload intact. Replay safe."}

decision must be one of: replay, discard, escalate. destination must match a route in DESTINATION_ROUTES when decision is replay. rootCause must be a non-empty string. confidence must be a float between 0.0 and 1.0. reasoning must be a non-empty string. Reject if decision is replay but destination is null.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Dead Letter Queue Message Replay Decision Prompt into an operational workflow with validation, routing, and safety checks.

This prompt is designed to be the decision engine within a dead letter queue (DLQ) replay harness, not a standalone chatbot. The application layer is responsible for fetching the message payload, metadata, and relevant system state, then assembling the prompt with these concrete values. The model's structured output—a replay-or-discard decision with root cause classification—must be parsed and enforced by the harness. Never allow the raw model output to directly trigger a replay action without validation against the system's own rules for ordering guarantees, idempotency, and poison message detection.

The implementation loop should follow a strict sequence: (1) Dequeue a batch of messages from the DLQ. (2) For each message, extract the message_body, error_stack, retry_count, queue_name, and timestamp. (3) Populate the prompt's [MESSAGE_PAYLOAD], [ERROR_CONTEXT], [RETRY_METADATA], and [QUEUE_CONTEXT] placeholders. (4) Call the model with temperature=0 and a structured output mode (e.g., JSON mode or function calling) to enforce the [OUTPUT_SCHEMA]. (5) Parse the decision field. If replay, validate that the destination_queue is not the original DLQ source and that the replay_priority is within acceptable bounds. If discard, log the discard_reason and root_cause_classification to your observability platform before archiving or permanently deleting the message. (6) Implement a hard circuit breaker: if the same message ID appears in the DLQ more than a configured threshold (e.g., 3 times), bypass the model and force a discard with a poison_message classification to prevent infinite replay loops.

For high-risk systems where message ordering or exactly-once processing is critical, insert a human approval step before replaying any message classified as ordering_risk or duplicate_potential. The harness should route these decisions to a review queue with the full prompt context and model reasoning attached. Additionally, instrument the harness with metrics: dlq_replay_decision_total (by decision type), dlq_model_latency_seconds, and dlq_circuit_breaker_activated_total. These metrics will surface when the model is adding latency, making poor decisions, or when the system is experiencing a poison message storm. Use a lightweight model (e.g., a fast instructor-tuned variant) to keep replay latency low; this is an operational decision, not a deep analysis task.

IMPLEMENTATION TABLE

Expected Output Contract

Fields, types, and validation rules for the Dead Letter Queue Message Replay Decision Prompt response. Use this contract to parse and validate the model output before executing any replay or discard action.

Field or ElementType or FormatRequiredValidation Rule

decision

enum: REPLAY | DISCARD | ESCALATE

Must be exactly one of the three allowed values. Any other value triggers a retry or fallback to ESCALATE.

root_cause_classification

enum: POISON_MESSAGE | TRANSIENT_ERROR | ORDERING_VIOLATION | SCHEMA_MISMATCH | DEPENDENCY_FAILURE | UNKNOWN

Must match one of the defined categories. UNKNOWN is allowed only when evidence is insufficient; must be accompanied by confidence below threshold.

confidence

number between 0.0 and 1.0

Parse as float. Must be within [0.0, 1.0]. If confidence < [CONFIDENCE_THRESHOLD], the harness must escalate for human review regardless of decision field.

destination_queue

string or null

Required when decision is REPLAY. Must match pattern ^[a-zA-Z0-9_-]+$ and exist in [VALID_QUEUE_LIST]. Null allowed when decision is DISCARD or ESCALATE.

payload_inspection_summary

string

Must be non-empty. Length must not exceed [MAX_SUMMARY_LENGTH] characters. Must reference specific fields from [PAYLOAD] that informed the decision.

ordering_guarantee_preserved

boolean

Required when decision is REPLAY. Must be true if the message has a sequence marker and replay would violate ordering. Harness must cross-check against [SEQUENCE_MARKER] if present.

poison_message_detected

boolean

Must be true if root_cause_classification is POISON_MESSAGE. Harness must verify that the payload contains a structural or semantic defect that cannot be resolved by retry.

escalation_reason

string or null

Required when decision is ESCALATE. Must describe why automated replay or discard is unsafe. Null allowed for REPLAY and DISCARD decisions.

PRACTICAL GUARDRAILS

Common Failure Modes

Production failures in DLQ replay decisions often stem from ambiguous classification, missing context, or unsafe automation. These cards cover the most common breakages and how to prevent them before a bad replay reaches production.

01

Poison Message Misclassification

What to watch: The prompt classifies a permanently malformed payload as a transient error and recommends replay, creating an infinite loop. This happens when the model cannot distinguish between a fixable schema mismatch and a corrupted body. Guardrail: Require the prompt to output a poison_message boolean flag. If true, the harness must route to a dead-letter storage bucket and block all replay attempts without human review.

02

Ordering Guarantee Violation

What to watch: The prompt recommends replaying a message without checking whether its processing depends on a prior message that was never acknowledged. This breaks exactly-once processing and entity state. Guardrail: Include the last acknowledged sequence number or entity version in the prompt context. Add a validation rule that rejects replay if the message's expected predecessor is not in the completed set.

03

Root Cause Hallucination

What to watch: The model confidently invents a root cause (e.g., 'database deadlock') when the error metadata is sparse or missing, leading the operator to apply an irrelevant fix. Guardrail: Constrain the output to only classify from a closed enum of known error categories. If confidence is low, force the root_cause field to unclassified and escalate for human triage.

04

Payload Inspection Blindness

What to watch: The prompt makes a decision based only on headers and error codes without inspecting the message body for semantic corruption, such as a negative quantity or a null customer ID. Guardrail: Explicitly instruct the prompt to extract and validate 3-5 critical business fields from the payload. If any field violates a schema constraint, the decision must be discard or quarantine, never replay.

05

Destination Routing Drift

What to watch: The prompt routes the message to a queue or topic that no longer exists or has incompatible schema registries, causing an immediate re-failure. Guardrail: Provide a current list of valid destination topics and their schema versions in the prompt context. Add a post-generation validation step that rejects any destination not present in the provided list.

06

Unbounded Retry Budget Consumption

What to watch: The prompt recommends a retry without considering the global retry budget or SLO burn rate, allowing a single bad message to consume all available retries. Guardrail: Include the current retry budget remaining and the message's retry count in the prompt. Add a hard rule: if the retry count exceeds a threshold or the budget is below 10%, the only allowed decisions are quarantine or escalate.

IMPLEMENTATION TABLE

Evaluation Rubric

Use these criteria to test the Dead Letter Queue Message Replay Decision Prompt before production deployment. Each row defines a pass standard, a failure signal, and a concrete test method.

CriterionPass StandardFailure SignalTest Method

Root Cause Classification

Output includes exactly one root cause from the allowed enum: [POISON_MESSAGE], [TRANSIENT_ERROR], [SCHEMA_MISMATCH], [ORDERING_VIOLATION], [DEPENDENCY_FAILURE], [UNKNOWN]

Missing root cause field, multiple root causes selected, or value outside allowed enum

Schema validation against enum constraint; spot-check 20 classified messages for single-selection compliance

Replay Decision Binary

[DECISION] field is exactly REPLAY or DISCARD with no hedging language or conditional modifiers

Decision contains qualifiers like 'maybe', 'if', or 'retry with changes'; decision field missing or null

Regex match for exact REPLAY|DISCARD; manual review of 10 edge-case payloads for hedging language

Poison Message Detection

When payload contains non-retryable corruption (malformed body, unrecoverable schema violation), decision is DISCARD with [POISON_MESSAGE] classification

Poison message receives REPLAY decision or classification is [TRANSIENT_ERROR] instead of [POISON_MESSAGE]

Inject 5 deliberately malformed payloads with truncated JSON, binary garbage, and missing required fields; verify DISCARD + POISON_MESSAGE

Ordering Guarantee Preservation

When [ORDERING_VIOLATION] is classified, output includes [SEQUENCE_GAP_DETECTED]: true and [LAST_GOOD_SEQUENCE_NUMBER] populated

Ordering violation classified but sequence gap fields missing, null, or false when gap exists

Feed message with sequence number 1007 when last processed was 1004; verify gap detection and correct last-good value

Destination Routing Instruction

[DESTINATION] field contains exactly one valid target: [PRIMARY_QUEUE], [DEAD_LETTER_QUEUE], [OBSERVATION_QUEUE], or [NULL_SINK]

Destination is empty, contains multiple targets, or references undefined queue names

Schema check for allowed enum values; verify DISCARD decisions route to NULL_SINK or DEAD_LETTER_QUEUE, not PRIMARY_QUEUE

Payload Inspection Evidence

[EVIDENCE] array contains at least one concrete observation from the message payload or error metadata supporting the classification

Evidence array is empty, contains only generic statements like 'message failed', or hallucinates fields not present in input

Compare evidence strings against input payload fields; flag any claim referencing data absent from the provided message

Retry Budget Exhaustion Handling

When [RETRY_COUNT] >= [MAX_RETRIES], decision is DISCARD regardless of error type unless [OVERRIDE_REASON] is populated with explicit justification

Message with exhausted retries receives REPLAY without override justification

Feed message with RETRY_COUNT=5 and MAX_RETRIES=5; verify DISCARD unless override present; test 3 override scenarios for valid justification format

Output Schema Completeness

All required fields present: [DECISION], [ROOT_CAUSE], [DESTINATION], [EVIDENCE], [CONFIDENCE_SCORE]; optional fields populated when relevant

Required field missing or null; confidence score outside 0.0-1.0 range

JSON schema validation against output contract; verify confidence score is float between 0 and 1 inclusive

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a single message and a simplified schema. Focus on root cause classification and a binary replay/discard decision. Skip ordering-guarantee checks and destination routing logic.

  • Replace [OUTPUT_SCHEMA] with a flat JSON object: {"decision": "replay|discard", "root_cause": "string", "reasoning": "string"}
  • Set [CONSTRAINTS] to: "Respond only with the JSON object."
  • Omit [ORDERING_CONTEXT] and [DESTINATION_ROUTING_RULES] placeholders.

Watch for

  • Overly broad root cause classifications that miss poison-message patterns.
  • No validation of the output schema, leading to downstream parse errors.
  • Treating all failures as transient, causing infinite replay loops.
Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.