Inferensys

Prompt

Circuit-Breaker-Aware Router Prompt Template

A practical prompt playbook for using the Circuit-Breaker-Aware Router Prompt Template in production AI workflows to prevent cascading failures and enable graceful degradation.
Developer doing prompt engineering on laptop, prompt variations visible on screen, casual coding session.
PROMPT PLAYBOOK

When to Use This Prompt

Determines when to deploy the circuit-breaker-aware router in production AI dispatch systems to prevent cascading failures.

This prompt is for site reliability engineers and platform engineers building AI dispatch systems that must remain resilient when downstream services fail. Use it when your router needs to make a real-time decision about where to send a request based on the current health of your infrastructure. The prompt ingests circuit breaker states, health check results, and error budget status to produce a dispatch decision that avoids degraded or failed services. It is designed for systems where a wrong routing decision causes cascading failures, not just a single bad response.

Do not use this prompt for simple static routing tables or when all downstream services are guaranteed to be healthy. This prompt assumes you have a live feed of service health data and that the model's decision will be executed by an orchestration layer that enforces the circuit breaker logic in code. The model's role is to interpret the health signals and produce a structured routing decision, but the actual circuit breaking, retry enforcement, and fail-open safety mechanisms must be implemented in the application layer. The prompt is not a replacement for infrastructure-level circuit breakers; it is a decision layer that sits on top of them.

Before deploying this prompt, verify that your health data feed is reliable and low-latency. Stale health data will cause the model to route to degraded services. Implement a hard timeout on the model's decision and a fail-open default route that preserves system availability even if the model call fails. Test the prompt against scenarios where multiple services degrade simultaneously, where error budgets are exhausted, and where health checks return ambiguous results. The eval suite should include checks for cascading failure prevention, fail-open safety, and correct prioritization of healthy services.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Circuit-Breaker-Aware Router Prompt Template works and where it introduces risk.

01

Good Fit: Resilient Multi-Service Dispatch

Use when: routing requests across multiple downstream services where some may be degraded or unavailable. The prompt evaluates circuit breaker state, health check data, and error budgets to select a healthy target. Guardrail: always provide real-time health status as structured input—do not rely on the model to infer service health from natural language descriptions.

02

Good Fit: Graceful Degradation Planning

Use when: you need the router to produce a primary target plus a ranked fallback list with explicit degradation metadata. The prompt can explain why each fallback was chosen and what functionality may be reduced. Guardrail: validate that fallback chains never route back to a known-dead service and that degradation notes are surfaced to downstream consumers.

03

Bad Fit: Real-Time Sub-Millisecond Routing

Avoid when: the routing decision must happen in single-digit milliseconds with no model inference latency. LLM-based circuit breaker routing adds tens to hundreds of milliseconds. Guardrail: use this prompt for async dispatch, batch routing, or control-plane decisions. For hot-path data-plane routing, use deterministic rule engines with the prompt's output as a configuration update.

04

Bad Fit: Single Upstream Dependency

Avoid when: there is only one downstream service with no alternatives. Circuit breaker routing adds complexity without providing resilience value. Guardrail: if you have a single dependency, implement a simple circuit breaker in application code and use this prompt only when you introduce multiple service options or degradation tiers.

05

Required Inputs: Live Health State

Risk: stale or incomplete health data causes the router to send traffic to degraded services or avoid healthy ones. Guardrail: the prompt requires structured input including circuit breaker status per service, recent error rates, remaining error budget, and latency percentiles. Build a health snapshot aggregator that feeds this data into the prompt context before every routing decision.

06

Operational Risk: Cascading Fail-Open

Risk: if the model fails to produce a valid routing decision, the system may fail-open and route to an unhealthy service, triggering cascading failures. Guardrail: implement a hardcoded fail-safe wrapper around the model output. If the response is unparseable, missing required fields, or selects a service with an open circuit breaker, default to a pre-defined safe fallback queue and fire an alert.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A system prompt that routes requests around degraded services using circuit breaker state, health checks, and error budgets.

This prompt template is designed to be the core instruction set for an AI routing agent. It forces the model to act as a resilient dispatcher, making decisions based on the provided circuit breaker states, health check results, and defined degradation rules. You must replace every square-bracket placeholder with the concrete topology, policies, and constraints of your production environment before use. The prompt is structured to produce a deterministic, machine-readable JSON output that your application harness can parse and execute.

markdown
# SYSTEM DIRECTIVE
You are a resilient service dispatcher. Your only job is to route a request to the most appropriate downstream service based on the provided topology, current circuit breaker states, health check results, and defined degradation rules. You do not process the request itself.

# ROUTING TOPOLOGY
[TOPOLOGY_DEFINITION]
# Example:
# - Service A: primary, handles "payment" intents.
# - Service B: secondary, handles "payment" intents, higher latency.
# - Service C: handles "account" intents.

# CURRENT SYSTEM STATE
- Circuit Breaker States: [CIRCUIT_BREAKER_STATES]
  # Example: {"Service A": "OPEN", "Service B": "HALF_OPEN", "Service C": "CLOSED"}
- Health Check Results: [HEALTH_CHECK_RESULTS]
  # Example: {"Service A": {"status": "FAILING", "latency_p99_ms": 5000}, "Service B": {"status": "DEGRADED", "latency_p99_ms": 800}}
- Error Budget Remaining: [ERROR_BUDGETS]
  # Example: {"Service A": 0, "Service B": 45}

# DEGRADATION RULES
[DEGRADATION_RULES]
# Example:
# 1. Never route to a service with an OPEN circuit breaker.
# 2. If primary service is OPEN, route to secondary if its circuit is CLOSED or HALF_OPEN and error budget > 0.
# 3. If no service is available for an intent, route to the "fallback" queue.
# 4. A service with a FAILING health check should be treated as OPEN.

# REQUEST TO ROUTE
- Request Intent: [REQUEST_INTENT]
- Request Payload ID: [REQUEST_ID]
- Priority: [REQUEST_PRIORITY]

# OUTPUT INSTRUCTIONS
Produce a single JSON object with the following schema. Do not include any other text.
{
  "decision": {
    "target_service": "<service_name_or_fallback>",
    "action": "ROUTE" | "QUEUE" | "REJECT",
    "reason": "<concise explanation referencing the specific rule and state that led to this decision>"
  },
  "degradation_metadata": {
    "is_degraded": true | false,
    "failed_primary": "<service_name_or_null>",
    "triggered_rule": "<the specific rule from DEGRADATION_RULES that was applied>"
  }
}

To adapt this, start by encoding your service topology in a structured format like JSON inside the [TOPOLOGY_DEFINITION] placeholder. The [DEGRADATION_RULES] are the most critical part; they must be written as explicit, deterministic logic statements that a model can follow without ambiguity. Avoid vague rules like 'prefer faster services.' Instead, use concrete conditions: 'Route to Service B only if Service A is OPEN and Service B's error budget is greater than 10.' After pasting this into your harness, run it against a test suite of known system states to ensure the model's output matches your expected routing logic before deploying to production.

IMPLEMENTATION TABLE

Prompt Variables

Inputs the prompt needs to work reliably. These must be populated by your application's control plane before the prompt is sent to the model.

PlaceholderPurposeExampleValidation Notes

[SERVICE_REGISTRY]

Current state of all downstream services including health status, circuit breaker state, and error budgets.

{"payment-svc": {"status": "OPEN", "failure_rate": 0.45, "error_budget_remaining": 0.12}, "inventory-svc": {"status": "CLOSED", "failure_rate": 0.02, "error_budget_remaining": 0.95}}

Must be valid JSON with status field set to OPEN, HALF_OPEN, or CLOSED per service. Null or missing status for any service in the routing path must trigger a fail-safe response.

[REQUEST_PAYLOAD]

The incoming request that needs to be routed, including its type, priority, and target workflow.

{"request_type": "order_create", "priority": "high", "payload": {"items": ["SKU-123"], "customer_tier": "enterprise"}}

Must contain request_type and priority fields. Priority must be one of low, medium, high, critical. Missing request_type must cause the prompt to return an invalid-input error rather than guessing a route.

[HEALTH_CHECK_TIMESTAMP]

ISO 8601 timestamp of the most recent health check evaluation to prevent stale routing decisions.

2025-03-15T14:30:00Z

Must be within the last 60 seconds. If older than 60 seconds, the application layer must refresh health checks before invoking this prompt. Stale timestamps produce a DEGRADED routing decision with a warning flag.

[ERROR_BUDGET_POLICY]

Thresholds that define when a service's error budget is exhausted and routing must be diverted.

{"critical_services": {"error_budget_min": 0.10}, "non_critical_services": {"error_budget_min": 0.0}}

Must define error_budget_min for both critical_services and non_critical_services. Values must be floats between 0.0 and 1.0. Missing policy defaults to conservative fail-open for non-critical and fail-closed for critical services.

[FAILOVER_MAP]

Mapping of primary services to their designated fallback services or degradation paths.

{"payment-svc": "payment-svc-fallback", "inventory-svc": "degraded-inventory-cache"}

Every service in SERVICE_REGISTRY with status OPEN must have a corresponding entry. Missing failover entries for an open circuit must trigger a human-review escalation rather than silent routing to a dead service.

[ROUTING_CONSTRAINTS]

Hard constraints that override normal routing logic, such as data residency, maintenance windows, or forced degradation.

{"data_residency": "eu-only", "maintenance_window": {"start": "2025-03-15T02:00:00Z", "end": "2025-03-15T04:00:00Z"}}

Must be a valid JSON object. Null is allowed and means no constraints are active. If data_residency is set, the routing decision must include a jurisdiction field that matches. Mismatch is a critical failure.

[PREVIOUS_ROUTING_DECISIONS]

Recent routing decisions for the same request context to detect retry loops and cascading failures.

[{"timestamp": "2025-03-15T14:29:55Z", "decision": "ROUTE_TO_FALLBACK", "target": "payment-svc-fallback", "reason": "circuit_open"}]

Must be an array of decision objects with timestamp, decision, target, and reason fields. Empty array is allowed for first attempts. More than 3 routing attempts for the same request must trigger a dead-letter or human-review decision.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Circuit-Breaker-Aware Router into a production dispatch loop with health checks, fail-open safety, and observability.

This prompt is not a standalone classifier; it is a decision node inside a resilient dispatch loop. The application layer must supply the prompt with live circuit breaker state, downstream health metrics, and error budget status before invocation. The model's output is a structured routing decision that the harness validates, logs, and executes. Because the prompt can recommend fail_open (route to a healthy fallback) or fail_closed (reject the request), the harness must enforce safety constraints: a fail_open decision must never route to a known-dead endpoint, and a fail_closed decision must produce a user-visible degradation notice, not a silent drop.

Wire the prompt into a dispatch function that runs after intent classification but before request execution. The function should: (1) fetch current circuit breaker states and health check results from your service mesh or monitoring store; (2) assemble the prompt with [CIRCUIT_STATES], [HEALTH_METRICS], [ERROR_BUDGETS], [REQUEST_CONTEXT], and [ROUTING_TABLE] populated from live data; (3) call the model with temperature=0 and a strict JSON output schema; (4) validate the response against the expected schema, rejecting any decision that references an unknown queue or a circuit that is forced-open by policy; (5) log the decision, circuit states, and model reasoning to your observability platform for post-incident analysis. If validation fails, retry once with the validation error injected into the prompt as additional [CONSTRAINTS]. If the retry also fails, escalate to the on-call rotation and route the request to a static fallback queue defined in infrastructure config, not model output.

Model choice matters. Use a fast, instruction-following model (GPT-4o-mini, Claude Haiku, or equivalent) because this prompt runs on the critical path of every request. Latency budget should be under 500ms for the model call. Cache circuit breaker states locally with a short TTL (5-15 seconds) rather than querying your service mesh on every invocation. For high-throughput systems, consider batching circuit state updates and running the prompt only when circuit states change or error budgets cross thresholds, using a cached routing decision otherwise. Always instrument the dispatch function with metrics: router_decision_total by outcome, router_fail_open_total, router_validation_failure_total, and router_latency_seconds. These metrics feed back into your error budgets and capacity planning.

The most dangerous failure mode is a stale circuit state. If your health check data is 30 seconds old and a downstream service has just failed, the prompt will route traffic to a dead endpoint. Mitigate this with client-side retries, request hedging, and a short deadline on downstream calls. The second most dangerous failure mode is the model hallucinating a queue name that passes schema validation but doesn't exist in your infrastructure. Prevent this by validating all queue identifiers against a static allowlist in the harness, not in the prompt. The third failure mode is cascading: if the fallback queue becomes overloaded because all traffic is failing open to it, you've traded one outage for another. Monitor fallback queue depth and set alerts before it saturates. For high-risk deployments, add a human approval step when the prompt recommends routing more than a configured percentage of traffic to fallback queues within a time window.

IMPLEMENTATION TABLE

Expected Output Contract

The model must return a single JSON object. Validate this schema before any downstream dispatch action is taken. A parse failure or missing required field should trigger a retry or fallback to the safest default queue.

Field or ElementType or FormatRequiredValidation Rule

routing_decision

object

Top-level object must parse as valid JSON. Schema validation must pass before dispatch.

routing_decision.primary_queue

string

Must match an active queue ID from [QUEUE_CATALOG]. Reject unknown or deprecated queue IDs.

routing_decision.fallback_queue

string

Must differ from primary_queue. Must be a known safe queue (e.g., 'dlq-general' or 'human-review'). Fail closed if missing.

routing_decision.confidence

number

Float between 0.0 and 1.0. Values below [CONFIDENCE_THRESHOLD] must route to fallback_queue.

circuit_breaker_status

object

Must include a status for each service listed in [CIRCUIT_STATE_INPUT]. Missing services trigger a fail-open to fallback_queue.

circuit_breaker_status.[SERVICE_ID].state

string

Must be one of: 'closed', 'open', 'half-open'. Any other value is invalid and must halt dispatch.

degradation_metadata

object

Must contain a 'degraded_services' array. If empty, 'fail_open_triggered' must be false.

degradation_metadata.fail_open_triggered

boolean

If true, primary_queue must be the fallback_queue. Log a P1 operational event.

PRACTICAL GUARDRAILS

Common Failure Modes

Circuit-breaker-aware routing introduces specific failure patterns distinct from static dispatch. These cards cover the most common production failure modes and how to prevent them before they cascade.

01

Stale Circuit State Routing

What to watch: The router uses cached or stale circuit breaker state, routing requests to a downstream service that has already failed but whose breaker hasn't tripped yet due to polling lag. Guardrail: Require the prompt to reference a freshness timestamp on circuit state and reject routing decisions where state age exceeds the health check interval.

02

Fail-Open Flooding

What to watch: When all downstream services are degraded, a naive fail-open policy routes requests anyway, overwhelming struggling services and preventing recovery. Guardrail: Include a global circuit state check in the prompt. When total healthy capacity drops below a threshold, the prompt must return a backpressure decision with retry-after metadata instead of routing.

03

Thundering Herd on Recovery

What to watch: When a circuit transitions from open to half-open, all queued requests flood the recovering service simultaneously, re-tripping the breaker. Guardrail: The prompt must include a probe-percentage constraint, limiting routing to the recovering service to a configurable fraction of traffic until full health is confirmed.

04

Error Budget Exhaustion Without Signal

What to watch: The router continues dispatching to a service whose error budget is exhausted but whose circuit hasn't tripped because the breaker uses only failure-rate thresholds, not budget-aware gating. Guardrail: Include remaining error budget as a required input field. The prompt must treat zero-budget services as degraded and route around them even if the circuit is nominally closed.

05

Degradation Metadata Loss

What to watch: The router produces a dispatch decision but omits degradation metadata, so downstream consumers can't adjust their behavior for degraded service. Guardrail: Require the output schema to include a degradation_level enum and degraded_capabilities list whenever routing to a non-healthy service. Validate presence in eval checks.

06

Cascading Fallback Collapse

What to watch: A primary service fails, the router falls back to a secondary, which also fails under redirected load, triggering a cascade through all fallback tiers. Guardrail: The prompt must include a maximum fallback depth constraint and require a dead-letter or human-review decision when all tiers are exhausted, preventing infinite fallback chaining.

IMPLEMENTATION TABLE

Evaluation Rubric

Run these scenarios against your configured Circuit-Breaker-Aware Router Prompt to validate production readiness before deployment. Each criterion targets a specific failure mode in resilient dispatch systems.

CriterionPass StandardFailure SignalTest Method

Fail-Open Safety

When circuit breaker state is OPEN for the primary downstream service, the router selects a healthy fallback service and includes degradation metadata in the output

Router returns null, halts, or selects a service with a known OPEN circuit breaker without explicit justification

Inject mock health check data with primary service in OPEN state; verify fallback selection is non-null and includes degradation_reason field

Cascading Failure Prevention

Router never dispatches more than 20% of traffic to a service with a HALF_OPEN circuit breaker state

Router floods a HALF_OPEN service with requests, exceeding the configured probe limit

Run 100 sequential test inputs against a HALF_OPEN service; count dispatches and verify count ≤ configured max_half_open_requests

Error Budget Awareness

Router reduces dispatch rate to a service when its error budget remaining falls below the configured threshold, and includes error_budget_remaining_pct in metadata

Router continues dispatching at full rate to a service with exhausted error budget

Set mock error budget to 0% for a target service; verify dispatch rate drops to 0 or fallback-only within 10 requests

Health Check Freshness

Router rejects health check data older than the configured max_health_check_age_seconds and treats the service as UNKNOWN state

Router uses stale health check data without checking timestamp freshness

Provide health check payload with last_checked timestamp exceeding max age; verify service state is UNKNOWN and dispatch decision includes stale_health_check: true

Degradation Metadata Completeness

Every dispatch decision includes circuit_breaker_state, selected_service_id, fallback_used, degradation_reason, and health_check_age_seconds fields

Output is missing one or more required degradation metadata fields

Parse JSON output from 50 test dispatches; validate schema completeness with a JSON Schema validator checking all required fields are present and non-null

Deterministic Routing for Identical State

Given identical circuit breaker states, health checks, and error budgets, the router produces the same service selection across 5 repeated invocations

Router produces different service selections for identical inputs (non-deterministic behavior)

Run same mock state payload 5 times; verify selected_service_id is identical across all runs

Graceful Degradation on Total Failure

When all downstream services are in OPEN or UNKNOWN state, router returns a structured no_healthy_service response with escalation instructions rather than throwing an error or returning null

Router returns empty response, throws exception, or selects a service in OPEN state

Set all mock services to OPEN state; verify output contains no_healthy_service: true and escalation_queue_id is populated

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a static circuit map and hardcoded health status. Replace real health checks with a simple JSON block you update manually between test runs. Focus on getting the routing logic right before wiring live telemetry.

code
[CIRCUIT_STATE] = {"payment-service": "closed", "inventory-service": "open", "notification-service": "half-open"}

Watch for

  • Routing decisions that ignore half-open state entirely
  • Fail-open logic that sends traffic to known-dead services because the prompt doesn't enforce the circuit map
  • No logging of why a route was chosen, making debugging impossible
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.