This prompt is designed for Site Reliability Engineers (SREs) and on-call developers who are actively troubleshooting HTTP 502 Bad Gateway or 504 Gateway Timeout errors. The core job is to correlate load balancer access logs with backend service logs to pinpoint the root cause: an unhealthy upstream instance, a connection timeout, a connection reset, or a backend pool misconfiguration. Use this prompt when you have access to both log sources and need a structured, evidence-backed diagnosis that identifies the specific failing backend pool and instance. This is not a general-purpose error explainer; it requires concrete log data to function reliably.
Prompt
Load Balancer 502/504 Error Investigation Prompt

When to Use This Prompt
Defines the precise job-to-be-done, the required inputs, and the operational boundaries for the load balancer error investigation prompt.
The prompt expects two primary inputs: a sample of load balancer access log lines showing the 502/504 errors and the corresponding backend service logs from the same time window. The access logs must include fields like upstream_addr, upstream_status, upstream_connect_time, and upstream_response_time. The backend logs should capture connection events, request processing, and any error or timeout messages. Without both log sources, the prompt cannot perform correlation and will produce low-confidence or speculative output. The prompt is most effective when the error is reproducible or ongoing, allowing you to capture fresh, time-aligned log samples rather than relying on stale historical data.
Do not use this prompt for initial alert triage or for diagnosing client-side errors (4xx). It is not a replacement for your monitoring dashboard or a substitute for checking basic infrastructure state—verify that backend instances are running and network ACLs are open before invoking the prompt. The prompt also assumes you have already narrowed the problem to a specific load balancer and backend pool; it is not designed to scan multiple unrelated services simultaneously. If you lack access to backend logs or your load balancer logs do not include upstream timing fields, the prompt will be unable to produce a grounded diagnosis and you should resolve that observability gap first.
After using the prompt, validate its output by checking the identified backend instance directly: review its health check status, resource utilization at the time of the error, and any application-level exceptions. The prompt's diagnosis is a hypothesis, not a final verdict. Use it to focus your investigation, then confirm with direct instance inspection before applying a fix such as restarting an instance, adjusting timeout settings, or removing an unhealthy node from the pool.
Use Case Fit
Where this prompt works, where it fails, and the operational preconditions required before trusting its output in a production harness.
Good Fit: Multi-Source Gateway Error Triage
Use when: you have correlated load balancer access logs and backend service logs for the same time window. The prompt excels at pinpointing whether a 502/504 originates from an unhealthy upstream instance, a timeout, or a connection reset, and identifying the specific failing backend pool. Guardrail: Always provide logs from both the LB and backend; single-source input produces speculation, not diagnosis.
Bad Fit: Network-Level Packet Loss or Firewall Drops
Avoid when: the root cause lies below the application layer—such as network congestion, firewall rules dropping packets, or TLS handshake failures. The prompt reasons from HTTP-layer log entries and cannot diagnose issues that leave no log footprint in the load balancer or backend service. Guardrail: Precede this prompt with network reachability checks; if LB logs show no backend connection attempts, the problem is upstream of the backend pool.
Required Inputs: Timestamp-Correlated Log Sources
What you must provide: load balancer access logs containing upstream status codes, upstream connect times, and backend target IPs; plus backend service logs showing request processing, timeouts, or crash signatures for the same time window. Guardrail: Without timestamp alignment, the model cannot correlate LB errors with backend events and will produce plausible but incorrect causal chains. Build correlation into the harness, not the prompt.
Operational Risk: Hallucinated Backend State
What to watch: when backend logs are absent or incomplete, the model may invent a plausible backend failure mode (e.g., 'connection pool exhaustion') that matches the LB error signature but has no evidence. Guardrail: Require the prompt to cite specific log lines as evidence for each conclusion. If no backend log evidence exists, the output must flag the gap and abstain from root cause claims rather than filling the gap with fluent speculation.
Bad Fit: Intermittent Errors Without Consistent Logs
Avoid when: the 502/504 errors are sporadic and you cannot capture a representative sample of correlated LB and backend logs during a failure window. The prompt needs concrete log entries to reason from; statistical summaries or metrics dashboards do not provide the frame-level detail required. Guardrail: Use log aggregation to capture full failure windows before invoking this prompt. If only metrics are available, route to a metrics-based anomaly detection workflow instead.
Required Inputs: Backend Pool Topology Context
What you must provide: a description of the backend pool topology—which services or instance groups sit behind the load balancer, their health check configurations, timeout settings, and any recent deployments or scaling events. Guardrail: Without topology context, the prompt cannot distinguish between 'pool member A timed out' and 'pool member B was marked unhealthy.' Provide topology as structured context alongside the logs.
Copy-Ready Prompt Template
A reusable prompt template for correlating load balancer access logs with backend service logs to diagnose the root cause of 502/504 gateway errors.
This prompt template is designed to be pasted directly into your AI orchestration harness. It instructs the model to act as an SRE investigating a 502/504 error burst by correlating two distinct log sources: the load balancer's access logs and the backend service's application logs. The goal is to move beyond the generic gateway error and pinpoint whether the failure is due to an unhealthy upstream target, a connection timeout, a connection reset, or a specific failing backend pool member. The template uses square-bracket placeholders for all dynamic inputs, allowing you to swap in your own log data, time windows, and infrastructure context without modifying the core reasoning instructions.
textYou are an SRE investigating a spike in 502/504 errors from a load balancer. Your task is to correlate the provided load balancer access logs with backend service logs to determine the root cause of the failures. ## INPUT DATA ### Load Balancer Access Logs (filtered for 502/504 errors within the incident window) ```json [LOAD_BALANCER_ACCESS_LOGS]
Backend Service Logs (from all upstream pool members for the same time window)
json[BACKEND_SERVICE_LOGS]
CONTEXT
- Incident Time Window: [INCIDENT_TIME_WINDOW]
- Load Balancer Type: [LB_TYPE, e.g., AWS ALB, Nginx, HAProxy]
- Backend Pool Configuration: [BACKEND_POOL_CONFIG, e.g., list of healthy/unhealthy targets, timeout settings]
- Recent Changes: [RECENT_CHANGES, e.g., deployments, config updates, scaling events]
INVESTIGATION STEPS
- Parse and Align Timestamps: Normalize all log timestamps to a single timezone (UTC). Identify the precise start and peak of the error burst from the load balancer logs.
- Identify Failing Targets: From the load balancer logs, extract the specific backend target IPs or instance IDs that returned 502/504 errors. Calculate the error rate per target.
- Correlate with Backend Logs: For the failing targets identified in step 2, examine their corresponding backend service logs during the same micro-window. Look for:
- Unhealthy Targets: Evidence of failed health checks, crash loops, or OOMKills immediately before or during the error burst.
- Timeouts: Requests in the backend logs that took longer than the load balancer's configured timeout to complete.
- Connection Resets: Log entries indicating the backend process closed the connection prematurely (e.g.,
connection reset by peer,broken pipe) or that the load balancer sent an RST packet. - No Matching Logs: If a target sent a 502/504 but has no corresponding request log, this points to a network-level failure (e.g., a full connection queue, a firewall drop) or the backend process being completely unresponsive.
- Identify the Dominant Failure Mode: Aggregate the findings from step 3 across all failing targets. Determine the single most common failure mode (e.g., 80% of errors were due to timeouts on pool member
backend-03).
OUTPUT SCHEMA
You must respond with a valid JSON object that strictly follows this schema:
json{ "incident_summary": "A one-sentence executive summary of the root cause.", "root_cause_hypothesis": { "primary_failure_mode": "UNHEALTHY_UPSTREAM | UPSTREAM_TIMEOUT | CONNECTION_RESET | NETWORK_FAILURE | UNKNOWN", "description": "A detailed explanation of the failure mechanism, citing specific log lines as evidence.", "failing_backend_pool_members": ["list of specific IPs or instance IDs that caused the errors"], "correlation_evidence": [ { "lb_log_entry": "A summarized or key-value excerpt from the load balancer log.", "backend_log_entry": "The correlated log entry from the backend service, or 'NO_MATCHING_LOG' if none was found.", "failure_type": "TIMEOUT | RESET | REFUSED | NO_RESPONSE" } ] }, "confidence": "HIGH | MEDIUM | LOW", "recommended_immediate_action": "A clear, actionable step to mitigate the issue (e.g., 'Remove backend-03 from the pool and restart its service.').", "requires_human_review": true or false }
CONSTRAINTS
- Do not invent log entries. If the evidence is insufficient to determine a root cause, set
primary_failure_modetoUNKNOWNandconfidencetoLOW, and explain what data is missing. - Base all conclusions strictly on the provided log data and context.
- If the
primary_failure_modeisUPSTREAM_TIMEOUT, you must state the configured load balancer timeout from the context and the actual backend processing time from the logs. - The
recommended_immediate_actionmust be a safe, reversible operational action, not a permanent code fix.
To adapt this template for your environment, replace the bracketed placeholders with your actual data. The [LOAD_BALANCER_ACCESS_LOGS] and [BACKEND_SERVICE_LOGS] fields should be populated with pre-filtered JSON arrays of log objects, ensuring you've already narrowed the data to the relevant time window to manage context length. The [BACKEND_POOL_CONFIG] placeholder is critical; providing the load balancer's timeout values and a list of pool members turns a generic diagnosis into a precise one. For high-severity production incidents, always set requires_human_review to true in your harness logic, and route the model's output to an on-call engineer for approval before any automated remediation is triggered.
Prompt Variables
Replace each placeholder with production data before executing the prompt. Multi-source correlation requires all log sources to be present and time-aligned within the same investigation window.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[LB_ACCESS_LOGS] | Raw load balancer access log entries for the incident window, including upstream_status, request_time, and upstream_connect_time fields | 2025-01-15T14:32:10.000Z elb-prod-01 10.0.1.5:443 502 0.001 5.000 upstream:10.0.2.12:8080 | Parse check: must contain timestamp, status code, upstream address, and timing fields. Reject if upstream_status is missing or null |
[BACKEND_SERVICE_LOGS] | Application logs from all backend instances in the target pool during the same time window, including request processing and error entries | 2025-01-15T14:32:10.050Z app-node-3 ERROR ConnectionPool::acquire timeout after 5000ms pool=main active=20 idle=0 | Parse check: must contain timestamp and log level. Validate time alignment with LB_ACCESS_LOGS within ±30s tolerance |
[BACKEND_POOL_CONFIG] | Current load balancer backend pool configuration including health check settings, timeout values, and member IPs with port mappings | pool: app-backend-prod, members: [10.0.2.11:8080, 10.0.2.12:8080, 10.0.2.13:8080], health_check: HTTP:8080/health interval=10s timeout=5s unhealthy_threshold=3 | Schema check: must include pool name, member list, health check type, timeout, and threshold. Reject if member list is empty |
[INCIDENT_TIME_RANGE] | Start and end timestamps defining the investigation window, typically spanning from first error spike to resolution or current time | start: 2025-01-15T14:30:00Z, end: 2025-01-15T14:45:00Z | Format check: ISO 8601 with timezone. Validate start < end and range does not exceed 24 hours to keep log volume manageable |
[HEALTH_CHECK_HISTORY] | Health check status transitions for each backend member during the incident window, showing when instances were marked unhealthy or healthy | 10.0.2.12:8080 healthy->unhealthy at 14:31:05, reason: timeout; returned healthy at 14:38:20 | Parse check: must include member identifier, status transition timestamps, and reason. Reject if no transitions recorded during INCIDENT_TIME_RANGE |
[DEPLOYMENT_EVENTS] | Recent deployment or configuration change events that may correlate with the error onset, including service restarts and pool membership changes | 2025-01-15T14:28:00Z deploy app-backend v2.4.1 to node-3, 2025-01-15T14:29:30Z scale-down removed node-5 from pool | Parse check: must include timestamp and event description. Allow null if no deployments in the 30 minutes preceding INCIDENT_TIME_RANGE start |
[UPSTREAM_METRICS] | Per-instance application metrics for the backend pool during the incident window, including request rate, error rate, CPU, memory, and connection pool utilization | node-3: cpu=92%, mem=87%, conn_pool_active=20/20, req_rate=450/s, error_rate=0.35 | Schema check: must include per-instance metrics with timestamps. Validate metric timestamps fall within INCIDENT_TIME_RANGE. Allow null for instances that were not scraped |
Implementation Harness Notes
How to wire the Load Balancer 502/504 Error Investigation Prompt into an application or incident response workflow.
This prompt is designed to be integrated into an automated incident response pipeline or a diagnostic chatbot for on-call SREs. The core challenge is that the prompt requires multi-source log correlation: load balancer access logs and backend service logs must be fetched, aligned by timestamp and request ID, and injected into the [LOAD_BALANCER_LOGS] and [BACKEND_SERVICE_LOGS] placeholders. Do not paste raw, unprocessed log streams. The harness must pre-process these inputs to extract a relevant time window (e.g., 5 minutes before and after the error spike) and normalize timestamps to UTC for accurate correlation.
For a production-grade implementation, wrap the model call in a validation and retry layer. The expected output is a structured JSON object with fields like root_cause, failing_backend_pool, evidence, and confidence. After the model responds, validate the JSON schema strictly. If the failing_backend_pool field references a pool name not present in the input logs, or if the evidence array is empty, reject the output and retry with a more constrained prompt that asks the model to abstain rather than guess. Log every attempt, including the raw model response and the validation error, to an audit trail for post-incident review. For high-severity incidents, route the validated output to a human SRE for approval before automatically updating the status page or paging the backend service owner.
Model choice matters here. Use a model with a large context window (128k+ tokens) to accommodate verbose log entries, and prefer models with strong JSON mode or structured output guarantees. If you are using a model without native JSON mode, append a strict [OUTPUT_SCHEMA] with a JSON Schema definition and instruct the model to respond with only that JSON object. For teams running this prompt in a RAG architecture, do not embed the logs in a vector database; instead, use a time-series log store and fetch the raw logs directly. The prompt's value comes from precise cross-source correlation, not semantic similarity search. Finally, implement a circuit breaker: if the model fails to produce valid JSON after three retries, escalate the raw logs to the on-call engineer with a note that automated diagnosis was inconclusive.
Expected Output Contract
Defines the strict JSON schema for the model's response. Use this contract to validate the output before it enters any downstream system or runbook. Every field must be parseable and verifiable.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
incident_id | string | Must match the [INCIDENT_ID] input exactly. Fail if null or mismatched. | |
classification | string (enum) | Must be one of: 'upstream_unhealthy', 'upstream_timeout', 'connection_reset', 'tls_error', 'unknown'. Fail on any other value. | |
failing_backend_pool | string[] | Must be a non-empty array of strings. Each string must match a backend pool name present in the [LB_ACCESS_LOG] input. Fail if empty or contains an unrecognized pool name. | |
root_cause_hypothesis | string | Must be a non-empty string between 50 and 500 characters. Must explicitly reference a log line or metric from the provided [LB_ACCESS_LOG] or [BACKEND_SERVICE_LOG] as evidence. Fail if no evidence citation is present. | |
evidence_log_lines | object[] | Array of objects, each with 'source' (string, either 'lb_access' or 'backend_service'), 'timestamp' (ISO 8601 string), and 'message' (string). Must contain at least 1 item. Fail if any 'source' is invalid or 'timestamp' is unparseable. | |
correlation_confidence | number | Must be a float between 0.0 and 1.0 inclusive. Represents the model's confidence in the correlation between LB and backend logs. Fail if out of range or not a number. | |
recommended_action | string | Must be a non-empty string. Must be one of: 'restart_backend', 'scale_backend', 'rollback_deployment', 'check_health_check_config', 'investigate_network', 'escalate_to_human'. Fail if not in the allowed set. | |
abstained | boolean | Must be true if classification is 'unknown' or correlation_confidence is below 0.5. Must be false otherwise. Fail if this invariant is violated. |
Common Failure Modes
What breaks first when using an LLM to investigate 502/504 errors and how to guard against it in production.
Hallucinated Backend Targets
What to watch: The model confidently names a specific backend pool or instance that does not exist in your infrastructure, or misattributes the error to a healthy service. This happens when log fields are ambiguous or the model fills gaps with plausible but incorrect service names. Guardrail: Require the model to cite exact log fields (e.g., upstream_addr, backend_connection_id) for every identified target. Validate cited identifiers against a known service registry or CMDB before accepting the diagnosis.
Timeout vs. Connection Reset Misclassification
What to watch: The model conflates a 504 (upstream timeout) with a 502 (connection reset/refused) because the log evidence is sparse or the error messages are similar. This misclassification sends the investigation down the wrong path—tuning timeouts when a service is crashing, or restarting a service when a timeout is too short. Guardrail: Include explicit definitions of 502 vs. 504 in the system prompt. Require the output to state which HTTP status code was observed and to cite the specific log field that supports the classification (e.g., upstream_status, request_time vs. upstream_connect_time).
Correlation Without Causation
What to watch: The model observes that a deployment happened around the same time as the error spike and declares the deployment as the root cause without evidence of a causal link. This leads to unnecessary rollbacks and missed real causes like an external dependency failure. Guardrail: Require the model to propose a causal mechanism (e.g., 'the deployment changed the connection pool size, which exhausted available sockets') and to identify a specific metric or log that would confirm or refute that mechanism. Flag any root cause claim that relies solely on temporal proximity.
Ignoring Multi-Source Log Gaps
What to watch: The model produces a diagnosis based only on the load balancer access logs because the backend service logs were not provided or are incomplete. It fails to flag the missing data and instead invents a plausible backend state. Guardrail: The prompt must require an explicit 'Evidence Completeness' section in the output. If backend logs are missing for a suspected upstream, the model must state 'Insufficient data to confirm' rather than guessing. The harness should test with intentionally incomplete log sets.
Brittle Log Format Parsing
What to watch: The model fails to parse a valid log line because the format differs slightly from the examples in the prompt (e.g., JSON vs. CLF, extra fields, different timestamp formats). This causes it to miss critical error codes or upstream identifiers entirely. Guardrail: Include multiple log format variants in the few-shot examples. Add a pre-processing step in the harness that normalizes timestamps and extracts key fields (status, upstream, request_time) before the prompt, reducing the model's parsing burden. Test with deliberately malformed log lines.
Overlooking the Health Check Status
What to watch: The model focuses on request-level errors but fails to correlate the 502/504 spike with the load balancer's health check logs. An upstream marked unhealthy by active health checks is the most common cause, but the model may ignore this signal if health check logs are in a separate source. Guardrail: The prompt must instruct the model to explicitly check and report the upstream health status from the load balancer's perspective during the incident window. The harness should provide health check logs as a required input and validate that the output references them.
Evaluation Rubric
Use this rubric to test the prompt's output quality before shipping it into your incident response toolkit. Each criterion targets a specific failure mode common in multi-source log correlation for 502/504 investigations.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Backend Pool Identification | Output correctly identifies the specific failing backend pool or instance from [LOAD_BALANCER_LOGS] and [BACKEND_SERVICE_LOGS] | Output names a pool not present in the logs, conflates multiple pools, or fails to identify any pool | Provide logs where a single backend pool is failing; check that the output matches the known failing pool ID |
Root Cause Classification | Output classifies the error as unhealthy upstream, timeout, or connection reset with direct log evidence quoted for each | Output uses vague language like 'backend issue' without specifying the mechanism, or misclassifies a timeout as a reset | Run against three known scenarios (unhealthy, timeout, reset); verify classification accuracy and evidence citation |
Multi-Source Correlation | Output explicitly links specific [LOAD_BALANCER_LOGS] entries to specific [BACKEND_SERVICE_LOGS] entries by timestamp, request ID, or connection ID | Output treats load balancer and backend logs as separate narratives without establishing a causal link between them | Provide logs with matching request IDs across sources; check that the output connects the correct pairs |
Evidence Grounding | Every claim about error cause, timing, or affected component is backed by a quoted log line or metric value from the provided inputs | Output makes assertions about backend health or connection state without citing a specific log entry or metric | Scan output for any causal claim lacking a direct quote; flag as failure if found |
Abstention When Data Is Insufficient | Output explicitly states when the available logs do not contain enough information to distinguish between competing root causes | Output confidently selects a single root cause when the log evidence is ambiguous or contradictory | Provide logs with deliberate gaps (missing backend logs for one pool); verify the output acknowledges the ambiguity |
Timeline Reconstruction | Output presents a chronologically ordered sequence of events from first symptom to error return, with timestamps from both sources aligned | Output lists findings in arbitrary order, misorders events, or ignores timing discrepancies between sources | Provide logs with a known event sequence; verify the output timeline matches the expected order within a 5-second tolerance |
Remediation Guidance Specificity | Output recommends a specific action tied to the root cause (e.g., restart pool X, increase timeout on route Y, investigate connection limits on instance Z) | Output gives generic advice like 'check the backend' or 'restart services' without naming the target component or parameter | Check that remediation steps reference specific pool names, instance IDs, or configuration parameters found in the logs |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Adapt This Prompt
How to adapt
Use the base prompt with a single log source and lighter validation. Replace multi-source correlation with a simpler instruction: "Given the following load balancer access log entries and backend service logs for the same time window, identify the most likely cause of the 502/504 errors." Drop the strict [OUTPUT_SCHEMA] requirement and accept a structured paragraph.
Watch for
- The model blaming the first unhealthy backend it finds without checking timing
- Hallucinated backend pool names when logs are incomplete
- Overconfident root cause statements when correlation is weak

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.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us