Debugging Guides

Distinguish symptoms from root causes, then verify the fix.

697 published

Page 5 of 7

Go — defer Inside a Loop Defers Cleanup Until Function Exit

Fix resource leaks where defer inside Go loops accumulates until function return, extract loop bodies into functions, and verify with descriptor counts.

intermediate
debugging · go · defer · resource-leak

Go — declared and not used / assigned but never used

Resolve Go unused variable errors by using blank identifiers, the blank assignment, or removing dead variables.

beginner
debugging · go · compile

Gin — panic on duplicate route or wildcard conflict

Fix Gin routing panics by removing conflicting paths and using consistent wildcard parameters.

beginner
debugging · go · gin

Go — CPU Throttling in Containers: GOMAXPROCS Mismatch

Diagnose latency spikes from Go running with host-sized GOMAXPROCS inside CPU-limited containers, read throttling metrics, and align the value with the quota.

advanced
debugging · go · containers · performance

GORM — record not found error on a lookup

Handle GORM ErrRecordNotFound by using Find for optional lookups and checking errors explicitly.

beginner
debugging · go · gorm

Go — Goroutine Count Climbs Steadily: a Leak Found with pprof

Diagnose steadily growing goroutine counts, capture pprof goroutine profiles, read the blocked-on stacks, and close the channel or context that never fires.

advanced
debugging · go · goroutines · pprof

Go — gRPC DeadlineExceeded cascading through services

Diagnose cascading gRPC DeadlineExceeded by propagating context deadlines and shortening downstream timeouts.

advanced
debugging · go · grpc

Go — HTTP Response Body Not Closed: Connections and Goroutines Leak

Fix connection growth and read-loop goroutine leaks caused by unclosed http.Response bodies, verify with fd counts and pprof, and close on every path.

intermediate
debugging · go · http · resource-leak

Go — Default HTTP Client Has No Timeout: Goroutines Hang Forever

Fix goroutines parked forever in net/http when using the default client, set client timeouts coarsely and per-request via context, and verify with load.

intermediate
debugging · go · http · timeouts

Go — import cycle not allowed

Break Go import cycles by moving shared types into a third package or inverting the dependency direction.

intermediate
debugging · go · build

Go — inconsistent vendoring error

Fix inconsistent vendoring by syncing the vendor directory with go.mod or disabling vendoring explicitly.

beginner
debugging · go · modules

Go — panic: index out of range on a slice or array

Fix index out of range panics by validating bounds before access and handling slice length explicitly.

beginner
debugging · go · runtime

Go — json: cannot unmarshal string into Go struct field

Resolve json: cannot unmarshal errors in Go by reading the exact field and value types in the message, fixing struct tags or custom unmarshalers for union types.

beginner
debugging · go · json · api

Go — Flaky Tests from Random Map Iteration Order

Eliminate flaky Go tests caused by randomized map iteration order, detect the class with -count and shuffle runs, and sort keys where order matters.

beginner
debugging · go · maps · testing

Go — checksum mismatch when downloading a module

Resolve module checksum mismatches by clearing the cache, verifying go.sum, and checking proxies and tags.

intermediate
debugging · go · modules

Go — panic: assignment to entry in nil map

Fix panic: assignment to entry in nil map by finding uninitialized maps, distinguishing read-safe nil maps from write-unsafe ones, and initializing before use.

beginner
debugging · go · maps · runtime

Go — Slice Append Aliasing Corrupts Data

Debug silent data corruption when two slices share a backing array, predict when append copies versus writes in place, and clone slices at ownership boundaries.

intermediate
debugging · go · slices · memory

Go — database/sql Pool Exhaustion from Unclosed Rows

Diagnose sql: connection pool exhausted errors in Go, find rows.Next loops without defer rows.Close, and restore pooling with deterministic resource handling.

intermediate
debugging · go · database · resource-leak

Go — sync.WaitGroup deadlock or negative counter panic

Fix WaitGroup misuse by adding before goroutines start and passing counters by pointer or closure.

intermediate
debugging · go · concurrency

Go — time.Parse Fails: parsing time with the wrong layout

Fix parsing time ... as ... errors in Go by learning the reference-time layout system, mapping real timestamp shapes to layouts, and testing at boundaries.

beginner
debugging · go · time · parsing

Go — Typed nil: a Non-Nil Interface Holding a nil Pointer

Explain why a nil *T stored in an interface compares non-nil in Go, find the functions returning typed nils, and fix the boundary with explicit nil returns.

intermediate
debugging · go · interfaces · nil

Go — go vet copylocks: Mutex Copied by Value

Understand the copylocks vet warning when structs containing sync.Mutex are copied, see why it corrupts locking, and pass pointers or embed the mutex explicitly.

intermediate
debugging · go · vet · concurrency

HikariCP — Connection is not available, request timed out after 30000ms

Diagnose HikariCP connection pool exhaustion, read active and pending counts, find connection-holding code (missing close, long transactions), and size the pool correctly.

intermediate
debugging · java · connection-pool · hikari

WebSocket Handshake Fails Behind a Proxy — Upgrade Not Forwarded

Fix WebSocket 400/failed upgrades where nginx or gateways do not forward the Upgrade handshake, configure hop-by-hop headers, and keep the connection alive.

intermediate
debugging · websocket · nginx · proxy

HTTP 429 — Retry Storm Makes Rate Limiting Worse

Handle 429 responses without amplifying load: honor Retry-After, add jittered exponential backoff, deduplicate callers, and shed load before the limit.

intermediate
debugging · http · rate-limiting · resilience

HTTP — 431 Request Header Fields Too Large

Fix HTTP 431 by reducing oversized cookies and headers and raising server header buffer limits appropriately.

intermediate
debugging · http · headers

HTTP 504 — Locating Which Layer Timed Out in a Proxy Chain

Trace 504 and Cloudflare 524 errors through CDN, load balancer, and app layers by reading response headers and per-layer logs, then align timeout budgets.

intermediate
debugging · http · timeouts · infrastructure

HTTP Caching — Authenticated Responses Leak Through Shared Caches

Prevent private data leaking through CDN and intermediary caches, understand why authenticated responses need explicit Cache-Control private, and audit cache keys.

advanced
debugging · security · caching · http

HTTP — ETag Revalidation Serves Stale or Never Caches

Debug ETag and If-None-Match behavior: 304 responses that carry changed content, caches that never store, and weak versus strong validator mismatches.

intermediate
debugging · http · caching · etag

HTTP — Double Compression Breaks Responses or Wastes Them

Diagnose Content-Encoding applied twice: mojibake or decompression failures downstream, and wasted CPU compressing already-compressed bytes. Fix the pipeline order.

intermediate
debugging · http · compression · proxy

HTTP/2 — ERR_HTTP2_STREAM_ERROR and GOAWAY Mid-Session

Diagnose HTTP/2 stream resets and GOAWAY terminations mid-session, distinguish protocol errors from graceful shutdowns, and isolate misbehaving intermediaries.

advanced
debugging · http2 · protocol · network

mTLS — 400 No Required SSL Certificate Was Sent

Diagnose mTLS failures from nginx and load balancers: missing client cert, wrong CA trust, expiry, and depth issues, verified with openssl s_client.

advanced
debugging · mtls · nginx · tls

SameSite=Lax — Cookies Missing on Cross-Site POST

Diagnose sessions that work for navigation but vanish on cross-site POSTs and iframes, understand Lax default semantics, and fix flow structure or cookie policy.

beginner
debugging · http · cookies · samesite

HTTP — too many redirects when fetching a URL

Diagnose redirect loops by tracing the Location chain and finding the mismatched rule that creates the cycle.

intermediate
debugging · http · redirects

HTTP — Chunked Responses Truncated by a Proxy

Debug truncated chunked responses where intermediaries mis-handle Transfer-Encoding, compare Content-Length expectations, and fix buffering or streaming layers.

intermediate
debugging · http · streaming · proxy

postMessage Silently Ignored — Origin Mismatch in iframes

Debug postMessage messages that never arrive, where targetOrigin and event.origin disagree, verify both sides of the handshake, and validate strictly.

intermediate
debugging · browser · iframe · postmessage

LCP Image Regression — loading=lazy on the Above-the-Fold Hero

Diagnose LCP regressions caused by lazy-loading the hero image, confirm with field and lab data, and reserve layout space while loading the fold eagerly.

beginner
debugging · performance · lcp · images

Java — ClassCastException at runtime

Resolve ClassCastException by tracing the actual runtime type and correcting generics or casts.

beginner
debugging · java · types

Java — ConcurrentModificationException while iterating

Fix ConcurrentModificationException by removing elements through the iterator or using concurrent collections.

beginner
debugging · java · collections

Java — Hibernate LazyInitializationException outside a session

Fix LazyInitializationException by fetching the needed associations within the transaction or using DTOs.

intermediate
debugging · java · hibernate

Java — OutOfMemoryError: Metaspace from class loading

Fix Metaspace OOM by finding classloader leaks from repeated dynamic class generation or undeployed apps.

advanced
debugging · java · jvm

Java — NoClassDefFoundError at runtime though the class compiled

Fix NoClassDefFoundError by finding why a class present at compile time is missing or failed at runtime.

intermediate
debugging · java · build

Java — NoSuchMethodError at runtime after a dependency change

Fix NoSuchMethodError by detecting duplicate dependency versions causing the wrong class to load.

advanced
debugging · java · dependencies

Java — NullPointerException with a helpful message

Locate the null source of a NullPointerException by using helpful messages, stack traces and defensive access.

beginner
debugging · java · jvm

Java — OutOfMemoryError: Direct buffer memory

Diagnose direct buffer exhaustion by tracking native memory use and MaxDirectMemorySize, not only the heap.

advanced
debugging · java · memory

Java — Spring BeanCreationException caused by a dependency

Trace Spring bean creation failures through the caused-by chain to the real root cause and its configuration.

intermediate
debugging · java · spring

Java — StackOverflowError from runaway recursion

Find the unbounded recursion behind StackOverflowError and convert it to iteration or bounded depth.

intermediate
debugging · java · jvm

Java — UnsupportedClassVersionError: compiled by a more recent version

Fix UnsupportedClassVersionError by aligning the compiler release target with the runtime JDK.

beginner
debugging · java · build

JavaScript — Cannot read properties of undefined (reading X)

Locate the undefined receiver by reading the stack, adding guards and tracing where the value should have been assigned.

beginner
debugging · javascript

JavaScript — TypeError: X is not a function

Diagnose "is not a function" by verifying the value at the call site, checking imports and avoiding this-binding pitfalls.

beginner
debugging · javascript

JWT — invalid audience error when verifying a token

Fix JWT audience errors by aligning the aud claim with the expected value and the resource that verifies it.

intermediate
debugging · jwt · auth

JWT — token expired error even with a fresh login

Diagnose JWT expiry errors by checking the exp claim, clock skew and token refresh timing.

intermediate
debugging · jwt · auth

Kubernetes — Job fails with BackoffLimitExceeded

Diagnose BackoffLimitExceeded by reading pod failure reasons and deciding between fixing the job and adjusting retries.

intermediate
debugging · kubernetes · jobs

Kubernetes — pod restarts in a loop from a failed liveness probe

Fix liveness probe restart loops by tuning thresholds and separating startup from steady-state checks.

intermediate
debugging · kubernetes · probes

Kubernetes — node stuck in NotReady state

Diagnose NotReady nodes by inspecting kubelet health, resource pressure conditions and network reachability.

intermediate
debugging · kubernetes · nodes

Kubernetes — CreateContainerConfigError from a missing secret key

Resolve Kubernetes secret key errors by verifying the secret exists, holds the key and is mounted correctly.

beginner
debugging · kubernetes · secrets

Layout Thrashing — Scroll Handlers Force Synchronous Reflows

Eliminate layout thrashing where JavaScript interleaves layout reads and writes, measure reflows with DevTools, and batch with requestAnimationFrame or transforms.

intermediate
debugging · performance · layout · javascript

INP Failures — Long Tasks Block Input Handling

Improve Interaction to Next Paint by finding long tasks that delay event handlers, use scheduler.yield and code splitting, and break up render-blocking work.

intermediate
debugging · performance · inp · javascript

MongoDB — explain() Reveals COLLSCAN on a Hot Query

Fix MongoDB queries doing full collection scans, read explain() stage trees, build compound indexes respecting ESR order, and cover the query to avoid FETCH.

intermediate
debugging · mongodb · indexes · query-planning

MongoDB — E11000 duplicate key error on insert

Resolve MongoDB E11000 by identifying the unique index and using upsert or idempotent writes.

intermediate
debugging · mongodb · indexes

MySQL — Aborted connection ... Got timeout reading communication packets

Investigate MySQL aborted connection warnings, separate client-side abandonment from network issues, and align wait_timeout with pooled connection lifecycles.

intermediate
debugging · mysql · connections · network

MySQL — Illegal mix of collations in a JOIN or WHERE

Fix MySQL Illegal mix of collations errors between utf8mb4_general_ci and utf8mb4_0900_ai_ci, understand when the error fires versus silent index loss, and unify charsets.

intermediate
debugging · mysql · collation · charset

MySQL — Deadlock Found When Trying to Get Lock (ERROR 1213)

Analyze MySQL ERROR 1213 Deadlock found when trying to get lock using SHOW ENGINE INNODB STATUS, fix lock ordering and indexing, and retry transactions idempotently.

advanced
debugging · mysql · innodb · transactions

MySQL — error 1045 Access denied for user

Resolve MySQL 1045 access denied by checking user host matching, authentication plugin and password configuration.

beginner
debugging · mysql · auth

MySQL — error 1366 Incorrect string value for a column

Fix MySQL 1366 by aligning connection, column and table character sets with the data being stored.

intermediate
debugging · mysql · charset

MySQL — Sorts Spill to Disk: Creating tmp table to disk

Fix slow ORDER BY and GROUP BY queries whose sorts and temp tables spill to disk, size sort_buffer and tmp_table appropriately, and index the sort order.

intermediate
debugging · mysql · query-tuning · performance

MySQL — Cannot Delete or Update a Parent Row: Foreign Key Constraint Fails

Resolve ERROR 1451 foreign key constraint fails by finding referencing rows across child tables, deciding cascade or restrict semantics, and deleting in dependency order.

beginner
debugging · mysql · foreign-keys · transactions

MySQL — MySQL server has gone away during a query

Fix "server has gone away" by checking max_allowed_packet, wait_timeout and connection health under load.

intermediate
debugging · mysql · networking

MySQL — ORM N+1 Queries Turn a Page Load into a Query Storm

Detect N+1 query patterns from ORMs with the general query log, confirm with query counts per request, and eliminate them with eager loading and joins.

intermediate
debugging · mysql · orm · performance

MySQL — Replication Lag: Seconds_Behind_Master Keeps Growing

Diagnose growing MySQL replication lag with SHOW REPLICA STATUS and performance_schema, separate IO from SQL thread stalls, and fix the bottleneck side.

intermediate
debugging · mysql · replication · performance

nginx — 499 status meaning the client closed the request

Interpret nginx 499 status by relating client timeouts to slow upstream responses and tuning timeouts accordingly.

intermediate
debugging · nginx · http

Node.js — AbortController signal has no effect on a fetch

Fix uncancelled fetch calls by passing the signal correctly and distinguishing connect-time from body-read cancellation.

intermediate
debugging · node · async

Node.js — Heap Out of Memory Caused by Missing Stream Backpressure

Diagnose heap out of memory while streaming large responses or files, spot the writable that never waits for drain, and add backpressure with pipeline and highWaterMark.

advanced
debugging · nodejs · streams · memory

Node.js — RangeError: Invalid string length or buffer too large

Resolve range errors from oversized strings or buffers by streaming data instead of concatenating it in memory.

intermediate
debugging · node · memory

Node.js — Cannot use import statement outside a module

Fix "Cannot use import statement outside a module" by aligning the package type, file extension and tooling with ES modules.

beginner
debugging · node · esm

Node.js — TypeError: Converting Circular Structure to JSON

Diagnose Converting circular structure to JSON when stringifying objects with cycles, find the back-reference in request or ORM objects, and serialize a safe projection.

beginner
debugging · nodejs · json · serialization

Node.js — Circular require Produces undefined Exports at Startup

Diagnose TypeError cannot read properties of undefined caused by CommonJS circular requires, read the partial export cache, and break the cycle with lazy requires or modules.

intermediate
debugging · nodejs · commonjs · modules

Node.js — ERR_CRYPTO_INVALID_KEY_OBJECT_TYPE or invalid key errors

Fix crypto key errors by matching key format, algorithm and purpose, for example using the right PEM for sign versus verify.

intermediate
debugging · node · crypto

Node.js — getaddrinfo EAI_AGAIN Under Concurrency

Diagnose EAI_AGAIN DNS failures that appear only under load in Node.js, measure resolver concurrency limits, and cache or prefetch lookups with a resolver agent.

intermediate
debugging · nodejs · dns · network

Node.js — ECONNREFUSED when connecting to a service

Diagnose ECONNREFUSED by checking whether anything listens on the target host and port and whether the address resolves as expected.

beginner
debugging · node · networking

Node.js — ETIMEDOUT or socket hang up on outbound requests

Diagnose ETIMEDOUT by separating network reachability, firewall drops and missing client timeouts.

intermediate
debugging · node · networking

Node.js — The Process Never Exits: Something Holds the Loop

Find why a Node.js script finishes its work but the process stays alive, enumerate active handles and ref state, and unref or close the right resource.

intermediate
debugging · nodejs · event-loop · lifecycle

Node.js — Requests Time Out While CPU Stays Idle: a Blocked Loop

Find the synchronous operation blocking the Node.js event loop, use monitorEventLoopDelay and blocked-at to time and localize it, and move the work off the loop.

advanced
debugging · nodejs · performance · event-loop

Node.js — MaxListenersExceededWarning on a Growing EventEmitter

Investigate MaxListenersExceededWarning: possible EventEmitter memory leak, find who adds listeners per request, and fix the registration and removal lifecycle.

beginner
debugging · nodejs · events · memory

Node.js child_process — Error: maxBuffer exceeded

Fix Error: maxBuffer exceeded from exec by measuring real output size, choosing execFile with streams for large output, and parsing incrementally.

beginner
debugging · nodejs · child-process · streams

Node.js — TypeError: Failed to parse URL from /api

Fix relative URL errors in Node fetch by resolving URLs against a base, since server-side fetch has no document origin.

beginner
debugging · node · fetch

Node.js — SIGTERM Kills In-Flight Requests During Deploys

Fix 502 bursts during rolling deploys by handling SIGTERM properly: stop accepting, close idle keep-alive connections, await in-flight work, then exit within budget.

intermediate
debugging · nodejs · deployment · shutdown

Node.js — ERR_HTTP2_GOAWAY_SESSION When the Server Sends GOAWAY

Diagnose ERR_HTTP2_GOAWAY_SESSION in Node.js http2 clients, correlate it with server GOAWAY frames and idle timeouts, and drain in-flight streams before reconnecting.

advanced
debugging · nodejs · http2 · network

Node.js — Error: listen EACCES When Binding Port 443 or 80

Resolve listen EACCES on privileged ports in Node.js by identifying the capability boundary, then use setcap, port redirection, or an unprivileged reverse proxy.

beginner
debugging · nodejs · network · linux

Node.js — MODULE_NOT_FOUND in Production from a Phantom Dependency

Track down Cannot find module errors that only appear in production, identify packages that worked via hoisting, and pin every real import as a declared dependency.

intermediate
debugging · nodejs · npm · dependencies

Node.js — Segfault in a Native Module After a Runtime Upgrade

Investigate Segmentation fault core dumped from native addons after a Node upgrade, verify NODE_MODULE_VERSION mismatches, and rebuild against the current ABI.

advanced
debugging · nodejs · native-modules · abi

Node.js — error:0308010C digital envelope routines::unsupported

Fix error:0308010C digital envelope routines::unsupported by mapping it to the OpenSSL 3 md4 removal, then upgrade the toolchain or enable the legacy provider deliberately.

advanced
debugging · nodejs · openssl · build

Node.js — Cannot Find Module for a Platform-Specific Optional Dependency

Fix Cannot find module errors like @swc/core-linux-x64-gnu by understanding optionalDependencies install behavior and locking the platform artifact in CI.

intermediate
debugging · nodejs · npm · native-modules

PM2 — max_memory_restart Causes a Restart Loop

Investigate PM2 restart loops where RSS crosses max_memory_restart, separate leaks from baseline growth, and size the limit against real memory profiles.

intermediate
debugging · nodejs · pm2 · memory

Node.js — process.exit() Truncates Piped stdout

Explain why calling process.exit() mid-write truncates output when stdout is a pipe, and replace it with a drain-aware shutdown that flushes every buffer.

beginner
debugging · nodejs · cli · stdout

Node.js — ERR_REQUIRE_ESM When require() Meets an ESM-Only Package

Resolve ERR_REQUIRE_ESM by checking the package exports field and type, then migrate the importer to dynamic import, ESM syntax, or a CJS-compatible version.

intermediate
debugging · nodejs · esm · modules

Node.js — EPIPE Crashes When Piping stdout to head

Stop Node.js from crashing with EPIPE when consumers close the pipe early, distinguish write-after-close from reader death, and exit gracefully on expected closes.

intermediate
debugging · nodejs · cli · streams

Node.js — ERR_STREAM_PREMATURE_CLOSE on HTTP Responses

Find why Node.js pipelines report ERR_STREAM_PREMATURE_CLOSE, separate server-side aborts from client disconnects, and fix both the response handling and the error path.

intermediate
debugging · nodejs · streams · http

Node.js — ERR_STREAM_WRITE_AFTER_END in Response Streams

Diagnose write after end errors on Node.js streams, find the double callback or late write in retry and middleware paths, and guard the writable lifecycle.

intermediate
debugging · nodejs · streams · http

Node.js — SyntaxError: Unexpected token caught at startup

Locate syntax errors quickly by reading the reported position and isolating the file from the build output.

beginner
debugging · node · syntax