Inferensys

Prompt

Cache Stampede Root Cause Prompt

A practical prompt playbook for using Cache Stampede Root Cause Prompt 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 job-to-be-done, ideal user, required context, and boundaries for the Cache Stampede Root Cause Prompt.

Platform engineers and SREs use this prompt to diagnose cache stampede or thundering herd incidents during post-incident review. The job-to-be-done is structured root cause analysis: turning a chaotic set of signals—cache hit ratio drops, key expiry spikes, recomputation latency surges, and lock contention—into a clear trigger event and a set of specific cache architecture remediation recommendations. The ideal user is an engineer who already has access to incident data from monitoring systems, cache observability tools, and application metrics, and needs to produce a defensible root cause document rather than a gut-feel guess.

The prompt expects structured incident data as input: cache hit ratios over the incident window, key TTL configurations, request concurrency metrics, recomputation latency distributions, and lock acquisition or contention logs. Without this data, the analysis will be speculative. Do not use this prompt for real-time mitigation decisions—it is designed for post-hoc root cause analysis, not live traffic control. It is also not a replacement for cache architecture design; it diagnoses what went wrong in an existing system rather than proposing a greenfield caching strategy. If you lack key access distribution data or lock contention metrics, the prompt will flag missing evidence rather than fabricating a cause.

Wire this prompt into an automated incident analysis pipeline where structured incident data is already aggregated, or use it manually during a post-incident review session. The output is a root cause hypothesis with supporting evidence, a confidence assessment, and specific remediation candidates such as probabilistic early expiration, external recompute orchestration, or lock timeout tuning. After receiving the output, validate the hypothesis against additional data sources before committing to remediation actions. For high-severity incidents affecting revenue or data integrity, always pair the prompt output with human SRE review before publishing the postmortem.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Cache Stampede Root Cause Prompt works, where it fails, and the operational preconditions required before trusting its output in a production incident review.

01

Good Fit: Post-Incident Review with Rich Telemetry

Use when: You have a complete incident timeline, cache hit/miss ratio logs, key-level access frequency data, recomputation latency metrics, and lock acquisition logs. The prompt excels at correlating these signals into a coherent stampede narrative. Guardrail: Feed structured, time-synchronized data rather than raw, unsorted log streams.

02

Bad Fit: Real-Time Incident Response

Avoid when: The incident is still active and you need an immediate mitigation command. This prompt is designed for deep causal analysis, not sub-second decision-making. Guardrail: Use a separate runbook automation prompt for live mitigation; invoke this prompt only during the post-mortem phase.

03

Required Inputs: Key-Level Expiry and Cost Data

Risk: Without per-key TTL configurations, recomputation cost estimates, and lock contention metrics, the model will hallucinate plausible but incorrect stampede triggers. Guardrail: Validate that your input payload includes key_ttl_map, recompute_cost_ms, and lock_wait_time_p99 before calling the prompt. If missing, abort and request the data.

04

Operational Risk: Blaming the Cache Without Evidence

Risk: The model may default to attributing the stampede to cache expiration even when the root cause is an upstream database stall or a network partition. Guardrail: Require the output to cite specific metric anomalies and timestamps. Cross-reference the prompt's hypothesis against database and network telemetry before accepting it.

05

Operational Risk: Recommending Unsafe Locking Changes

Risk: The prompt might suggest aggressive locking or eager refresh strategies that introduce deadlocks or overwhelm the origin during normal load. Guardrail: All remediation recommendations must pass a manual review by a senior platform engineer. Never auto-apply cache architecture changes from an LLM output.

06

Bad Fit: Single-Node or Monolithic Setups

Avoid when: Your application does not use a distributed cache or has no concurrent request fan-out. The stampede pattern requires concurrent miss storms, which are rare in single-instance architectures. Guardrail: Confirm that the incident involved >1 concurrent caller for the same cache key before using this prompt.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt for diagnosing cache stampede root causes with placeholders for incident-specific data.

This template is designed to be copied directly into your AI harness, observability tool, or on-call runbook. It accepts structured incident data—cache metrics, key access patterns, recomputation costs, and lock contention signals—and returns a root cause hypothesis with specific remediation recommendations. The square-bracket placeholders represent the minimum required inputs; adapt them to match your telemetry sources and cache layer topology.

code
You are an SRE investigator specializing in distributed cache failures. Analyze the following incident data to determine the root cause of a cache stampede or thundering herd event.

[INCIDENT_TIMELINE]
[KEY_ACCESS_DISTRIBUTION]
[CACHE_EXPIRY_PATTERNS]
[RECOMPUTATION_COST_METRICS]
[LOCK_CONTENTION_SIGNALS]
[INFRASTRUCTURE_TOPOLOGY]

[OUTPUT_SCHEMA]
{
  "root_cause_hypothesis": "string",
  "trigger_event": "string",
  "contributing_factors": ["string"],
  "evidence": [
    {
      "source": "string",
      "observation": "string",
      "relevance": "string"
    }
  ],
  "stampede_mechanism": "synchronous_expiry | lock_contention | cold_start | hot_key_overload | cascading_failure",
  "affected_keys": ["string"],
  "remediation_recommendations": [
    {
      "action": "string",
      "category": "immediate | architectural | monitoring",
      "expected_impact": "string",
      "implementation_effort": "low | medium | high"
    }
  ],
  "confidence": "high | medium | low",
  "unexplained_observations": ["string"]
}

[CONSTRAINTS]
- Cite specific metrics, timestamps, and key names from the provided data.
- If lock contention is present, distinguish between client-side locking and server-side mutex contention.
- If recomputation cost data is provided, quantify the amplification factor (requests per recomputation).
- Do not speculate beyond the provided evidence; flag gaps in [unexplained_observations].
- If multiple mechanisms are possible, rank them by likelihood and explain your ranking.
- Recommend probabilistic early expiration (TTL jitter) only when synchronous expiry is confirmed.

To adapt this template, replace each placeholder with data from your observability stack. [INCIDENT_TIMELINE] should include deployment events, traffic spikes, and cache metric anomalies with timestamps. [KEY_ACCESS_DISTRIBUTION] requires per-key request rates and cardinality data—ingest this from your cache proxy or client-side metrics. [CACHE_EXPIRY_PATTERNS] needs TTL configurations and observed expiry events; pull these from cache server logs or configuration management. [RECOMPUTATION_COST_METRICS] should include p50/p99 latency and resource consumption for cache miss regeneration. [LOCK_CONTENTION_SIGNALS] requires mutex wait times, lock acquisition failures, or connection pool saturation metrics. [INFRASTRUCTURE_TOPOLOGY] should describe the cache layer architecture—client-side, reverse proxy, or distributed cluster—and any relevant replication or sharding configuration. For high-severity incidents, route the output through a human reviewer before applying remediation actions, especially when the recommendation involves cache configuration changes or lock implementation modifications.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Cache Stampede Root Cause Prompt. Each placeholder must be populated with concrete data from your observability stack before the prompt is assembled. Missing or null values will degrade the quality of the root cause hypothesis.

PlaceholderPurposeExampleValidation Notes

[CACHE_TOPOLOGY]

Map of cache nodes, regions, and replication relationships

{"nodes": ["redis-us-east-1", "redis-us-east-2"], "replication": "primary-replica"}

Must be valid JSON. Validate against infrastructure-as-code source of truth. Null not allowed.

[KEY_ACCESS_LOG_SAMPLE]

Sample of cache key access patterns during the incident window

timestamp,key,operation,ttl_remaining_ms 2024-01-15T14:03:01Z,user:42:profile,READ,0 2024-01-15T14:03:01Z,user:42:profile,READ,0

Must contain at least 100 rows covering the incident window. Validate timestamp ordering and key cardinality. Null not allowed.

[CACHE_EVICTION_POLICY]

Configured eviction policy for the affected cache instance

volatile-lru

Must match one of: noeviction, volatile-lru, allkeys-lru, volatile-lfu, allkeys-lfu, volatile-random, allkeys-random, volatile-ttl. Validate against runtime config, not documentation.

[RECOMPUTE_COST_MS]

Measured or estimated p99 latency for recomputing a single cache entry

850

Must be a positive integer. Validate against application performance monitoring data. If null, prompt will assume high cost and flag uncertainty.

[LOCK_IMPLEMENTATION]

Description of the distributed lock mechanism used during cache recomputation

Redisson RLock with 30s lease time, no retry backoff

Free text but must describe lock provider, timeout, and retry behavior. If no lock is used, set to 'none'. Null triggers a missing-lock hypothesis branch.

[TTL_DISTRIBUTION]

Histogram or summary of TTL values for keys in the affected cache segment

{"p50": 300, "p95": 3600, "p99": 86400, "count": 150000}

Must be valid JSON with at minimum p50 and p95 in seconds. Validate against cache introspection tools. Null allowed if TTL data is unavailable.

[INCIDENT_WINDOW]

Start and end timestamps of the observed stampede symptoms

{"start": "2024-01-15T14:03:00Z", "end": "2024-01-15T14:08:30Z"}

Must be valid ISO 8601 timestamps. End must be after start. Validate against incident management tool. Null not allowed.

[CLIENT_CONCURRENCY]

Number of concurrent clients or threads requesting cache keys during the incident

1200

Must be a positive integer. Validate against load balancer or application server metrics. If null, prompt will request concurrency estimation from other signals.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Cache Stampede Root Cause Prompt into an incident response or postmortem workflow.

This prompt is designed to be invoked during active cache degradation incidents or as part of a structured postmortem analysis. The primary integration point is your incident management bot or an internal SRE toolchain. The prompt expects a structured [INCIDENT_DATA] payload containing cache metrics, key access logs, and configuration snapshots. Before calling the model, your harness must assemble this payload from your observability stack—typically pulling time-series data from Prometheus or Datadog for cache hit ratios and recomputation latency, extracting key-level access patterns from Redis MONITOR logs or Elasticsearch, and capturing TTL configurations from your deployment manifests or config stores.

The implementation should enforce a strict validation layer on the input side. If the [INCIDENT_DATA] payload is missing any of the three required sections—cache_metrics, key_access_samples, or config_snapshot—the harness must abort and return a structured error asking the user to provide the missing data. On the output side, parse the model's response against the [OUTPUT_SCHEMA] defined in the prompt. Validate that the root_cause object contains a non-empty trigger_event and at least one evidence item. If the model returns a malformed JSON response, implement a single retry with a repair prompt that includes the raw output and the schema. Do not retry more than once for the same input; instead, log the failure and escalate to the on-call engineer for manual review. For high-severity incidents where a wrong diagnosis could delay mitigation, always route the final output to a human for approval before posting it to the incident timeline.

Choose a model with strong reasoning and structured output capabilities for this task. GPT-4o or Claude 3.5 Sonnet are appropriate defaults. Avoid smaller or faster models that may hallucinate causal links when the evidence is sparse. Wire the prompt into your workflow with a clear logging sidecar: capture the full prompt, the assembled [INCIDENT_DATA], the raw model response, and the parsed output. This audit trail is critical for postmortem reviews and for improving the prompt over time. Finally, ensure your harness handles timeouts gracefully—if the model call exceeds 30 seconds, abort and fall back to a pre-cached checklist of common stampede causes for the on-call engineer to review manually.

IMPLEMENTATION TABLE

Expected Output Contract

The structured output the Cache Stampede Root Cause Prompt must produce. Use this contract to validate the model's response before it enters downstream systems or dashboards.

Field or ElementType or FormatRequiredValidation Rule

stampede_trigger

string (enum)

Must match one of: 'mass_expiry', 'cold_start', 'lock_contention', 'traffic_spike', 'recomputation_cascade', 'unknown'. Reject if missing or not in enum.

trigger_evidence

array of objects

Each object must contain 'source' (string), 'timestamp' (ISO 8601), and 'observation' (string). Array length >= 1. Reject if empty.

affected_keys

array of strings

Each key must be a non-empty string matching the cache key pattern [KEY_PATTERN]. Reject if any element is empty or fails pattern match.

recomputation_cost_estimate

object

Must contain 'unit' (string, one of 'ms', 'cpu_seconds', 'db_queries') and 'value' (number >= 0). Reject if unit is missing or value is negative.

lock_contention_analysis

object or null

If trigger is 'lock_contention', required. Must contain 'lock_type' (string), 'average_wait_ms' (number), and 'contention_hotspots' (array of strings). If not applicable, must be null.

contributing_factors

array of strings

Each factor must be a non-empty string describing a condition that amplified the stampede. Array length >= 1. Reject if any element is empty or duplicates another.

remediation_recommendations

array of objects

Each object must contain 'recommendation' (string), 'category' (string, one of 'ttl_strategy', 'locking', 'prewarming', 'circuit_breaker', 'architecture'), and 'effort' (string, one of 'low', 'medium', 'high'). Array length >= 1.

confidence_score

number

Must be a float between 0.0 and 1.0 inclusive. Reject if out of range. If below [CONFIDENCE_THRESHOLD], flag for human review.

PRACTICAL GUARDRAILS

Common Failure Modes

Cache stampede prompts fail when the model hallucinates lock contention details, misidentifies the trigger key, or recommends unsafe cache-warming patterns. These cards cover the most common production failure modes and how to guard against them.

01

Phantom Lock Contention Diagnosis

Risk: The model invents lock contention as the root cause when the real issue is a misconfigured TTL or a cold start after a deployment. It may describe mutexes or distributed locks that don't exist in your stack. Guardrail: Require the prompt to cite specific log evidence (e.g., Redis SLOWLOG, application mutex wait metrics) before accepting a lock contention hypothesis. If no lock instrumentation exists, the prompt must flag that gap rather than fabricate it.

02

Hot-Key Misattribution

Risk: The model identifies the wrong cache key as the stampede trigger, often picking the most frequently accessed key rather than the one whose recomputation cost and expiry pattern actually caused the thundering herd. Guardrail: Include a required output field for evidence_per_key that maps each candidate key to its access frequency, recomputation latency, and expiry window overlap. The prompt must explain why the selected key dominates, not just that it's popular.

03

Unsafe Probabilistic Revalidation Advice

Risk: The model recommends probabilistic early recomputation (PER) without calculating the correct probability threshold for your traffic volume and recomputation cost. A wrong threshold can amplify the stampede instead of preventing it. Guardrail: Add a constraint that any PER recommendation must include the formula and input parameters used. Validate the output by checking that the recommended probability decreases as the number of concurrent requestors increases.

04

Ignoring Cold Start vs. Expiry Stampede Distinction

Risk: The model conflates a cold start stampede (many keys expiring simultaneously after a cache flush or deployment) with a single-key expiry stampede. The remediation for each is fundamentally different—cold starts need staggered pre-warming, while single-key stampedes need lock-based or PER solutions. Guardrail: Require the prompt to classify the stampede type explicitly before proposing remediation. Include a decision gate in the output schema: stampede_type: cold_start | hot_key_expiry | mixed.

05

Downstream Capacity Overestimation

Risk: The model proposes a cache-warming or lock-based solution that assumes the downstream database or service can handle the redirected load. If the downstream is already the bottleneck, serializing requests through a lock makes the outage worse by adding queuing delays. Guardrail: Add a required input field for downstream_capacity_headroom_pct and instruct the model to compare proposed remediation load against that headroom. If headroom is unknown, the prompt must recommend measuring it before implementing any lock-based solution.

06

TTL Synchronization Blind Spot

Risk: The model misses that multiple keys share the same TTL boundary, creating a recurring stampede every N minutes. It treats the incident as a one-off rather than identifying the synchronized expiry pattern that guarantees future repeats. Guardrail: Instruct the prompt to analyze the distribution of key TTLs and expiry timestamps, not just the incident window. Require a recurrence_risk field in the output that flags whether TTL alignment creates a predictable future stampede window.

IMPLEMENTATION TABLE

Evaluation Rubric

Criteria for evaluating the quality of a Cache Stampede Root Cause Analysis output before it is accepted or escalated. Use these checks to gate automated root cause reports.

CriterionPass StandardFailure SignalTest Method

Root Cause Specificity

Identifies a specific trigger event (e.g., a key expiry, a deployment, a config change) with a timestamp or narrow time window.

Output describes the stampede mechanism in general terms without a specific triggering event or time.

LLM-as-judge check: Does the output name a single, testable trigger event? Parse the output for a timestamp or event ID.

Evidence Grounding

Every causal claim is supported by a specific log line, metric data point, or configuration value cited in the output.

Claims use vague language like 'likely due to high load' without linking to a specific metric spike or log entry.

Citation verification: Extract all claims. For each, check if a source artifact is referenced. Fail if any claim is ungrounded.

Causal Chain Completeness

Output traces the full chain from trigger to symptom, including the cache miss, recomputation storm, and resource exhaustion.

Output jumps from trigger directly to symptom, skipping the intermediate steps of lock contention or recomputation cost.

Schema check: Verify the output contains fields for 'trigger', 'mechanism', and 'impact'. Fail if any field is missing or null.

Remediation Actionability

Recommends at least one specific, concrete change (e.g., 'set TTL to 3600s with a 600s stagger', 'implement Probabilistic Early Expiration') with a rationale.

Recommendations are generic (e.g., 'improve caching') or suggest actions that cannot be directly implemented.

Parse check: Extract the 'remediation' field. Fail if it contains fewer than 2 sentences or lacks a specific configuration value or algorithm name.

Differential Diagnosis

Output explicitly rules out at least one alternative hypothesis (e.g., network partition, code regression) with a reason.

Output presents a single root cause without considering or dismissing any alternatives.

LLM-as-judge check: Does the output contain a section or statement that names and dismisses an alternative cause? Fail if absent.

Key Access Pattern Analysis

Identifies the specific cache key(s) involved and describes their access pattern (hot key, expired batch, etc.).

Output discusses the stampede without naming the affected cache keys or their TTL configuration.

Schema check: Verify the 'affected_keys' field is a non-empty array and each entry has a 'key_name' and 'ttl' property.

Resource Contention Identification

Pinpoints the exhausted resource (CPU, DB connections, thread pool) and links it to the recomputation cost.

Output mentions 'high load' without specifying which resource was saturated and why.

Parse check: Extract the 'exhausted_resource' field. Fail if the value is not one of a predefined enum or is missing a utilization metric.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Add strict JSON schema validation, retry logic on parse failure, and structured logging of every invocation. Wire the output into an incident management system that requires all fields before closing the root cause task.

Prompt modification

Add to [CONSTRAINTS]: Return ONLY valid JSON matching the output schema. If any required field cannot be determined from the evidence, set its value to null and include an evidence_gap note. Do not invent cache keys, timestamps, or metric values. Add a confidence field (0.0–1.0) to the output schema.

Watch for

  • Silent schema drift when the model adds or renames fields
  • Missing evidence_gap notes when the model fills nulls with plausible guesses
  • Retry loops masking persistent format failures—cap retries at 3 and escalate to human review
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.