Back to cookbook

AI Prompt to Design an API Error-Handling and Retry Strategy

9 views Published

Make this prompt yours

Share

This AI prompt for error handling helps engineers design a consistent retry and failure strategy for an API client or backend service before writing any code. It's built for backend developers, platform engineers, and anyone integrating with a third-party or internal API who needs to decide how to handle timeouts, rate limits, and transient failures instead of bolting on ad-hoc try/catch blocks later.

Instead of asking a model to "add error handling," which tends to produce generic try/catch wrappers, this prompt asks it to reason through failure modes first: which errors are retryable (503s, timeouts, connection resets) versus which are not (4xx validation errors, auth failures), what backoff strategy fits the call pattern, and where circuit breakers or idempotency keys matter. The output is a structured plan plus implementation code, so the reasoning is visible and reviewable rather than hidden inside generated code.

Because the resulting strategy often ends up as reusable logic spread across multiple endpoints or services, it's worth running the finished prompt output through Prompt Optimizer afterward if you plan to reuse this prompt as a template for other API integrations, since its Coding mode tightens vague instructions into something you can drop into future requests with less rewriting.

Prompt template

Make this prompt yours

prompt-template
272 tokens
Role: You are a backend engineer designing a resilient API error-handling and retry strategy. Context: - API being called: [API_NAME_OR_DESCRIPTION] - Language/framework: [LANGUAGE_OR_FRAMEWORK] - Known behavior: [RATE_LIMITS_TIMEOUTS_ERROR_CODES] - Call pattern: [SINGLE_REQUEST_OR_BATCH_OR_HIGH_VOLUME] - Idempotency: [IS_THE_OPERATION_SAFE_TO_RETRY] Task: 1. Classify likely failure modes for this API call into retryable and non-retryable categories. 2. Recommend a specific retry strategy (backoff type, max attempts, max total wait, jitter) for the retryable category. 3. Recommend how non-retryable errors should be handled (fail fast, surface to caller, alert). 4. Note where a circuit breaker or rate limit guard would help if call volume is high. 5. Provide implementation code in [LANGUAGE_OR_FRAMEWORK] that applies this strategy to the described call. Constraints: - Do not retry non-retryable errors. - Include logging at each retry attempt and final failure. - Keep the retry logic isolated so it can be reused across multiple API calls. Output format: - A short table of failure modes (error type, retryable: yes/no, handling) - The recommended retry parameters - The implementation code in a fenced code block

Want it sharper? Optimize this prompt with Prompt Optimizer, check it with the Prompt Debugger or shorten it with the Token Optimizer.

Example input

example-input
228 tokens
Role: You are a backend engineer designing a resilient API error-handling and retry strategy. Context: - API being called: a third-party payment processor's REST API - Language/framework: Node.js with axios - Known behavior: returns 429 when rate limited, 503 during brief outages, 400 for invalid request bodies, times out after 10 seconds on their end - Call pattern: single request per checkout event, roughly 50 per minute at peak - Idempotency: the API accepts an idempotency key header, so retries are safe Task: 1. Classify likely failure modes into retryable and non-retryable categories. 2. Recommend a specific retry strategy for the retryable category. 3. Recommend how non-retryable errors should be handled. 4. Note where a circuit breaker or rate limit guard would help. 5. Provide implementation code in Node.js with axios that applies this strategy. Constraints: - Do not retry non-retryable errors. - Include logging at each retry attempt and final failure. - Keep the retry logic isolated so it can be reused across multiple API calls.

When to use it

  • Before building a client that calls a flaky or rate-limited third-party API
  • When a service keeps failing silently and you need a defined retry policy instead of guesswork
  • When designing a new microservice-to-microservice call and want error handling decided upfront
  • When a code review flagged inconsistent or missing error handling across endpoints

Best practices

  • State the API's actual behavior (rate limits, timeout thresholds, documented error codes) so the model doesn't invent generic assumptions
  • Specify whether calls need to be idempotent, since that changes whether retries are safe at all
  • Ask for a distinction between retryable and non-retryable errors explicitly, not just a blanket retry loop
  • Run the generated retry logic through Prompt Debugger if you're turning this into a reusable prompt, to catch edge cases like retry storms or missing jitter before you rely on it repeatedly

Common mistakes

  • Retrying every failed request the same way, including errors that will never succeed on retry (like 400 or 401)
  • Using fixed-delay retries instead of exponential backoff with jitter, which can cause thundering-herd spikes
  • Forgetting to cap total retry attempts or total retry duration, leading to requests that hang indefinitely
  • Not asking for logging or observability hooks, so failures are handled but invisible to monitoring

FAQs

How do I know which API errors are safe to retry?

As a general rule, 5xx server errors, timeouts, and connection resets are usually safe to retry because they often indicate a transient problem. 4xx client errors like 400 (bad request) or 401 (unauthorized) are not safe to retry as-is, since the same request will fail the same way every time until the underlying issue (bad payload, expired token) is fixed.

What's the difference between exponential backoff and fixed-delay retries?

Fixed-delay retries wait the same amount of time between every attempt, which can cause many clients to retry at the same moment and overwhelm a recovering service. Exponential backoff increases the delay after each failed attempt (and adding jitter randomizes it slightly), spreading retries out over time and reducing the chance of a retry storm.

Should I always retry a failed API call automatically?

No. Automatic retries only make sense when the operation is idempotent (safe to repeat) and the failure is likely transient. For non-idempotent operations without a safeguard like an idempotency key, an automatic retry can cause duplicate side effects, such as charging a customer twice.

Which Cuelara tool can help me turn this into a reusable prompt for other APIs?

Prompt Optimizer — its Coding mode is built to tighten vague or one-off coding prompts like this into a structured template you can reuse across different API integrations without rewriting it from scratch each time.

Found this prompt useful? Share it.

Share

More in Engineering

Engineering

AI Prompt to Triage Production Incidents Using Datadog's MCP Server

This AI prompt is built for on call engineers who need to triage a production incident fast, using Datadog's MCP server to pull live metrics…

ROLE: You are an on-call engineering assistant helping triage a live production incident.

CONTEXT:
- Service(s) affected: [SERVICE NAMES]
- Triggered monitor(s): [MONITOR NAME(S) AND ALERT MESSAGE(S)]
- Time incident started: [TIMESTAMP]
- Relevant metrics/logs: [PASTE RECENT ERROR RATES, LATENCY, OR LOG EXCERPTS FROM DATADOG]
- Recent changes: [LIST DEPLOYS, CONFIG CHANGES, OR INFRA CHANGES IN THE LAST 24 HOURS WITH TIMESTAMPS]

TASK:
1. Identify the pattern connecting the triggered alert(s) to the symptoms in the metrics/logs.
2. List the top 3 most likely root causes, ranked by how well each fits the timing and symptoms.
3. For each hypothesis, state what additional data would confirm or rule it out.
4. Recommend the single next diagnostic step to run first.

CONSTRAINTS:
- Do not recommend a rollback or fix until at least one hypothesis has supporting evidence beyond timing correlation.
- Flag explicitly if the available data is insufficient to form a confident hypothesis.

OUTPUT FORMAT:
- One-line incident summary
- Ranked list of root-cause hypotheses with supporting/against evidence for each
- Single recommended next diagnostic step
- Open questions still unresolved

Make this prompt yours

Engineering

AI Prompt to Write a Load Testing Plan for a REST API Endpoint

This prompt has ChatGPT, Claude, or Gemini draft a concrete load testing plan for a REST API endpoint before you run a single test. It's for…

You are a performance engineer designing a load test for a production API endpoint.

Context:
- Endpoint: [METHOD AND PATH, e.g. POST /api/v1/orders]
- Expected traffic: [REQUESTS PER SECOND AT PEAK, e.g. 150 rps average, 600 rps peak]
- Downstream dependencies: [LIST, e.g. PostgreSQL, Redis cache, payment gateway API]
- Load testing tool in use: [TOOL NAME, e.g. k6, Locust, JMeter]
- Current known constraints: [e.g. database connection pool size, rate limiter config]

Write a load testing plan with the following requirements:
1. Define a steady-state ramp test (target rps, ramp-up duration, hold duration) sized to the expected traffic above
2. Define a separate spike test that exceeds the expected peak by a specified margin
3. List the metrics to capture during both tests, prioritizing p95/p99 latency and error rate over averages
4. Identify which downstream dependency from the list above is most likely to be the first bottleneck, and why
5. Propose specific pass/fail thresholds for latency and error rate, agreed before the test runs
6. Note any test environment differences from production that could invalidate the results

Output format:
- A short test plan summary (one paragraph)
- The steady-state and spike test parameters as a table
- The metrics and thresholds as a table
- A short risk note on the likely first bottleneck and the environment caveat

Make this prompt yours

Engineering

AI Prompt to Write a Feature Flag Rollout and Cleanup Plan

A feature flag rollout plan lays out how a new capability ships behind a flag, moves through stages of exposure, and eventually gets removed…

You are a senior platform engineer helping plan a feature flag rollout.

Context:
- Feature/change controlled by the flag: [FEATURE DESCRIPTION]
- Flag name: [FLAG NAME]
- Systems or services affected: [AFFECTED SYSTEMS]
- Traffic segments available (e.g. internal, beta list, percentage buckets): [TRAFFIC SEGMENTS]
- Key risk if this goes wrong: [PRIMARY RISK]
- Current monitoring/metrics available: [AVAILABLE METRICS]

Task:
1. Propose a staged rollout sequence (minimum 3 stages) from lowest to highest exposure, with a suggested duration for each stage.
2. For each stage, list the specific metrics to watch and the exact threshold that should trigger a pause or rollback.
3. Define who should approve advancing to the next stage.
4. Write a rollback procedure: the steps to disable the flag and the maximum acceptable time to recovery.
5. Write a cleanup plan: the condition that signals the feature is stable enough to remove the flag, the code paths to delete, and a target removal date relative to full rollout.

Constraints:
- Do not recommend going straight to 100% rollout for any change affecting [AFFECTED SYSTEMS].
- Keep each stage's exit criteria measurable, not subjective.
- Flag any step that depends on information not provided above.

Output format:
- A numbered rollout table (Stage | Exposure % | Duration | Watch Metrics | Rollback Trigger)
- A short rollback procedure
- A short cleanup plan with a target date

Make this prompt yours