Troubleshooting a 502 Error on an Internal LLM Gateway: A Layered Debugging and Fix Guide
This article walks through a real 502 failure that appeared after a version upgrade, where GUI requests to a self-hosted internal LLM inference gateway all failed while script-based requests to the same gateway kept returning 200. It explains how that contradiction narrows the root cause to differences between the two request paths, then breaks the black-box error into four observable layers: which hop fails, TLS negotiation results, runtime and crypto library versions, and connection reuse behavior. The root cause was three overlapping factors: mismatched TLS protocol versions, an empty cipher suite intersection, and stale pooled connections being reused. The article covers temporary recovery steps, long-term fixes such as explicit TLS policies and health-checked pooling, observability improvements, and a quick troubleshooting checklist.
1. Symptom: After an Upgrade, Every UI Request Fails
After a version upgrade of an AI coding tool, users connecting their own custom model — a self-hosted large model inference gateway inside the enterprise network — started hitting stability problems. Every conversation request sent from the graphical interface returned 502, no business logs were written on the gateway side, and the tool became completely unusable.
The error message on the failing path was clear enough: while forwarding the request to the internal inference gateway, the local proxy process threw a handshake exception. The connection was closed by the peer during protocol negotiation, reported as “the connection was closed in a way that violates the protocol.” The nature of this exception is that the underlying socket read a close signal from the peer before the transfer completed or just as it began, and the transport layer never received a single complete protocol message.
2. The Key Contradiction: One Machine, Two Outcomes
What stalled the investigation was a seemingly self-contradictory fact:
- Sending requests directly to the internal gateway from a script returned 200 every time, with complete response bodies.
- Sending messages through the graphical interface reproduced 502 consistently, without exception.
This contradiction is valuable because it rules out whole-system causes such as “the network is unreachable,” “the gateway is down,” or “the certificate expired.” If the internal gateway itself were unavailable, script requests could not succeed; if the certificate had failed globally, script requests would fail too. The root cause therefore has to sit at the point where the two paths differ.
The differences usually concentrate in a few places:
- Different processes issue the requests, loading different runtimes and dependency library versions.
- Different outbound paths: one connects directly, the other goes through a local proxy listening port that forwards traffic.
- Different request shapes: UI requests often carry longer context, larger request bodies, and streaming response requirements.
- Different connection lifecycles: the UI process stays resident and reuses a connection pool, while the script process establishes a connection once and exits.
3. Layered Diagnosis: Turning a Black-Box 502 into Four Observable Layers
The first principle of troubleshooting is to make every layer observable. Verify layer by layer in the order below rather than jumping to guesses.
Layer 1: Identify Which Hop Fails
Turn on verbose logging on the local proxy and record three timestamps: when the UI request is received, when the upstream connection is initiated, and when the peer close is read. If the proxy never receives the UI request, the problem is in the UI process’s outbound configuration. If the proxy receives it but the upstream connection fails, the problem is on the hop from the proxy to the internal gateway. This incident fell into the latter category.
Layer 2: Verify the Transport Layer Negotiation Result
Use a minimal probe script that only prints the negotiation result without sending business data, focusing on the protocol version and cipher suite:
import socket, sslctx = ssl.create_default_context()with socket.create_connection(("intranet-gateway.local", 443), timeout=5) as raw:with ctx.wrap_socket(raw, server_hostname="intranet-gateway.local") as s:print("version:", s.version()) # e.g. TLSv1.2 / TLSv1.3print("cipher :", s.cipher())
If this script succeeds while the resident process fails, the difference is not in the certificate trust chain but in the negotiation parameters the client proposes.
Layer 3: Compare the Runtime Environments of the Two Processes
The most common side effect of an upgrade is that dependencies get re-resolved: after a major version change in the underlying crypto library, the highest protocol version supported by default, the default cipher suite blacklist, and whether session reuse is enabled by default can all change. Print the libraries and versions actually loaded by each process and compare them item by item:
import ssl, sysprint(sys.version)print(ssl.OPENSSL_VERSION)print(sorted(ssl.HAS_SNI, ) if False else ssl.HAS_SNI)
Also confirm whether environment variables or config directory differences cause the resident process to read a different proxy and certificate configuration.
Layer 4: Observe Connection Reuse Behavior
A resident process maintains a long-lived connection pool. If connections established before the upgrade are still reused after it, while the peer has changed its idle timeout or forced-close policy, you get the classic pattern of “the first request succeeds and all subsequent requests fail.” The test is simple: restart the resident process and check whether the first request works. If it does, the evidence points strongly to connection reuse and stale idle connections.
4. Root Cause: Three Overlapping Factors
Taken together, the evidence showed this was not a single-point problem but three factors stacking up:
- Inconsistent protocol version negotiation. After the upgrade, the runtime narrowed the available protocol versions by default, while the internal gateway still used an older negotiation policy. The two had no overlap in their version ranges, so the peer chose to drop the connection outright, and the client could only observe a connection that ended abnormally.
- Mismatched cipher suite sets. Even when the version could be negotiated, an empty suite intersection would also break the handshake, and the error is often wrapped by upper layers into the same exception, hiding the real cause.
- Stale long-lived connections being reused. Old connections in the pool were handed out again, and only when the request was written did it turn out the peer had long since closed them, showing up as intermittent or persistent 502s.
Script requests always succeeded because they created a new connection each time, negotiated with a permissive default parameter set, sent small request bodies, and never triggered the streaming path — sidestepping all of the above conditions.
5. Fixes: From Temporary Recovery to Long-Term Stability
5.1 Temporary Recovery
- Restart the resident process and the local proxy to clear the connection pool and restore first-request availability.
- Explicitly specify the protocol version and cipher suites that match the internal gateway on the proxy side, instead of relying on runtime defaults.
- Set a reasonable idle timeout and maximum lifetime for upstream connections, actively evicting stale ones.
Sample configuration (pseudocode, intent only):
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)ctx.minimum_version = ssl.TLSVersion.TLSv1_2ctx.maximum_version = ssl.TLSVersion.TLSv1_2ctx.load_default_certs()# Only narrow the suites explicitly after confirming peer capabilities, to avoid an empty intersection
5.2 Permanent Fix
- Unify the transport layer policy of the internal gateway, explicitly declaring the supported protocol versions and suite list as a written baseline.
- On the client side, disable unbounded connection reuse and switch to “pooling with health checks”: run a lightweight validation before handing out a connection, and rebuild on failure.
- Add retry and circuit breaking at the proxy layer: retry handshake-type exceptions only once with a forced new connection, to avoid amplifying the failure.
- Add the upgrade process to a regression checklist that automatically runs an end-to-end connectivity probe after each upgrade.
6. Observability: Locating Similar Issues in Ten Minutes
Three capabilities are worth building:
- End-to-end request identification: generate a unique ID for each UI request and carry it through UI, proxy, and upstream gateway logs for cross-layer alignment.
- Handshake metrics: instrument protocol version, suite, handshake latency, and categorized failure reasons, wire them into monitoring and alerting, and fire an alert immediately when version ranges have no intersection.
- Dual-channel probing: run “new connection probe” and “reused connection probe” in parallel on a schedule; divergence between the two results is a strong signal of a stale connection problem.
7. Quick Troubleshooting Checklist
- Which hop fails: UI to proxy, or proxy to upstream.
- Whether new connections succeed and reused connections fail.
- Whether the runtimes and crypto library versions of the two processes match.
- Whether the protocol version and suite intersection is non-empty.
- Whether there is an idle timeout mismatch on long-lived connections.
- Whether request body size and the streaming toggle affect reproduction.
- Whether configuration differences before and after the upgrade have been archived for comparison.
8. Conclusion
A pattern like “the CLI works but the UI always fails” almost always points to environment differences and connection lifecycle, not a whole-service outage. Once every layer becomes observable, comparable, and regression-testable, a vague error like 502 that upper layers package uniformly can be traced back to a concrete protocol negotiation problem — and intercepted early in the upgrade process.
