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.

intermediate
debugging · node · tls

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.

intermediate
debugging · nodejs · fetch · undici

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.

intermediate
debugging · node · testing

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.

advanced
debugging · nodejs · worker-threads · concurrency

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.

advanced
debugging · node · workers

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.

intermediate
debugging · npm · tooling

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.

advanced
debugging · oauth · authentication · concurrency

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.

beginner
debugging · postgresql · timeouts · query-tuning

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.

intermediate
debugging · postgresql · ddl · locks

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.

intermediate
debugging · postgresql · jsonb · indexes

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.

intermediate
debugging · postgresql · locks · performance

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.

advanced
debugging · postgresql · locks · configuration

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.

intermediate
debugging · postgresql · query-planning · indexes

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.

beginner
debugging · postgresql · sequences · schema

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.

advanced
debugging · postgresql · vacuum · performance

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.

intermediate
debugging · postgresql · concurrency · upsert

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.

beginner
debugging · postgres · sql

PostgreSQL — error 23503 foreign key constraint violation

Diagnose PostgreSQL 23503 by identifying which referencing row lacks a matching parent and ordering the writes correctly.

beginner
debugging · postgres · sql

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.

beginner
debugging · postgres · sql

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.

intermediate
debugging · python · asyncio · concurrency

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.

intermediate
debugging · python · asyncio

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.

beginner
debugging · python · asyncio · jupyter

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.

beginner
debugging · python · asyncio · warnings

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.

intermediate
debugging · python · celery

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.

intermediate
debugging · python · imports · modules

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.

beginner
debugging · python · csv · windows

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.

intermediate
debugging · python · threading · shutdown

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.

beginner
debugging · python · datetime · timezone

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.

beginner
debugging · python · django

FastAPI — request fails with 422 Unprocessable Entity

Read FastAPI 422 validation error responses to find which field and rule rejected the request body.

beginner
debugging · python · fastapi

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.

intermediate
debugging · python · fastapi · asyncio

Python — FileNotFoundError with a path that exists

Fix FileNotFoundError by resolving the working directory, since relative paths depend on where the process was started.

beginner
debugging · python · filesystem

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.

beginner
debugging · python · flask

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.

advanced
debugging · python · memory · gc

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.

intermediate
debugging · python · concurrency · performance

Gunicorn — WORKER TIMEOUT and workers are killed

Diagnose Gunicorn worker timeouts by locating blocking request handlers and tuning timeout and worker class appropriately.

intermediate
debugging · python · gunicorn

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.

advanced
debugging · python · memory · performance

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.

beginner
debugging · python · 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.

beginner
debugging · python · logging · stdlib

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.

intermediate
debugging · python · multiprocessing · pickling

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.

beginner
debugging · python · file-io · resource-leak

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.

beginner
debugging · python · networking

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.

intermediate
debugging · python · pandas · data-science

pandas — SettingWithCopyWarning when assigning to a slice

Eliminate SettingWithCopyWarning by using explicit copies and loc-based assignment instead of chained indexing.

intermediate
debugging · python · pandas

Python — PermissionError: [Errno 13] Permission denied on file access

Resolve PermissionError by distinguishing file permission issues from directory, ownership and container boundary problems.

beginner
debugging · python · filesystem

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.

intermediate
debugging · python · pickle · serialization

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.

beginner
debugging · python · pip · packaging

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.

beginner
debugging · python · pytest

requests — SSLError: certificate verify failed (hostname mismatch)

Diagnose certificate verify failures by separating hostname mismatch, missing CA trust and expired certificates.

intermediate
debugging · python · tls

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.

intermediate
debugging · python · selenium

SQLAlchemy — DetachedInstanceError when accessing attributes

Resolve SQLAlchemy detached instance errors by controlling session lifetime and eager loading needed attributes.

intermediate
debugging · python · sqlalchemy

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.

intermediate
debugging · python · tls

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.

beginner
debugging · python · unicode · windows

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.

intermediate
debugging · python · http · performance

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.

intermediate
debugging · react · performance · inputs

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.

beginner
debugging · react · keys · state

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.

intermediate
debugging · react · hooks · closures

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.

intermediate
debugging · react · hooks · lifecycle

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.

intermediate
debugging · react · suspense · lazy-loading

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.

intermediate
debugging · redis · latency · bigkeys

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.

advanced
debugging · redis · latency · linux

Redis — NOAUTH Authentication required

Fix Redis NOAUTH by configuring credentials and aligning the auth setting between server and client.

beginner
debugging · redis · auth

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.

intermediate
debugging · browser · resizeobserver · layout

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.

beginner
debugging · rust · integers · build-profiles

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.

advanced
debugging · rust · async · traits

Cargo — build script failed with a confusing exit status

Debug Cargo build script failures by reading build output and reproducing the underlying command.

intermediate
debugging · rust · cargo

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.

beginner
debugging · rust · cargo

Rust — E0106 unexpected closing delimiter or mismatched braces

Locate unmatched delimiters in Rust by isolating the region and reading the compiler suggestion.

beginner
debugging · rust · syntax

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.

intermediate
debugging · rust · concurrency · traits

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.

intermediate
debugging · rust · lifetimes

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.

beginner
debugging · rust · types

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.

intermediate
debugging · rust · closures · ownership

Rust — E0382 use of moved value

Fix E0382 by cloning, borrowing instead of moving, or restructuring ownership so the value stays available.

beginner
debugging · rust · ownership

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.

advanced
debugging · rust · lifetimes

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.

intermediate
debugging · rust · borrow-checker

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.

intermediate
debugging · rust · borrow-checker

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.

intermediate
debugging · rust · borrow-checker · lifetimes

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.

advanced
debugging · rust · lifetimes · borrow-checker

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.

intermediate
debugging · rust · concurrency · mutex

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.

beginner
debugging · rust · panics · error-handling

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.

intermediate
debugging · rust · memory · smart-pointers

Serde — missing field or invalid type when deserializing

Fix Serde deserialization errors by matching field names, adding defaults and handling optional fields.

beginner
debugging · rust · serde

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.

advanced
debugging · rust · tokio · async

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.

advanced
debugging · rust · tokio

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.

intermediate
debugging · pwa · caching · deployment

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.

advanced
debugging · sqlite · database · storage

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.

beginner
debugging · security · cdn · sri

Terraform — provider version conflict or failed to query provider

Fix provider version conflicts by constraining versions and refreshing the dependency lock file.

intermediate
debugging · terraform · providers

Terraform — Error acquiring the state lock

Resolve Terraform state lock errors by confirming no run is active and force-unlocking only when safe.

intermediate
debugging · terraform · state

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.

intermediate
debugging · browser · cookies · authentication

TLS — certificate has expired error

Diagnose expired TLS certificates by checking validity dates, clock skew and whether the presented certificate is the expected one.

beginner
debugging · tls · certificates

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.

intermediate
debugging · typescript

TypeScript — TS2307: Cannot find module or its type declarations

Fix TS2307 by correcting module resolution settings and installing the missing type declarations.

intermediate
debugging · typescript

TypeScript — TS2322: Type is not assignable to type

Resolve TS2322 by aligning the declared and actual types, widening narrow literals or narrowing unions correctly.

beginner
debugging · typescript

TypeScript — TS2339: Property does not exist on type

Fix TS2339 by narrowing unions, extending interfaces, or correcting the type instead of asserting.

beginner
debugging · typescript

TypeScript — TS2532: Object is possibly undefined

Resolve possible-undefined errors with proper guards, optional chaining and a clear decision about missing values.

beginner
debugging · typescript

TypeScript — TS2739: Type is missing properties from type

Fix missing-property errors by constructing complete object literals or reusing helper factories and interfaces.

beginner
debugging · typescript

TypeScript — TS2769: No overload matches this call

Debug TS2769 by reading the overload list and matching argument types to the intended signature.

intermediate
debugging · typescript

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.

beginner
debugging · typescript

TypeScript — TS7006: Parameter implicitly has an any type

Fix implicit any errors by annotating parameters or providing enough contextual type from call sites.

beginner
debugging · typescript