Inferensys

Prompt

Retry and Timeout Behavior Test Prompt

A practical prompt playbook for SREs and backend engineers using AI to generate test scenarios for retry logic, timeout configurations, and backoff strategies from code analysis.
Finance professional using AI FP&A copilot on laptop, board presentation visible on screen, home office work session.
PROMPT PLAYBOOK

When to Use This Prompt

Define the job, reader, and constraints for generating resilience test scenarios from production retry and timeout code.

This prompt is built for SREs and backend engineers who need to validate resilience patterns directly from production source code. The job-to-be-done is turning raw code snippets containing retry logic, timeout configurations, and backoff strategies into structured, actionable test scenarios. The ideal user is someone who can provide the relevant code blocks and a map of service dependencies, and who needs to expose idempotency violations, cascading failure risks, and misconfigured timeout chains before they cause incidents. The required context includes the code under review, the service dependency graph, and any known infrastructure-level retry behavior that might interact with application-level logic.

Do not use this prompt for general unit test generation or for systems where retry behavior is handled entirely by infrastructure layers outside the codebase, such as a service mesh or API gateway that manages retries transparently. It is also not suitable for generating load tests, performance benchmarks, or security fuzzing inputs. The prompt assumes that retry and timeout logic is visible in the application code and that the reader can articulate the expected failure modes of downstream dependencies. If the codebase uses a library or framework that abstracts retry behavior, provide the configuration or decorator usage rather than expecting the model to infer it from imports alone.

Before running this prompt, gather the relevant code snippets, identify the service boundaries, and document any known idempotency guarantees or lack thereof. The output will be a structured test plan, not a passing test suite. You will need to implement the scenarios in your testing framework and validate them against your actual infrastructure. For high-risk systems where retry misbehavior could cause data corruption or financial impact, always include a human review step before executing generated test scenarios in production-like environments.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Retry and Timeout Behavior Test Prompt delivers value and where it introduces risk.

01

Strong Fit: Backend Service Hardening

Use when: you have service code with configurable retry logic, exponential backoff, or circuit breakers and need to verify resilience against transient failures. Guardrail: Pin the prompt to specific function signatures or configuration blocks to avoid generating tests for unrelated code paths.

02

Strong Fit: Idempotency Verification

Use when: operations must be safe to retry without duplicate side effects. The prompt excels at generating scenarios that detect missing idempotency keys, non-idempotent state mutations, or duplicate processing. Guardrail: Require the output to map each test case to a specific code location where idempotency is expected.

03

Poor Fit: Pure Infrastructure Testing

Avoid when: the resilience behavior is defined entirely in infrastructure configuration (service mesh, ingress, load balancer) rather than application code. The prompt analyzes code, not YAML configs or Terraform. Guardrail: Use this prompt only when retry or timeout logic exists in the repository's application source code.

04

Required Input: Code with Retry Primitives

What to watch: The prompt cannot invent retry scenarios for code that lacks retry, timeout, or backoff constructs. Running it on vanilla HTTP clients or database calls without resilience wrappers produces low-value or speculative output. Guardrail: Pre-scan the target code for libraries like tenacity, retry, axios-retry, Polly, or custom retry decorators before invoking the prompt.

05

Operational Risk: Cascading Failure Blindness

What to watch: The prompt may generate tests that verify local retry correctness but miss systemic cascading failure risks—such as retry storms, thundering herd on backoff reset, or downstream overload from synchronized retry schedules. Guardrail: Supplement prompt output with a manual review step that checks for cross-service retry alignment and jitter configuration.

06

Operational Risk: Mock-Heavy Test Fragility

What to watch: Generated tests may rely heavily on mocked clocks, mocked network failures, or mocked service responses that drift from real system behavior over time. Guardrail: Require at least one integration-level test scenario that exercises actual timeout boundaries against a real or containerized dependency, not just unit-level mocks.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt template for generating retry, timeout, and backoff test scenarios from code analysis, ready to be adapted with your specific repository context and resilience requirements.

This template is designed to be copied directly into your AI coding agent or test generation pipeline. It instructs the model to analyze retry logic, timeout configurations, and backoff strategies in your codebase and produce structured test scenarios that expose idempotency violations, cascading failure risks, and misconfigured resilience patterns. Replace each square-bracket placeholder with your specific context before use.

code
You are a resilience testing engineer analyzing retry, timeout, and backoff behavior in a production codebase. Your task is to generate structured test scenarios that validate the correctness and safety of resilience patterns.

## INPUT
Source code files to analyze:
[CODE_FILES]

Configuration files containing timeout and retry settings:
[CONFIG_FILES]

Dependency graph or service topology:
[SERVICE_DEPENDENCY_MAP]

Existing test patterns to follow:
[EXISTING_TEST_EXAMPLES]

## CONSTRAINTS
- Target language and test framework: [TEST_FRAMEWORK]
- Maximum test execution time per scenario: [MAX_EXECUTION_TIME_MS]ms
- Required coverage: all retry paths, timeout boundaries, backoff strategies, and circuit breaker states
- Do not generate tests that require external network access
- Tests must be deterministic and repeatable
- Flag any idempotency concerns with severity HIGH, MEDIUM, or LOW

## OUTPUT_SCHEMA
Return a JSON array of test scenarios with this structure:
{
  "scenarios": [
    {
      "scenario_id": "string",
      "category": "retry | timeout | backoff | circuit_breaker | idempotency",
      "target_function_or_endpoint": "string",
      "description": "string",
      "preconditions": ["string"],
      "test_input": "object describing input or trigger",
      "expected_behavior": "string",
      "assertions": ["string"],
      "failure_mode_tested": "string",
      "idempotency_risk": "HIGH | MEDIUM | LOW | NONE",
      "cascading_failure_risk": "HIGH | MEDIUM | LOW | NONE",
      "test_code_skeleton": "string containing the test function stub",
      "mocks_required": ["string"],
      "timeout_config_under_test": "string or null"
    }
  ],
  "global_risks": [
    {
      "risk_type": "string",
      "location": "string",
      "severity": "HIGH | MEDIUM | LOW",
      "description": "string",
      "recommendation": "string"
    }
  ],
  "coverage_summary": {
    "retry_paths_found": "number",
    "timeout_configs_found": "number",
    "backoff_strategies_found": "number",
    "circuit_breaker_patterns_found": "number",
    "untestable_paths": ["string"]
  }
}

## TOOLS
You may use the following tools during analysis:
[AVAILABLE_TOOLS]

## RISK_LEVEL
This analysis targets [TARGET_ENVIRONMENT] where failures can cause [BUSINESS_IMPACT]. Flag any scenario where a test failure indicates a production outage risk.

## EXAMPLES
Here are examples of the expected test scenario format:
[FEW_SHOT_EXAMPLES]

Begin analysis.

After copying the template, fill in the placeholders with your specific context. For [CODE_FILES], include the source files containing retry logic, HTTP clients with timeout settings, message queue consumers, or database connection pools. For [CONFIG_FILES], provide YAML, JSON, or environment-based configuration that sets timeout values, retry counts, and backoff multipliers. The [SERVICE_DEPENDENCY_MAP] should describe which services call which, so the model can trace cascading failure paths. If you have existing test examples, include them in [EXISTING_TEST_EXAMPLES] so the generated tests follow your team's conventions. The [FEW_SHOT_EXAMPLES] placeholder is critical for output quality—provide two or three well-formed scenario objects that demonstrate your expected level of detail and assertion style. For high-risk production systems, set [RISK_LEVEL] context explicitly and ensure a human reviews the generated scenarios before they enter your CI pipeline.

IMPLEMENTATION TABLE

Prompt Variables

Replace each placeholder with concrete values before sending the prompt to the model. Validation notes describe how to verify the replacement is correct and safe.

PlaceholderPurposeExampleValidation Notes

[RETRY_CODE_SNIPPET]

The source code block containing the retry logic, timeout configuration, or backoff strategy to analyze

async def fetch_with_retry(url, max_retries=3, backoff=2.0): ...

Parse check: must be valid code in the target language. Null not allowed. Truncate at 2000 tokens if larger.

[DEPENDENCY_GRAPH]

A list or map of services, databases, and external APIs the retry logic interacts with, used to assess cascading failure risk

{"services": ["payment-api", "inventory-db", "auth-service"], "call_chain": ["gateway -> payment-api -> inventory-db"]}

Schema check: must be valid JSON with services array. Null allowed if dependency analysis is not required.

[TIMEOUT_CONFIG]

The current timeout settings for the operation, including connect, read, and total timeout values in milliseconds

{"connect_timeout_ms": 500, "read_timeout_ms": 3000, "total_timeout_ms": 10000}

Schema check: must include numeric values for at least connect and total timeout. Null allowed if timeout analysis is out of scope.

[IDEMPOTENCY_REQUIREMENT]

A boolean flag indicating whether the operation must be idempotent, used to trigger idempotency violation checks

Must be true or false. When true, the eval must include idempotency violation detection. Default to true for write operations.

[FAILURE_MODE_CATALOG]

A list of known failure modes to test against, such as network errors, timeouts, rate limits, and partial failures

["ECONNREFUSED", "ETIMEDOUT", "HTTP 429", "HTTP 503", "partial_write"]

Schema check: must be a JSON array of strings. Each entry should map to a testable error condition. Null allowed to let the model infer from code.

[BACKOFF_STRATEGY]

The expected backoff algorithm name, used to validate that the generated tests match the intended strategy

exponential_jitter

Must be one of: fixed, linear, exponential, exponential_jitter, decorrelated_jitter. Null allowed if the model should detect the strategy from code.

[OUTPUT_FORMAT]

The desired output structure for generated test scenarios, specifying the schema fields required

{"format": "pytest", "include": ["test_name", "setup", "assertions", "expected_behavior"]}

Schema check: must specify format and include fields. Supported formats: pytest, jest, go-test, custom. Null not allowed.

[MAX_RETRY_LIMIT]

The maximum number of retries the system should attempt, used to generate boundary tests at and beyond this limit

5

Must be a positive integer. Validation: generated tests must include scenarios at max_retries and max_retries+1 to test overflow behavior.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Retry and Timeout Behavior Test Prompt into a CI pipeline or pre-production resilience review.

This prompt is designed to be executed automatically within a CI pipeline or as part of a manual pre-production resilience review. It takes a code diff, a target function signature, or a service configuration block as input and produces a structured test plan. The primary integration point is a step that runs after static analysis but before deployment to a staging environment. The prompt's output is not executable code; it is a JSON specification of test scenarios that must be parsed and fed into your existing test execution framework.

To wire this into an application, build a harness that performs the following steps: First, extract the relevant source context—this could be a git diff output, a specific file path, or a parsed AST snippet—and inject it into the [CODE_OR_CONFIG] placeholder. Second, inject the [SERVICE_CONTEXT] with known dependencies, such as database connection strings or downstream service names, to enable the model to reason about cascading failures. Third, define a strict [OUTPUT_SCHEMA] in the prompt, such as a JSON array of objects with fields for test_name, failure_mode, assertions, and risk_level. After receiving the model's response, validate it against this schema programmatically. Any output that fails schema validation should trigger a retry with a more explicit error message appended to the prompt, up to a maximum of two retries. For high-risk services, route the validated test plan to a human reviewer via a pull request comment or a ticketing system before any load test is generated from it.

The most common production failure mode is the model generating a test for a timeout configuration that doesn't exist in the provided code, a hallucination often caused by the model's pre-training on common library defaults. Mitigate this by adding a [CONSTRAINTS] block that explicitly instructs: 'Only generate tests for retry and timeout configurations explicitly visible in the provided code. Do not assume default values for any library.' A second failure mode is the generation of non-idempotent test scenarios for message queue consumers or payment endpoints. Your harness must run a secondary validation pass using a separate, smaller classifier model or a regex-based check to flag any generated test that performs a state-changing operation without a corresponding idempotency key or a unique identifier. Flagged tests should be blocked from automatic execution and sent for human review.

For model choice, a mid-tier reasoning model like claude-3.5-sonnet or gpt-4o provides a good balance of code comprehension and structured output adherence. Avoid smaller, faster models for this task, as they frequently confuse backoff strategies (e.g., exponential vs. linear jitter) when described in code. Log the full prompt, the raw model response, the schema validation result, and the final parsed test plan as a single trace object. This trace is invaluable for debugging false positives in the idempotency check or for tuning the prompt's constraints over time. The next step after generating this test plan is to feed the validated JSON into a test scaffold generator that produces the actual pytest or k6 script, but that is a separate prompt's responsibility.

IMPLEMENTATION TABLE

Expected Output Contract

The model response must conform to this schema for downstream automation to work reliably. Each test scenario must be machine-parseable and include all required fields for execution and evaluation.

Field or ElementType or FormatRequiredValidation Rule

test_scenarios

Array of objects

Must contain at least 1 scenario. Empty array fails.

test_scenarios[].id

String (kebab-case)

Must match pattern ^[a-z0-9]+(-[a-z0-9]+)*$. Unique within array.

test_scenarios[].name

String

Must be 5-120 characters. Cannot be empty or whitespace-only.

test_scenarios[].retry_config

Object

Must contain max_attempts, backoff_strategy, and initial_delay_ms fields.

test_scenarios[].retry_config.max_attempts

Integer

Must be >= 1 and <= 10. Values outside range trigger validation warning.

test_scenarios[].retry_config.backoff_strategy

Enum string

Must be one of: fixed, linear, exponential, exponential_with_jitter. Unknown values fail.

test_scenarios[].retry_config.initial_delay_ms

Integer

Must be >= 0 and <= 60000. Negative values fail.

test_scenarios[].timeout_config

Object

Must contain connect_timeout_ms, read_timeout_ms, and total_timeout_ms fields.

test_scenarios[].timeout_config.connect_timeout_ms

Integer

Must be >= 100 and <= 30000. Values below 100ms trigger a realism warning.

test_scenarios[].timeout_config.read_timeout_ms

Integer

Must be >= 100 and <= 120000. Must be less than total_timeout_ms.

test_scenarios[].timeout_config.total_timeout_ms

Integer

Must be >= 500 and <= 300000. Must be greater than connect_timeout_ms and read_timeout_ms.

test_scenarios[].failure_injection

Object

Must contain type and trigger_after_attempt fields.

test_scenarios[].failure_injection.type

Enum string

Must be one of: timeout, connection_refused, http_429, http_503, http_500, partial_response, dns_failure. Unknown values fail.

test_scenarios[].failure_injection.trigger_after_attempt

Integer or null

If integer, must be >= 0 and < max_attempts. If null, failure is injected on every attempt.

test_scenarios[].expected_outcome

Object

Must contain success, final_state, and total_duration_ms_range fields.

test_scenarios[].expected_outcome.success

Boolean

Must be true or false. Cannot be null.

test_scenarios[].expected_outcome.final_state

Enum string

Must be one of: completed, exhausted_retries, timeout, circuit_open, partial_success. Unknown values fail.

test_scenarios[].expected_outcome.total_duration_ms_range

Object

Must contain min and max fields. min must be >= 0. max must be > min.

test_scenarios[].idempotency_check

Object or null

If not null, must contain method and assertion fields. method must be one of: request_signature, state_comparison, side_effect_count. assertion must be a non-empty string.

test_scenarios[].cascading_failure_risk

Enum string

Must be one of: none, low, medium, high, critical. Unknown values fail.

test_scenarios[].source_code_reference

String or null

If not null, must be a valid file path relative to repository root with optional line range (e.g., src/client.ts:42-68). Path must exist in provided context.

PRACTICAL GUARDRAILS

Common Failure Modes

What breaks first when generating retry and timeout tests from code analysis and how to guard against it.

01

Misidentifying Retry Boundaries

What to watch: The model generates tests for retry logic that doesn't exist or misses retry wrappers implemented via decorators, middleware, or service mesh configs. Guardrail: Require the prompt to ingest explicit retry configuration files, decorator annotations, and middleware chains before generating test scenarios. Validate generated test targets against a known retry inventory.

02

Ignoring Idempotency Requirements

What to watch: Generated tests verify retry behavior but fail to assert that operations remain idempotent across retries, missing duplicate side effects. Guardrail: Add an explicit idempotency check instruction in the prompt template. Require test assertions that verify state after N retries matches state after 1 success, especially for payment, write, and state-transition operations.

03

Unrealistic Timeout Simulation

What to watch: Tests use hardcoded sleep durations or wall-clock waits that are either too short to trigger real timeouts or too long for CI pipelines. Guardrail: Instruct the model to generate tests using injectable clock abstractions, mock timers, or configurable timeout values rather than real sleep calls. Validate that generated tests complete within a specified CI time budget.

04

Missing Cascading Failure Scenarios

What to watch: Tests cover single-service retries but ignore downstream propagation when a retry storm overwhelms dependent services. Guardrail: Require the prompt to analyze the call graph and generate at least one test scenario where retries from Service A cause overload in Service B. Include assertions for circuit breaker activation and bulkhead isolation.

05

Backoff Strategy Assertion Gaps

What to watch: Tests verify that retries happen but don't assert exponential backoff, jitter, or max retry limits, allowing linear or fixed-delay implementations to pass. Guardrail: Add explicit output schema requirements for backoff assertions: expected delay ranges per retry attempt, jitter presence, and total retry duration ceiling. Validate timing distributions in eval.

06

State Leakage Between Retry Attempts

What to watch: Generated tests reuse mutable state across retry iterations, causing false positives where later attempts succeed due to side effects from earlier attempts. Guardrail: Require test isolation instructions: each retry attempt must start from a clean state. Generate teardown or reset steps between retry iterations and validate that test order doesn't affect outcomes.

IMPLEMENTATION TABLE

Evaluation Rubric

How to test output quality before shipping. Run these checks on a sample of 10-20 code snippets with known retry patterns to validate the prompt before integrating it into a pipeline.

CriterionPass StandardFailure SignalTest Method

Retry Pattern Detection

All retry loops, exponential backoff, and jitter implementations in [CODE_SNIPPET] are identified with correct line references

Missing a retry loop that exists in the code or flagging a non-retry loop as retry logic

Diff the detected patterns against a manually labeled ground-truth set for the 10-20 sample snippets

Timeout Configuration Extraction

Every timeout value, deadline context, and cancellation signal is extracted with its exact value and scope

Timeout value is missing, incorrectly parsed, or attributed to the wrong operation scope

Compare extracted timeout values against a schema-validated JSON of expected timeouts per snippet

Idempotency Violation Flagging

Non-idempotent operations inside retry blocks are flagged with a risk level and explanation

A non-idempotent operation inside a retry block is missed, or an idempotent operation is incorrectly flagged

Run a targeted check on 5 snippets with known idempotency violations and verify all are caught

Backoff Strategy Classification

Each retry block is classified as fixed, linear, exponential, or exponential-with-jitter with correct parameters

Misclassification of backoff type or incorrect parameter extraction

Validate classification against a lookup table of expected backoff types for each snippet

Cascading Failure Risk Assessment

Downstream call chains inside retry blocks are identified and annotated with timeout budget analysis

Failure to identify a downstream dependency that could cause cascading timeouts

Trace the call graph manually for 3 complex snippets and confirm the prompt output matches

Output Schema Compliance

The response is valid JSON matching the [OUTPUT_SCHEMA] with all required fields present

JSON parse error, missing required field, or field type mismatch

Validate the output against the JSON Schema using a programmatic validator for all 10-20 samples

False Positive Rate

No more than 1 false positive per 10 snippets for retry pattern detection

Multiple false positives indicating the prompt is over-flagging normal loops or error handling

Count false positives across the sample set and calculate the rate

Explanation Grounding

Every finding includes a direct code reference or line number from [CODE_SNIPPET] as evidence

A finding is stated without a code reference, or the reference points to unrelated code

Spot-check 5 findings per snippet and verify the referenced line contains the described pattern

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Add strict schema validation, idempotency analysis, and cascading failure detection. Wire the prompt into a CI pipeline that runs on PRs touching retry/timeout configuration files.

  • Add [IDEMPOTENCY_VIOLATION_CHECK]: "For each retry scenario, determine if the operation is idempotent. Flag any non-idempotent operation that could be retried without a mutex or deduplication key."
  • Add [CASCADING_FAILURE_CHECK]: "Trace upstream callers of this service. For each timeout scenario, identify whether upstream callers will exhaust their own timeouts before this service responds."
  • Require [OUTPUT_SCHEMA] to include idempotency_risk (boolean), cascading_impact (array of affected services), and remediation_priority (enum: LOW, MEDIUM, HIGH, CRITICAL).

Watch for

  • Silent format drift when the model omits nested fields in cascading_impact.
  • False positives on idempotency for read-only operations that are safe to retry.
  • Missing human review for CRITICAL priority findings before automated Jira ticket creation.
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.