Inferensys

Prompt

gRPC Deadline Exceeded and Unavailable Retry Prompt Template

A practical prompt playbook for using gRPC Deadline Exceeded and Unavailable Retry Prompt Template 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

Defines the operational context, required inputs, and boundaries for automating gRPC retry decisions with an LLM.

This prompt is designed for service engineers and SRE teams who need to automate recovery decisions when a gRPC call fails with DEADLINE_EXCEEDED or UNAVAILABLE status codes. The job-to-be-done is interpreting a structured gRPC error context, calculating a safe new deadline, and producing a machine-readable instruction that a retry harness can execute directly. The ideal user is an engineer integrating this prompt into an incident response automation or a custom gRPC interceptor that catches failures and calls an LLM before blindly retrying or failing over.

Use this prompt when you have access to the original gRPC status code, the current retry count, the original deadline, and the target service's SLO. It is particularly effective for unary RPCs where idempotency is guaranteed. Do not use this prompt for streaming RPCs without additional context about the last received message offset, as the retry semantics differ significantly. Avoid using it when the error is a deterministic application-layer failure (e.g., INVALID_ARGUMENT or FAILED_PRECONDITION), as retrying will not resolve the root cause. The prompt assumes the caller has already verified that the error is transient and worth retrying.

Before wiring this into a production harness, ensure you have a clear retry budget defined. The prompt will respect a maximum retry count, but it is your responsibility to enforce circuit-breaker state and total latency budgets outside the model call. If the prompt recommends a fallback to a REST transport, you must have that endpoint pre-configured and tested. The model will not invent a fallback URL; it will only signal that a fallback is the correct next step. For high-risk financial or healthcare transactions, always route the final retry decision through a human approval queue, even if the model's instruction is machine-readable.

PRACTICAL GUARDRAILS

Use Case Fit

Where this prompt works and where it does not. Understand the operational boundaries before wiring it into a production retry harness.

01

Good Fit: Unary RPCs with Strict Deadlines

Use when: recovering from DEADLINE_EXCEEDED on a single request-reply call where the server might still complete the work. Guardrail: The prompt must recalculate a new deadline based on the remaining SLO budget, not just add a fixed offset.

02

Bad Fit: Non-Idempotent Streaming Mutations

Avoid when: a streaming RPC that has already sent partial data fails with UNAVAILABLE. Replaying from the start could duplicate side effects. Guardrail: Implement a resume offset or sequence number check before allowing any retry.

03

Required Input: gRPC Status Code and Trailers

Risk: A generic retry without the specific gRPC status code and metadata trailers will make a poor fallback decision. Guardrail: The prompt harness must parse and inject the exact StatusCode, error message, and any retry-info or throttle trailers into the template.

04

Operational Risk: Retry Storm Amplification

Risk: A server under load returning UNAVAILABLE will be hit again by every client's immediate retry, worsening the outage. Guardrail: The prompt must output a jittered backoff instruction and respect any Retry-After-like metadata from the server.

05

Good Fit: Transparent Fallback to REST

Use when: a gRPC endpoint is persistently unavailable, but a REST equivalent exists. Guardrail: The prompt must verify the REST endpoint's semantic equivalence and map the original protobuf payload to a JSON body, flagging any field transformations for review.

06

Bad Fit: Client-Side Timeout vs. Server Deadline

Avoid when: the DEADLINE_EXCEEDED was triggered by a client-side timeout, not a server-side deadline. The server may still be processing the request. Guardrail: The harness must distinguish the error source before retrying to prevent creating orphaned server-side operations.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt template for generating a structured retry decision when a gRPC call fails with Deadline Exceeded or Unavailable status codes.

This template is designed to be injected into a retry harness. It instructs the model to act as a gRPC reliability expert, interpreting the specific error code, current retry count, and method type to produce a machine-readable decision. The prompt forces a clear distinction between transient failures that benefit from a deadline recalculation and persistent failures that require a transport fallback, such as switching from gRPC to REST.

markdown
You are a gRPC reliability expert. Analyze the failed gRPC call details and produce a structured retry decision.

**Input Details:**
- Service Method: [SERVICE_METHOD]
- Call Type: [UNARY_OR_STREAMING]
- gRPC Status Code: [STATUS_CODE]
- Error Message: [ERROR_MESSAGE]
- Current Retry Count: [RETRY_COUNT]
- Maximum Retries Allowed: [MAX_RETRIES]
- Original Deadline (ms): [ORIGINAL_DEADLINE_MS]
- Available Fallback Transports: [AVAILABLE_TRANSPORTS]

**Decision Constraints:**
- For DEADLINE_EXCEEDED, recalculate a new deadline using exponential backoff: new_deadline = original_deadline * (2 ^ retry_count).
- For UNAVAILABLE, check if the current retry count is less than the maximum allowed. If so, retry with the same deadline.
- If retries are exhausted for the primary transport, select the first available fallback from [AVAILABLE_TRANSPORTS] (e.g., REST).
- For streaming calls, a retry is only valid if the stream can be resumed from the last received sequence ID. If no sequence ID is available, the decision must be NO_RETRY.

**Output Schema:**
Return a valid JSON object with the following structure:
{
  "decision": "RETRY" | "FALLBACK" | "NO_RETRY",
  "reasoning": "A concise explanation of the decision.",
  "retry_parameters": {
    "new_deadline_ms": <integer>,
    "backoff_delay_ms": <integer>,
    "resume_sequence_id": <string or null>
  },
  "fallback_transport": "<string or null>"
}

To adapt this template, replace the square-bracket placeholders with values from your gRPC interceptor or service mesh telemetry. The [AVAILABLE_TRANSPORTS] field should be a list derived from your service's routing configuration. The critical adaptation for production is ensuring the resume_sequence_id logic is wired to your streaming client's internal state; a null value for a streaming call must always result in a NO_RETRY decision to prevent data loss. Before deployment, validate the output JSON against your application's schema to catch any malformed responses from the model.

IMPLEMENTATION TABLE

Prompt Variables

Inputs required for the gRPC retry prompt to produce a reliable retry-or-fallback decision. Validate each placeholder before calling the model to prevent runtime parsing errors.

PlaceholderPurposeExampleValidation Notes

[GRPC_STATUS_CODE]

The gRPC status code from the failed call

DEADLINE_EXCEEDED

Must be a valid gRPC status code string. Check against the gRPC status code enumeration. Null not allowed.

[GRPC_ERROR_MESSAGE]

The raw error message string from the gRPC failure

Deadline Exceeded before headers received

Must be a non-empty string. Truncate to 500 characters to avoid prompt bloat. Null not allowed.

[GRPC_METHOD_TYPE]

The type of gRPC method that failed

UNARY

Must be one of UNARY, CLIENT_STREAMING, SERVER_STREAMING, BIDI_STREAMING. Controls retry safety logic.

[CURRENT_RETRY_COUNT]

The number of retries already attempted for this request

2

Must be a non-negative integer. Used to enforce the retry budget. Null not allowed.

[MAX_RETRY_BUDGET]

The maximum allowed retries before escalation

3

Must be a positive integer. If CURRENT_RETRY_COUNT >= MAX_RETRY_BUDGET, the prompt should output an escalation decision.

[ORIGINAL_DEADLINE_MS]

The original deadline for the request in milliseconds

5000

Must be a positive integer. Used to calculate the remaining time budget and a safe new deadline.

[REST_FALLBACK_ENDPOINT]

The REST endpoint URL to use if gRPC fallback is recommended

Must be a valid URL if provided. Can be null if no REST fallback is configured. The prompt must not suggest REST fallback if this is null.

[IDEMPOTENCY_KEY]

The idempotency key for the request to ensure safe replay

ikey-a1b2c3d4

Must be a non-empty string for non-idempotent methods. Can be null for safe methods like GET. The prompt must check this before recommending a retry.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the gRPC retry decision prompt into a production service mesh with validation, streaming differentiation, and safe fallback routing.

The gRPC Deadline Exceeded and Unavailable retry prompt is not a standalone decision engine—it is a structured reasoning step inside a broader retry harness. The harness is responsible for extracting the gRPC status code, current deadline, retry count, and request metadata from the failed call, injecting them into the prompt's placeholders, and then executing the model's output as a machine-readable retry instruction. The prompt must be treated as a structured decision generator, not a free-text advisor. Its output should be parsed into a typed retry action: RETRY_WITH_DEADLINE, FALLBACK_TO_REST, FAIL_FAST, or ESCALATE. The harness validates that the action is one of these known values before acting on it.

Streaming vs. unary differentiation is the most critical harness check. For unary RPCs, a full retry is safe when idempotent. For server-side streaming calls, the harness must extract the last received sequence number or resume token from the error context and inject it into the prompt's [STREAM_STATE] placeholder. The prompt should then produce a RESUME_STREAM action with a resume offset rather than a naive RETRY. For client-side streaming, the harness must decide whether to replay the entire stream or request a checkpoint from the server before resuming. The harness should reject any retry action that does not match the RPC type—e.g., a RESUME_STREAM action for a unary call is a validation failure and should trigger an ESCALATE fallback.

Deadline recalculation must happen outside the model. The prompt receives the original deadline and elapsed time via [DEADLINE_CONTEXT] and [ELAPSED_MS], and it may suggest a new deadline in its output. The harness must enforce a maximum cumulative deadline derived from the upstream SLO. If the model's suggested deadline exceeds this bound, the harness clamps it and logs the override. Additionally, the harness must track retry budget exhaustion: if the retry count exceeds a configured maximum or the cumulative latency approaches the upstream caller's deadline, the harness short-circuits the prompt entirely and emits a FAIL_FAST or ESCALATE action without invoking the model.

Fallback to REST transport requires pre-configured endpoint mappings. The prompt's FALLBACK_TO_REST action must include a suggested REST endpoint path, but the harness validates that path against a known allowlist of REST fallback endpoints. If the model hallucinates an unmapped endpoint, the harness rejects the fallback and escalates. The harness must also inject the original gRPC request payload into the REST call with proper content-type headers and authentication token forwarding. All fallback calls must carry an X-Grpc-Fallback-Reason header for observability. Log every retry decision—model-invoked or harness-short-circuited—with the gRPC status code, retry count, chosen action, and deadline consumed.

Model choice and latency budget: this prompt is latency-sensitive because it sits on the critical path of request recovery. Use a fast, small model (e.g., a distilled or quantized variant) with a strict inference timeout—typically 200–500 ms. If the model does not respond within that window, the harness must fall back to a static retry policy (exponential backoff with jitter, capped retries) and log the model timeout. Never let the retry decision prompt become a bottleneck that worsens tail latency. Pre-warm model endpoints and consider caching identical error signatures for short TTLs to skip model invocation entirely for repeated, identical failures.

IMPLEMENTATION TABLE

Expected Output Contract

Fields, format, and validation rules for the gRPC retry decision output. Use this contract to parse and validate the model response before executing the retry or fallback action.

Field or ElementType or FormatRequiredValidation Rule

retry_decision

enum: retry | fallback | escalate | noop

Must match one of the allowed enum values exactly. Reject any other string.

status_code_interpretation

object

Must contain 'code' (string matching gRPC status code name) and 'meaning' (string). Reject if code is not in the canonical gRPC code list.

recommended_deadline_ms

integer

Must be a positive integer. Must be greater than the original elapsed time and less than or equal to [MAX_DEADLINE_MS]. Reject if zero or negative.

backoff_sequence_ms

array of integers

Must be a non-empty array of positive integers. Each element must be greater than or equal to the previous element. Reject if empty or contains non-integer values.

fallback_transport

enum: grpc | rest | null

Must be 'rest' if retry_decision is 'fallback'. Must be null if retry_decision is 'retry' or 'escalate'. Reject mismatches.

streaming_resume_strategy

enum: replay_from_last | restart_stream | null

Must be non-null if [IS_STREAMING] is true. Must be null if [IS_STREAMING] is false. Reject invalid combinations.

idempotency_check

boolean

Must be true if retry_decision is 'retry' and [IS_IDEMPOTENT] is false. Reject if idempotency is asserted without evidence or contradicts the input flag.

escalation_reason

string | null

Required if retry_decision is 'escalate'. Must be a non-empty string describing why retries are exhausted. Reject if present for non-escalate decisions.

PRACTICAL GUARDRAILS

Common Failure Modes

What breaks first when retrying gRPC Deadline Exceeded and Unavailable errors, and how to guard against it.

01

Retry Amplification Storms

What to watch: A Deadline Exceeded error on a client that has already retried multiple times can cause cascading retries upstream, overwhelming the service. Guardrail: Enforce a strict per-request retry budget (e.g., max 3 attempts) and use a circuit breaker that opens after a threshold of consecutive failures, preventing further load on a struggling backend.

02

Non-Idempotent Method Retry

What to watch: Retrying a Unary RPC that is not idempotent (e.g., a CreateOrder call) after an Unavailable error can result in a duplicate transaction if the server processed the request but the response was lost. Guardrail: The prompt must classify the RPC method as idempotent or non-idempotent. For non-idempotent methods, the retry decision must require an idempotency key or escalate for human review instead of blindly retrying.

03

Streaming vs. Unary Retry Confusion

What to watch: Applying a simple retry-with-backoff strategy to a server-side streaming RPC that failed with Deadline Exceeded can restart a costly operation from the beginning, wasting server resources. Guardrail: The prompt must differentiate between unary and streaming RPCs. For streaming calls, the recovery instruction should specify resuming from the last known sequence or offset, or failing over to a simpler unary fallback, rather than a naive full restart.

04

Static Deadline Propagation

What to watch: A retry prompt that uses the original, full deadline for a subsequent attempt guarantees a client-side timeout before the server can respond, making the retry useless. Guardrail: The prompt must include a deadline recalculation step. The new deadline for the retry must be original_deadline - elapsed_time - safety_margin. If the remaining budget is insufficient, the prompt must escalate immediately rather than attempt a guaranteed failure.

05

Fallback to Incompatible REST Transport

What to watch: Falling back to a REST endpoint after a gRPC Unavailable error without validating that the REST API supports the same operation and semantics can lead to silent data corruption or 400 errors. Guardrail: The prompt's fallback logic must include a preflight check against a known mapping of gRPC methods to REST endpoints. If no compatible REST endpoint exists, the fallback decision must be to route to a different gRPC server instance or escalate.

06

Ignoring Server-Sent Retry Directives

What to watch: A retry harness that ignores retry-delay or retry-info metadata in the gRPC error details and uses a generic exponential backoff can violate server backpressure instructions, causing a thundering herd problem. Guardrail: The prompt must instruct the harness to parse gRPC error details for server-sent retry directives. If present, these directives override the default backoff configuration to respect the server's explicit load-shedding signal.

IMPLEMENTATION TABLE

Evaluation Rubric

Criteria for evaluating the quality of a gRPC retry decision prompt before shipping it in a production harness. Each criterion includes a pass standard, a failure signal, and a concrete test method.

CriterionPass StandardFailure SignalTest Method

Status Code Interpretation

Correctly identifies DEADLINE_EXCEEDED vs. UNAVAILABLE and selects appropriate retry strategy for each

Confuses DEADLINE_EXCEEDED with UNAVAILABLE or applies identical retry logic to both

Run 10 labeled gRPC error scenarios through the prompt; assert status classification accuracy >= 95%

Deadline Recalculation

New deadline is strictly less than the original total budget minus elapsed time, with a minimum floor of 100ms

New deadline exceeds remaining budget, is negative, or is set to zero

Parse the output deadline field; assert 0 < deadline <= (original_budget - elapsed_time)

Streaming vs. Unary Differentiation

Streaming RPCs trigger a resume-from-last-sequence strategy; unary RPCs trigger a full request replay

Applies unary retry logic to a streaming RPC or vice versa

Provide 5 streaming and 5 unary failure scenarios; assert retry strategy field matches RPC type in all 10 cases

Fallback Transport Decision

Recommends REST fallback only when gRPC retries are exhausted and a REST endpoint is provided in [FALLBACK_CONFIG]

Recommends REST fallback on the first failure or when no REST endpoint is configured

Test with retry_count < max_retries (no fallback), retry_count >= max_retries with REST config (fallback), and retry_count >= max_retries without REST config (escalate); assert correct decision in all three branches

Backoff Parameter Output

Output contains base_delay_ms, max_delay_ms, and jitter_strategy fields with values consistent with [BACKOFF_POLICY]

Missing fields, values outside configured bounds, or jitter_strategy is not one of the allowed enum values

Schema-validate the output; assert all three fields present, base_delay >= min_delay, max_delay <= max_delay, jitter_strategy in ['full', 'equal', 'decorrelated']

Idempotency Key Handling

Preserves the original [IDEMPOTENCY_KEY] in the retry request when present; generates a new key only for non-idempotent methods

Strips the idempotency key on retry or generates a new key for idempotent-safe methods

Provide inputs with and without idempotency keys for both idempotent and non-idempotent methods; assert key preservation or generation matches spec

Escalation Trigger

Outputs escalation action with severity level when retry budget is exhausted and no fallback is available

Continues to suggest retry after budget exhaustion or escalates prematurely

Set retry_count = max_retries and no fallback config; assert output.action == 'escalate' and output.severity is not null

Output Schema Compliance

Output is valid JSON matching the [OUTPUT_SCHEMA] with all required fields present and correct types

Missing required fields, type mismatches, or extra fields not in schema

Run JSON Schema validator against the output; assert validation passes with no errors

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a single gRPC status code and a hardcoded deadline. Focus on getting the decision shape right before adding production complexity. Replace [ERROR_CONTEXT] with a simple status string and [SERVICE_METADATA] with a stub service name.

Watch for

  • The model treating all DEADLINE_EXCEEDED errors as retryable without checking the deadline budget
  • Confusing UNAVAILABLE with PERMISSION_DENIED when the error message is ambiguous
  • Missing the streaming vs. unary distinction, which changes retry safety
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.