Debugging Guides
Distinguish symptoms from root causes, then verify the fix.
697 published
Page 6 of 7
Node.js — unable to verify the first certificate
Resolve TLS verification errors in Node by fixing the CA trust and the presented chain, not by disabling verification.
Node.js fetch — UND_ERR_HEADERS_TIMEOUT Against Slow Upstreams
Explain UND_ERR_HEADERS_TIMEOUT from the Node fetch global, measure where response headers stall, and configure undici timeouts per endpoint instead of globally.
Node.js — server.listen EADDRINUSE in tests or watch mode
Fix EADDRINUSE in tests and watch mode by releasing ports, using port 0, and closing servers after each test.
Node.js — Worker Thread Exits with Code 13 (Unfinished Work)
Decode worker_threads exit code 13, distinguish it from crashes and uncaught exceptions, and shut workers down cleanly with explicit completion signaling.
Node.js — worker thread does not exit or terminate
Fix worker threads that never terminate by closing message channels, avoiding active handles and calling terminate as a fallback.
npm — ERR! code EINTEGRITY from a Corrupted Cache
Resolve npm ERR! code EINTEGRITY integrity check failures by verifying the lockfile hash source, clearing the right cache slice, and pinning registry mirrors.
OAuth — Concurrent Refreshes Race and Return invalid_grant
Fix 401 storms caused by concurrent refresh token requests invalidating each other, serialize refresh per session, and handle rotation gracefully.
PostgreSQL — ERROR: canceling statement due to statement timeout
Investigate PostgreSQL canceling statement due to statement timeout, find which layer set the deadline, measure the query real cost, and fix the plan or the budget.
PostgreSQL — CREATE INDEX Locks the Table: Use CONCURRENTLY
Fix write stalls during index creation on PostgreSQL, understand the ACCESS EXCLUSIVE lock of plain CREATE INDEX, and use CONCURRENTLY with its caveats.
PostgreSQL — JSONB Queries Trigger Full Table Scans
Make PostgreSQL use indexes for JSONB containment and path queries, choose between GIN default and jsonb_path_ops operators, and restructure hot predicates as columns.
PostgreSQL — Queries Pile Up Waiting on Locks
Diagnose PostgreSQL statements blocked behind a long-running lock holder using pg_locks joins, find the blocking query and session, and fix the holder pattern.
PostgreSQL — ERROR: out of shared memory During Heavy DDL
Resolve PostgreSQL out of shared memory errors from lock table overflow by understanding max_locks_per_transaction, sizing it for DDL fan-out, and batching schema changes.
PostgreSQL — EXPLAIN Shows Seq Scan Despite an Existing Index
Find why PostgreSQL chooses a sequential scan over an existing index: type mismatches, functions on columns, stale statistics, and low selectivity — then fix each.
PostgreSQL — nextval: reached maximum value of sequence
Fix PostgreSQL nextval reached maximum value of sequence errors, check int4 versus bigint column pairs, plan the migration without downtime, and burn nothing.
PostgreSQL — Table Bloat: Autovacuum Cannot Keep Up
Diagnose PostgreSQL table bloat where dead tuples accumulate and autovacuum never completes, tune per-table autovacuum settings, and rebuild with pg_repack.
PostgreSQL — duplicate key value violates unique constraint Despite a Check
Explain duplicate key violations under concurrency despite check-then-insert code, use ON CONFLICT for atomic upserts, and handle serialization failures correctly.
PostgreSQL — error 22P02 invalid input syntax for type
Fix PostgreSQL 22P02 by matching the literal format to the column type and validating input before the insert.
PostgreSQL — error 23503 foreign key constraint violation
Diagnose PostgreSQL 23503 by identifying which referencing row lacks a matching parent and ordering the writes correctly.
PostgreSQL — error 42P01 relation does not exist
Resolve PostgreSQL 42P01 by checking search_path, schema qualification and whether the migration created the table in the expected schema.
Python asyncio — gather() Cancels Sibling Tasks on First Failure
Understand why asyncio.gather aborts remaining awaitables when one raises, keep sibling work alive with return_exceptions, and handle ExceptionGroup-style fan-out failures.
Python — RuntimeError: event loop is already running
Resolve "loop already running" errors when nesting asyncio run calls or calling async code from a synchronous context.
Python — RuntimeError: asyncio.run() cannot be called from a running event loop
Resolve asyncio.run() cannot be called from a running event loop in notebooks and frameworks, find the outer loop owner, and await coroutines directly instead.
Python — RuntimeWarning: coroutine was never awaited
Diagnose RuntimeWarning coroutine never awaited, find call sites that invoke async functions without awaiting or scheduling, and close orphans deterministically.
Celery — Received unregistered task of type error
Fix Celery "unregistered task" by ensuring workers import the module that defines the task and use the same app and name.
Python — ImportError: cannot import name from partially initialized module
Resolve ImportError from partially initialized modules by reading the import chain in the traceback, then break Python circular imports with leaf modules or deferred imports.
Python csv — Extra Blank Lines in Output on Windows
Fix doubled newlines in csv.writer output on Windows by understanding text-mode translation, and open files with newline="" as the csv module requires.
Python — Interpreter Hangs at Exit Because of Non-Daemon Threads
Find why Python waits for non-daemon threads at shutdown, identify the thread that never finishes, and join threads with timeouts at program exit.
Python — TypeError: can't compare offset-naive and offset-aware datetimes
Fix the naive-versus-aware datetime TypeError, decide the single timezone convention for the codebase, and convert at the boundaries instead of patching comparisons.
Django — "no such table" after starting the server
Diagnose Django "no such table" errors by confirming which database the running process uses and whether migrations were applied to it.
FastAPI — request fails with 422 Unprocessable Entity
Read FastAPI 422 validation error responses to find which field and rule rejected the request body.
FastAPI — One Slow sync def Endpoint Blocks All Requests
Diagnose FastAPI endpoints declared with sync def that block the event loop, read the threadpool exhaustion pattern, and move CPU or IO-heavy work correctly.
Python — FileNotFoundError with a path that exists
Fix FileNotFoundError by resolving the working directory, since relative paths depend on where the process was started.
Flask — port 5000 already in use when starting the dev server
Resolve Flask address-in-use errors by finding the process bound to the port and choosing a free port or fixing the stale server.
Python — Memory Grows Despite Freed Objects: gc Cycles
Investigate Python memory growth that survives manual del, find reference cycles with gc.get_referrers and objgraph, and break cycles with weakref or explicit close.
Python — Multithreaded CPU Work Runs No Faster Than Single Thread
Explain why threading.Thread gives no speedup for CPU-bound Python code, measure the GIL effect with timings, and switch to processes or native extensions.
Gunicorn — WORKER TIMEOUT and workers are killed
Diagnose Gunicorn worker timeouts by locating blocking request handlers and tuning timeout and worker class appropriately.
Python — High RSS After Processing Large Datasets
Explain why Python RSS stays high after big objects are freed, separate allocator arena retention from true leaks with tracemalloc, and release pages deliberately.
Python — json.decoder.JSONDecodeError on parsing a response
Debug JSONDecodeError by inspecting the raw bytes actually received, since empty or HTML bodies parse as invalid JSON.
Python — Log Messages Appear Multiple Times
Fix duplicated Python log lines by finding repeated addHandler calls and propagating records between loggers, then configure handlers once at the root.
Python — multiprocessing Raises Can't pickle on Windows and macOS
Fix PicklingError and AttributeError in multiprocessing under the spawn start method, pass picklable arguments only, and guard module-level side effects.
Python — OSError: [Errno 24] Too many open files
Trace Python file descriptor leaks with lsof and fd counts, find open calls missing with or close, and switch to context managers everywhere.
Python — OSError: [Errno 98] Address already in use when binding a socket
Resolve address-in-use errors by releasing the socket, enabling reuse options and understanding TIME_WAIT behavior.
Pandas — SettingWithCopyWarning and Silently Dropped Writes
Explain SettingWithCopyWarning, find chained indexing that writes into a temporary copy, and adopt .loc single-step assignment plus copy() for intentional snapshots.
pandas — SettingWithCopyWarning when assigning to a slice
Eliminate SettingWithCopyWarning by using explicit copies and loc-based assignment instead of chained indexing.
Python — PermissionError: [Errno 13] Permission denied on file access
Resolve PermissionError by distinguishing file permission issues from directory, ownership and container boundary problems.
Python — Unpickling Fails After a Class Refactor
Resolve pickle AttributeError Can't get attribute and __reduce__ errors after renaming classes or moving modules, and keep pickles loadable with aliasing.
Python — error: externally-managed-environment Blocks pip install
Understand the PEP 668 externally-managed-environment error in Python 3.11+ system interpreters, and pick the sanctioned path: venv, pipx, or --break-system-packages.
pytest — fixture not found though it is defined
Fix pytest fixture-not-found errors by placing fixtures at the right scope and ensuring conftest files are discoverable.
requests — SSLError: certificate verify failed (hostname mismatch)
Diagnose certificate verify failures by separating hostname mismatch, missing CA trust and expired certificates.
Selenium — WebDriverException: unknown error on browser start
Fix Selenium WebDriverException by matching the driver to the browser version and running headless with adequate container resources.
SQLAlchemy — DetachedInstanceError when accessing attributes
Resolve SQLAlchemy detached instance errors by controlling session lifetime and eager loading needed attributes.
Python — SSLError: wrong version number when using HTTPS
Diagnose the SSL wrong version number error by checking whether the endpoint is actually speaking TLS or is behind a misconfigured proxy.
Python — UnicodeEncodeError: charmap codec can't encode character
Fix UnicodeEncodeError on Windows where the console and files default to cp1252, pin UTF-8 on every boundary, and stop replacing errors with question marks.
Python — urllib3 Connection Pool Is Full Warning and Slowdown
Address urllib3 connection pool is full discarding connection warnings, size the pool to real concurrency, and stop discarding keep-alive connections on every request.
React — Controlled Input Lags on Every Keystroke
Fix slow typing in React controlled inputs caused by re-rendering large subtrees per keystroke, profile the render cost, and split state scope or debounce persistence.
React — Index as key Corrupts Row State
Fix React bugs where list rows show wrong state after reorder or deletion, understand why index keys break reconciliation identity, and use stable keys.
React — useEffect Sees Stale State from Closure Capture
Diagnose React effects and callbacks reading old state because closures captured the render-time value, fix dependencies and refs, and avoid the classic timer trap.
React — Effects Fire Twice in Development Under StrictMode
Understand why React StrictMode double-invokes effects in development, why subscriptions and requests duplicate, and how to make cleanup fully symmetric.
React — A Component Suspended with No Fallback UI
Fix React suspended without a fallback error and hydration-time suspension flashes, place Suspense boundaries correctly, and use startTransition for urgent updates.
Redis — SLOWLOG Filled with Big-Key Operations
Diagnose Redis latency spikes from big keys and blocking commands via SLOWLOG and LATENCY HISTORY, find the keys with memory usage analysis, and break them up.
Redis — Periodic Latency Spikes from Fork and Swap
Track down Redis latency spikes caused by background save forks and OS swapping using LATENCY HISTORY, measure fork rates, and fix memory overcommit and THP.
Redis — NOAUTH Authentication required
Fix Redis NOAUTH by configuring credentials and aligning the auth setting between server and client.
ResizeObserver Loop Limit Exceeded Warning
Fix ResizeObserver loop completed with undelivered notifications, find the feedback loop between observation and layout writes, and break it with rAF or guards.
Rust — Integer Overflow Panics in Debug, Wraps in Release
Explain why attempt to add with overflow panics in debug builds but wraps silently in release, make overflow strategy explicit, and check both profiles in CI.
Rust — async fn in Traits and dyn Compatibility (E0038 / E0277)
Untangle async fn in trait errors before Rust 1.75 and dyn Trait incompatibility, understand the return-position impl Trait limitation, and pick the right pattern per version.
Cargo — build script failed with a confusing exit status
Debug Cargo build script failures by reading build output and reproducing the underlying command.
Cargo — feature not found or dependency feature does not exist
Fix Cargo feature errors by matching declared features and dependency feature names in Cargo.toml.
Rust — E0106 unexpected closing delimiter or mismatched braces
Locate unmatched delimiters in Rust by isolating the region and reading the compiler suggestion.
Rust — error[E0277]: closure cannot be sent between threads safely
Fix `std::thread::spawn` requires closure to be Send errors by finding the Rc, RefCell, or raw pointer captured across the boundary, and swapping in thread-safe types.
Rust — cannot return reference to local temporary value
Fix return-of-local-reference errors by returning owned data or by borrowing a longer-lived source.
Rust — E0308 mismatched types expected X found Y
Resolve E0308 mismatched type errors by aligning types, handling Option and Result, and fixing references versus values.
Rust — error[E0373]: closure may outlive the current function
Fix E0373 closure may outlive the current function by understanding borrowed captures versus move semantics, and pass ownership or clone into long-lived closures.
Rust — E0382 use of moved value
Fix E0382 by cloning, borrowing instead of moving, or restructuring ownership so the value stays available.
Rust — E0432 lifetime may not live long enough
Fix lifetime errors by relating input and output lifetimes or by returning owned data instead of references.
Rust — E0499 cannot borrow as mutable more than once at a time
Fix E0499 by scoping mutable borrows, using reborrowing, or restructuring to hold one mutable reference.
Rust — E0502 cannot borrow as mutable because it is also borrowed as immutable
Resolve E0502 borrow conflicts by shortening immutable borrows and restructuring to avoid overlapping borrows.
Rust — error[E0716]: temporary value dropped while borrowed
Resolve error[E0716] temporary value dropped while borrowed, see why let x = &foo().bar fails, and bind the intermediate value with let before borrowing.
Rust — Lifetime Errors from Multiple Anonymous References
Demystify lifetime errors like explicit lifetime required with two reference parameters, apply elision rules deliberately, and annotate the data flow you intend.
Rust — Poisoned Mutex: Another Task Failed While Holding the Lock
Handle poisoning errors from std Mutex in Rust, understand why panics poison locks, recover with into_inner or explicit state validation, and prevent poisoning.
Rust — panicked at called Option::unwrap() on a None value
Debug panics from Option and Result unwrap in Rust, read the panic location and backtrace, replace hot-path unwrap with explicit handling, and use expect with context.
Rust — Rc Reference Cycles Leak Memory
Diagnose memory growth in Rust from Rc and RefCell cycles that the ownership model cannot free, break cycles with Weak, and verify with leak tests.
Serde — missing field or invalid type when deserializing
Fix Serde deserialization errors by matching field names, adding defaults and handling optional fields.
Rust — tokio::spawn Requires Future + Send: async Blocks with Rc
Resolve future cannot be sent between threads safely in tokio::spawn, find the Rc or non-Send captured across await points, and restructure or localize the borrowing.
Tokio — Cannot start a runtime from within a runtime
Fix nested Tokio runtime errors by using async contexts, spawn_blocking or Runtime::enter as appropriate.
Service Worker — Users Stuck on the Old Version After Deploy
Fix users permanently served stale assets by a Service Worker cache, understand update activation semantics, and deploy versioned caches with proper cleanup.
SQLite — WAL File Grows Without Bound and Checkpoints Stall
Diagnose an ever-growing SQLite WAL file, find the long-running reader blocking checkpoints, and restore checkpointing with timeouts and reader discipline.
SRI Failure — Failed to Find a Valid Digest in the integrity Attribute
Fix Failed to find a valid digest in the integrity attribute when CDN assets and SRI hashes disagree, recompute hashes correctly, and automate them.
Terraform — provider version conflict or failed to query provider
Fix provider version conflicts by constraining versions and refreshing the dependency lock file.
Terraform — Error acquiring the state lock
Resolve Terraform state lock errors by confirming no run is active and force-unlocking only when safe.
Third-Party Cookies Blocked — Iframe Login State Silently Lost
Debug cross-site iframes losing session cookies as browsers phase out third-party cookies, verify with partitioned storage tests, and migrate to token patterns.
TLS — certificate has expired error
Diagnose expired TLS certificates by checking validity dates, clock skew and whether the presented certificate is the expected one.
TypeScript — TS18048: Value is possibly undefined in strict mode
Handle TS18048 by structuring code so optional values are narrowed before use, avoiding non-null assertions.
TypeScript — TS2307: Cannot find module or its type declarations
Fix TS2307 by correcting module resolution settings and installing the missing type declarations.
TypeScript — TS2322: Type is not assignable to type
Resolve TS2322 by aligning the declared and actual types, widening narrow literals or narrowing unions correctly.
TypeScript — TS2339: Property does not exist on type
Fix TS2339 by narrowing unions, extending interfaces, or correcting the type instead of asserting.
TypeScript — TS2532: Object is possibly undefined
Resolve possible-undefined errors with proper guards, optional chaining and a clear decision about missing values.
TypeScript — TS2739: Type is missing properties from type
Fix missing-property errors by constructing complete object literals or reusing helper factories and interfaces.
TypeScript — TS2769: No overload matches this call
Debug TS2769 by reading the overload list and matching argument types to the intended signature.
TypeScript — TS6133: Variable is declared but never read
Resolve unused variable errors by removing dead code, prefixing intentional ignores, or adjusting lint and compiler settings.
TypeScript — TS7006: Parameter implicitly has an any type
Fix implicit any errors by annotating parameters or providing enough contextual type from call sites.