Inferensys

Prompt

Distributed Queue Poison Message Recovery Prompt

A practical prompt playbook for SREs and data engineers using AI to analyze and recover poison messages in distributed queue systems.
Data scientist building training data pipeline on laptop, data preprocessing visible, technical workspace.
PROMPT PLAYBOOK

When to Use This Prompt

Defines the job-to-be-done, ideal user, required context, and boundaries for the poison message recovery prompt.

This prompt is for SREs and data engineers who manage distributed message queues (SQS, Kafka, RabbitMQ, Pub/Sub) and need to handle poison messages that repeatedly fail processing. A poison message is one that has exceeded a configured retry count and risks blocking a queue or being lost to a dead-letter queue (DLQ) without diagnosis. The prompt analyzes the message payload, failure history, and queue context to produce a structured recovery decision: dead-letter permanently, repair and retry, or escalate for human review. Use this when your existing retry logic has been exhausted and you need an AI-assisted triage step before automated systems make a final disposition.

The ideal user is an on-call engineer or platform operator who has been alerted to a growing DLQ backlog or a consumer group stall. They have access to the raw message body, the stack trace or error message from the last processing attempt, the retry count, and the queue configuration (max retries, visibility timeout, DLQ ARN or routing key). The prompt expects these inputs as structured context so it can reason about whether the failure is transient (repairable), permanent (dead-letter), or ambiguous (escalate). Without this context, the model cannot distinguish a schema mismatch from a downstream outage.

Do not use this prompt for real-time message processing in the hot path. It is designed for asynchronous recovery workflows where latency is acceptable and correctness matters more than speed. Do not use it when the message payload contains sensitive data that cannot be sent to an external model endpoint—redact or mask PII before invoking the prompt. Do not rely on this prompt to automatically replay messages without a human-in-the-loop gate when the recovery action is repair-and-retry; the repaired payload must be validated against the consumer's schema before re-enqueueing. Finally, do not use this prompt as a replacement for proper DLQ monitoring and alerting—it is a triage tool, not an observability platform.

PRACTICAL GUARDRAILS

Use Case Fit

Where this prompt works, where it fails, and what you must provide before using it in a production harness.

01

Good Fit: Repeated Processing Failures

Use when: A message has failed processing multiple times with deterministic errors (schema violations, poisoned payloads, missing dependencies). The prompt analyzes failure history to decide dead-letter vs. repair. Avoid when: Failures are transient (network blips, timeouts). Use a simple retry with backoff instead.

02

Bad Fit: Novel or Ambiguous Failures

Avoid when: The error is unprecedented or the failure log is empty. The prompt relies on pattern-matching against known failure signatures. Risk: Without historical context, the model may hallucinate a recovery strategy or misclassify a transient error as a poison message. Guardrail: Require a minimum failure count (≥3) before invoking this prompt.

03

Required Inputs: Failure History and Payload

Use when: You can provide the raw message payload, the full stack trace or error message from each attempt, and the retry count. Avoid when: You cannot share the payload due to PII or security constraints. Guardrail: Redact sensitive fields before passing the payload to the model, or use a local-only deployment.

04

Operational Risk: Infinite Repair Loops

Risk: The prompt suggests a repair action that also fails, creating a new poison message and an infinite loop. Guardrail: Enforce a hard retry budget in the harness. After N total attempts (original + repairs), force dead-lettering regardless of the prompt's suggestion. Log every repair attempt for audit.

05

Operational Risk: Batch Poisoning

Risk: A single poisoned message in a batch causes the entire batch to be dead-lettered or repeatedly retried, blocking healthy messages. Guardrail: The prompt must be instructed to isolate the poison message and recommend releasing the remaining healthy messages for individual reprocessing. The harness should support batch-splitting.

06

Bad Fit: Stateful Side Effects Already Applied

Avoid when: The message processing had partial success and committed irreversible side effects (e.g., sending an email, deducting inventory). Risk: A repair-and-retry could duplicate the side effect. Guardrail: The harness must check for idempotency keys or processing logs before retrying. If side effects exist, escalate for manual reconciliation instead of automated repair.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

Paste this prompt into your recovery harness to analyze a poison message and produce a strict JSON decision object.

This prompt template is the core instruction set for your poison message recovery harness. It is designed to be sent to the model after a message has exceeded its processing retry count or has been flagged by a circuit breaker. The prompt forces the model to act as an SRE analyst, evaluating the message's failure history, payload, and system context to produce one of three deterministic actions: dead-letter the message, repair and retry it, or escalate to a human operator. The output is a strict JSON object that your harness can parse and execute without ambiguity.

text
You are an SRE analyst reviewing a poison message that has repeatedly failed processing in a distributed queue.

Your task is to analyze the failure history, message payload, and system context to decide the safest recovery action.

## INPUT
- **Message Payload:** [MESSAGE_PAYLOAD]
- **Failure History (last [FAILURE_COUNT] attempts):** [FAILURE_HISTORY]
- **Queue Context:** [QUEUE_CONTEXT]
- **System Health at Time of Failures:** [SYSTEM_HEALTH_SNAPSHOT]

## CONSTRAINTS
- Do not invent missing data. If critical information is absent, note it in your reasoning.
- If the failure pattern suggests a transient infrastructure issue that has since resolved, prefer repair-and-retry.
- If the message payload is malformed, corrupt, or violates a known schema, prefer dead-letter with a clear reason.
- If the failure pattern is novel, involves data integrity risks, or you are below 90% confidence in your assessment, prefer escalation.
- To prevent batch poisoning, check if the failure pattern matches other recently dead-lettered messages. If yes, escalate immediately and recommend pausing the consumer group.

## OUTPUT_SCHEMA
Respond with a single JSON object matching this schema:
{
  "decision": "dead_letter" | "repair_retry" | "escalate",
  "confidence": 0.0-1.0,
  "reasoning": "Concise technical explanation of the failure pattern and why this decision was chosen.",
  "repair_instructions": "If decision is repair_retry, provide the exact transformation or fix to apply to the message payload before retrying. Otherwise null.",
  "escalation_reason": "If decision is escalate, explain what makes this case novel, risky, or part of a batch-poisoning pattern. Otherwise null.",
  "batch_poisoning_detected": true | false,
  "recommended_consumer_action": "If batch_poisoning_detected is true, recommend pausing or draining the consumer group. Otherwise null."
}

Before integrating this prompt into your harness, replace every square-bracket placeholder with real data from your queue system. [MESSAGE_PAYLOAD] should be the raw message body, not a summary. [FAILURE_HISTORY] must include stack traces, error codes, and timestamps for at least the last three attempts. [QUEUE_CONTEXT] should include the queue name, consumer group ID, and current queue depth. [SYSTEM_HEALTH_SNAPSHOT] should capture the state of downstream dependencies (databases, APIs, event stores) at the time of the most recent failure. After receiving the model's JSON response, validate it against the schema before acting. If the model returns invalid JSON or a decision outside the allowed enum, your harness should treat this as an escalation trigger and alert a human operator immediately.

IMPLEMENTATION TABLE

Prompt Variables

Each placeholder required by the Distributed Queue Poison Message Recovery Prompt. Use these variables to populate the prompt template, wire up your harness, and validate inputs before execution.

PlaceholderPurposeExampleValidation Notes

[MESSAGE_PAYLOAD]

The raw body of the poison message that repeatedly failed processing.

{"orderId": "ORD-9921", "amount": -50.00, "currency": "USD"}

Must be valid JSON or string. Null not allowed. Schema check against expected message contract before injection.

[FAILURE_HISTORY]

Ordered list of failure records including timestamps, error codes, and stack traces from each retry attempt.

[{"attempt": 1, "error": "InvalidAmountError", "timestamp": "2025-03-15T10:00:00Z"}, {"attempt": 2, "error": "InvalidAmountError", "timestamp": "2025-03-15T10:01:00Z"}]

Must be a non-empty array. Each record requires attempt number, error code, and timestamp. Parse check for valid ISO 8601 timestamps.

[QUEUE_NAME]

The name of the queue or topic where the poison message was detected.

order-processing-queue.fifo

Must be a non-empty string matching queue naming conventions. Regex validation against allowed queue name patterns.

[MAX_RETRY_COUNT]

The maximum number of retries configured for this queue before dead-lettering.

5

Must be a positive integer. Compare against length of [FAILURE_HISTORY] to detect infinite-loop risk. Retry budget exceeded if failure count >= max retry count.

[DLQ_NAME]

The dead-letter queue name where unrecoverable messages should be routed.

order-processing-dlq.fifo

Must be a non-empty string. Validate that DLQ exists and is writable before attempting dead-letter action. Null allowed if no DLQ configured, but triggers escalation path.

[PROCESSING_SERVICE]

Identifier for the service or handler that processes messages from this queue.

order-validation-service-v2

Must be a non-empty string. Used to correlate with deployment status and known bug databases. Validate service name against service registry.

[ESCALATION_CHANNEL]

The notification channel or endpoint for human escalation when automated recovery fails.

slack://#order-ops-oncall

Must be a valid URI or channel identifier. Parse check for supported schemes (slack, pagerduty, email, webhook). Null triggers default escalation policy.

[BATCH_POISONING_THRESHOLD]

The number of poison messages within a time window that triggers batch-poisoning detection.

10

Must be a positive integer. If poison count in window exceeds threshold, prompt must recommend batch investigation instead of per-message recovery. Validate against recent queue metrics.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the poison message recovery prompt into a production retry pipeline with validation, loop prevention, and escalation.

The poison message recovery prompt is designed to sit inside a dead-letter queue (DLQ) handler, not as a standalone chatbot. When a message exceeds the max retry count, the handler should extract the message payload, the full stack of delivery attempts, and the most recent exception or error code. This context becomes the [FAILURE_HISTORY] input. The handler then calls the LLM with the prompt template, passing the message body as [POISON_MESSAGE] and any relevant queue or service metadata as [QUEUE_CONTEXT].

Before the LLM response reaches any production actuator, you must validate the output against the expected [OUTPUT_SCHEMA]. At minimum, check that the decision field is one of the allowed enum values: dead_letter, repair_and_retry, or escalate. If repair_and_retry is selected, confirm that the repaired_payload field is present, non-empty, and parseable by the downstream message handler. Reject any response that invents a new decision value or omits required fields. Log the raw LLM response and the validation result before taking action.

Infinite-loop prevention is the most critical harness concern. Implement a poison_counter in message headers or metadata that increments each time the message passes through the repair path. If the counter exceeds a hard limit (e.g., 3 repair attempts), override the LLM decision and force escalate to a human on-call rotation. Additionally, implement a batch-poisoning guard: if more than N messages from the same queue or with the same error signature hit the DLQ within a time window, pause automated recovery and escalate the entire batch. This prevents a single bad payload shape from triggering a retry storm.

For model choice, prefer a model with strong instruction-following and structured-output capabilities. The prompt relies on strict enum adherence and conditional field requirements, which weaker models may violate. Set temperature to 0 or near-zero to minimize creative deviations. If your infrastructure supports it, use structured-output mode (e.g., JSON mode or function-calling with a strict schema) rather than relying solely on the prompt's formatting instructions. This adds a second layer of schema enforcement before your application-level validation.

Human review is required before any automated repair_and_retry action if the message payload contains personally identifiable information (PII), financial transactions, or healthcare data. In these cases, route the LLM's suggested repair to a review queue and require explicit human approval before re-enqueueing. For escalate decisions, include the full failure history, the LLM's analysis, and a link to the raw message in the escalation ticket. Never let the LLM directly mutate production databases or state stores without a human-approved action boundary.

IMPLEMENTATION TABLE

Expected Output Contract

Fields, types, and validation rules for the poison message recovery decision. Use this contract to parse and validate the model response before executing any repair or dead-letter action in your queue consumer harness.

Field or ElementType or FormatRequiredValidation Rule

decision

enum: dead_letter | repair_retry | escalate

Must be exactly one of the three allowed values. Reject any other string.

repair_instructions

object

true when decision is repair_retry, else null

If repair_retry, must contain action and payload fields. If dead_letter or escalate, must be null.

repair_instructions.action

string

true when repair_instructions is present

Must be a non-empty string describing the specific repair operation. Reject empty or whitespace-only strings.

repair_instructions.payload

object

true when repair_instructions is present

Must be a valid JSON object containing the repaired message body. Schema must match the original message schema for the queue.

escalation_reason

string

true when decision is escalate

Must be a non-empty string explaining why automated recovery is not possible. Must not exceed 500 characters.

dead_letter_reason

string

true when decision is dead_letter

Must be a non-empty string explaining why the message is unrecoverable. Must not exceed 500 characters.

retry_count_recommendation

integer

If present, must be an integer between 1 and [MAX_RETRY_LIMIT]. If absent, the harness default applies.

confidence_score

number

If present, must be a float between 0.0 and 1.0. Values below [CONFIDENCE_THRESHOLD] should trigger human review before executing the decision.

PRACTICAL GUARDRAILS

Common Failure Modes

Poison message recovery prompts fail in predictable ways under production load. These are the most common failure modes and the guardrails that prevent them.

01

Infinite Retry Loop on Unrepairable Messages

What to watch: The prompt repeatedly suggests 'repair-and-retry' for messages with permanently corrupted payloads or missing required fields, causing the message to cycle between the dead-letter queue and the processor indefinitely. Guardrail: Enforce a hard max_retry_count in the harness, not the prompt. After N attempts, force a dead-letter decision regardless of the model's suggestion.

02

Batch Poisoning from a Single Malformed Message

What to watch: A single poison message causes the model to recommend batch-level actions (e.g., 'reprocess the entire batch') or contaminates the context window for subsequent messages in the same batch. Guardrail: Process poison messages one-at-a-time in the recovery path. Never include sibling messages in the recovery prompt context. Validate that the output decision applies only to the target message ID.

03

Loss of Original Message Context During Repair

What to watch: The prompt generates a 'repaired' payload that drops critical fields, reorders array elements, or normalizes values in ways that break downstream consumers. Guardrail: Require the prompt to output a diff or patch structure rather than a full replacement payload. Validate that all original top-level keys are preserved in the repaired output before re-enqueueing.

04

Escalation Without Actionable Context

What to watch: The prompt escalates to a human operator but provides only a vague summary ('message failed processing') without the failure history, stack trace, or payload excerpt needed to diagnose the issue. Guardrail: Require the escalation output to include failure_history, last_error_message, payload_preview, and attempt_count. Validate these fields are non-empty before routing to the on-call queue.

05

Model Hallucinates a Repair That Passes Validation but Breaks Semantics

What to watch: The model generates a syntactically valid payload that passes schema checks but changes the business meaning—e.g., altering an amount field, swapping from/to addresses, or fabricating a plausible customer_id. Guardrail: Add a semantic_invariants block to the prompt listing fields that must not change. Run a pre- and post-repair diff on those fields and dead-letter if any invariant is violated.

06

Retry Storm from Transient Infrastructure Errors

What to watch: The prompt treats all failures as message-level problems and recommends repair for transient errors (network timeouts, database connection pools exhausted, rate limits) that would succeed on retry without modification. Guardrail: Classify the error type before invoking the recovery prompt. Route transient errors to a simple retry-with-backoff path. Only invoke the poison-message recovery prompt for deterministic failures (validation errors, schema mismatches, data integrity violations).

IMPLEMENTATION TABLE

Evaluation Rubric

Criteria for testing the Distributed Queue Poison Message Recovery Prompt before production deployment. Each row defines a pass standard, a failure signal, and a concrete test method to validate output quality and safety.

CriterionPass StandardFailure SignalTest Method

Disposition Decision Validity

Output contains exactly one of three valid dispositions: dead-letter, repair-and-retry, or escalate. Disposition matches the failure pattern described in [FAILURE_HISTORY].

Output proposes an invalid disposition, proposes multiple conflicting dispositions, or selects a disposition that contradicts documented failure patterns (e.g., dead-letter for a transient network timeout).

Schema check: parse output field disposition and assert value is in enum {dead-letter, repair-and-retry, escalate}. Run 10 golden cases with known failure patterns and assert disposition matches expected label.

Repair Instruction Completeness

When disposition is repair-and-retry, output includes a concrete, executable repair instruction in [REPAIR_INSTRUCTION] that references specific fields from [MESSAGE_PAYLOAD] and corrects the root cause identified in [FAILURE_HISTORY].

Repair instruction is missing, is a generic restatement of the error without a corrective action, or references fields not present in the message payload.

Parse [REPAIR_INSTRUCTION] field. Assert it is non-null when disposition is repair-and-retry. Validate that all referenced field paths exist in the input [MESSAGE_PAYLOAD] schema. Run repair instruction through a dry-run validator that checks for actionable verbs (e.g., transform, replace, set).

Infinite Loop Prevention

Output includes a [RETRY_COUNT_CHECK] field that evaluates whether the message has exceeded [MAX_RETRY_THRESHOLD]. If retry count exceeds threshold, disposition must be dead-letter or escalate, never repair-and-retry.

Output recommends repair-and-retry when [RETRY_COUNT] in [FAILURE_HISTORY] exceeds [MAX_RETRY_THRESHOLD], or [RETRY_COUNT_CHECK] field is missing or evaluates to an incorrect boolean.

Assert that when input [FAILURE_HISTORY].retry_count > [MAX_RETRY_THRESHOLD], output disposition is not repair-and-retry. Assert [RETRY_COUNT_CHECK] field is present and is a boolean matching the threshold comparison.

Batch Poisoning Avoidance

Output includes a [BATCH_POISONING_RISK] assessment. If the failure pattern indicates a systemic issue (e.g., schema mismatch, upstream data corruption), the assessment flags high risk and disposition must be dead-letter or escalate to prevent blocking the entire queue.

Output recommends repair-and-retry for a systemic failure that would affect all messages in the batch, or [BATCH_POISONING_RISK] assessment is missing or incorrectly flags low risk for a systemic pattern.

Inject test cases with systemic failure signatures (e.g., all messages failing with same schema error). Assert [BATCH_POISONING_RISK] is high and disposition is not repair-and-retry. Assert the assessment references the systemic pattern from [FAILURE_HISTORY].

Escalation Context Quality

When disposition is escalate, output includes an [ESCALATION_CONTEXT] object with a concise failure summary, the original [MESSAGE_ID], the [FAILURE_HISTORY] summary, and a recommended [ESCALATION_TARGET] (e.g., on-call, data-engineering, upstream-owner).

Escalation context is missing, omits the message ID, contains an overly verbose or unactionable summary, or fails to recommend a specific escalation target.

Parse [ESCALATION_CONTEXT] object. Assert required fields are present: summary, message_id, failure_summary, escalation_target. Assert summary length is under 500 characters. Validate escalation_target is a non-empty string.

Dead-Letter Metadata Preservation

When disposition is dead-letter, output includes a [DEAD_LETTER_METADATA] object containing the original [MESSAGE_ID], [FAILURE_HISTORY], the reason for dead-lettering, and a timestamp. This ensures the message can be audited or reprocessed later.

Dead-letter metadata is missing, omits the failure history, or lacks a clear reason string explaining why the message was dead-lettered rather than repaired or escalated.

Parse [DEAD_LETTER_METADATA] object. Assert required fields: message_id, failure_history, dead_letter_reason, dead_lettered_at. Assert dead_letter_reason is a non-empty string that references specific failures from [FAILURE_HISTORY].

Output Schema Compliance

Output is valid JSON matching the expected schema: top-level fields include disposition, repair_instruction, retry_count_check, batch_poisoning_risk, escalation_context, dead_letter_metadata. All required fields for the chosen disposition are present and non-null.

Output is not valid JSON, is missing top-level fields, contains null values for fields required by the chosen disposition, or includes extra fields that violate the output contract.

Validate output against JSON Schema. Assert parse succeeds. For each disposition value, assert that the corresponding required fields are present and non-null. Assert no unexpected top-level fields are present.

Failure History Grounding

Every claim in the output (repair instruction, escalation summary, dead-letter reason) is grounded in specific entries from [FAILURE_HISTORY]. The output does not invent failure modes not present in the input.

Output references a failure mode, error code, or stack trace not present in [FAILURE_HISTORY], or makes a generic recommendation without citing specific failure entries.

Extract all error codes, exception types, and failure descriptions from output. Assert each is a substring match or semantic match to content in [FAILURE_HISTORY]. Flag any novel failure descriptions as hallucination.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Start with the base prompt and a lightweight harness that reads a dead-letter queue JSON file. Use a single model call per message with no retry loop. Focus on getting the classification decision (dead-letter, repair-and-retry, escalate) correct before adding infrastructure.

Strip the prompt down to:

  • [MESSAGE_PAYLOAD]
  • [FAILURE_HISTORY] (last 3 attempts)
  • [QUEUE_METADATA]
  • Decision output: {"action": "dead_letter" | "repair" | "escalate", "reasoning": "..."}

Watch for

  • The model classifying every poison message as escalate because it's the safest default
  • Missing the distinction between transient failures (network timeout) and permanent failures (schema violation)
  • No loop detection—if you accidentally feed the same message back, the model won't catch it
  • Overly verbose reasoning that costs tokens without improving decisions
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.