Interview Questions: Debugging Production Issues
Debugging questions in real interviews rarely ask you to name an exception in isolation — they show you a symptom or a snippet and ask you to diagnose it, the same way this chapter's catalog is organized. This set covers all eight categories: Crashes & Exceptions and Performance (Q1-20), then Memory Leaks, Concurrency & Deadlocks, Data Corruption, Deployment & Environment, Database & API Failures, and Logging & Observability (Q21-38).
1 A dict lookup crashes with KeyError in production but never did in testing. Walk me through how you'd debug it.
Start from the traceback: it names the exact missing key and the exact line. The real question is why the key is missing in production but not in tests — usually a config/environment difference (an env var that's set locally but not in the deploy environment, a config file that isn't shipped the same way). The fix depends on whether the key is genuinely optional (use .get() with a sensible default) or required (fail fast at startup with a clear message naming every missing key, not just the first one hit).
Jumping straight to "just use .get() everywhere" without asking whether the key is actually supposed to be required ā that just turns a loud, diagnosable crash into a silent misconfiguration.
"What's the downside of wrapping every dict access in a try/except KeyError?" (It can hide genuine bugs the same way a bare except: does ā the goal is deciding per-key whether missing is expected, not blanket-suppressing the error everywhere.)
2 You see IndexError: list index out of range in a loop that uses range(n). What's your first hypothesis?
range(n) produces indices with no awareness of any particular list's actual length ā it's just a sequence of integers. The first hypothesis is a mismatch between n (however it was chosen) and len(list_being_indexed). I'd check whether n comes from a different source than the list itself (a separate count, a hardcoded assumption, a different collection's length) ā that's almost always where the two silently drift apart.
Suggesting a blanket try/except IndexError around the loop instead of fixing the actual bound ā that hides the bug instead of preventing it.
Follow-up"What's a bound that can never cause this bug?" (range(len(the_actual_list)), or just iterating the list directly instead of indexing by position at all.)
3 What's wrong with a bare except:, specifically ā not "it's bad practice," but what concretely goes wrong?
It catches every exception, not just the one you had in mind ā including ones that indicate a real, unrelated bug (a typo'd dict key, a NameError from a refactor, even KeyboardInterrupt/SystemExit in older code). The concrete failure mode: a function returns a fallback value that looks completely normal, while masking a bug that silently produces wrong behavior for months. The fix is always to name the specific exception you expect (except KeyError:), so anything else still surfaces as its own distinct, diagnosable crash.
A vague "it's just bad style" answer with no concrete failure scenario ā this needs a real example of what breaks.
Follow-up"Is except Exception: just as bad?" (Nearly ā it's slightly narrower than bare except: (it won't catch SystemExit/KeyboardInterrupt), but it's still broad enough to swallow bugs you didn't anticipate, same failure mode.)
4 A TypeError shows up three function calls deep from where the actual bad value entered the system. How do you find the real source?
Read the traceback bottom-to-top: the deepest frame shows where the crash actually happened (the arithmetic that failed), but the value that caused it was likely valid-looking all the way through several calls until it hit an operation that couldn't tolerate its type. I'd trace the value backward through each frame in the traceback to find where it first entered the call chain ā usually external input (form data, a query parameter, an API response) that was never converted or validated at the boundary.
Red flagsOnly looking at the last line of the traceback and proposing a type-check fix at that exact spot, rather than validating input at the actual entry point.
Follow-up"Where's the right place to fix this ā where it crashed, or where the bad value entered?" (Where it entered ā fixing it at the crash site just moves the problem one call deeper next time.)
5 AttributeError: 'NoneType' object has no attribute 'X' is one of the most common production tracebacks. What's the usual root cause?
Almost always a function that returns None on some code path ā often implicitly, by falling through without an explicit return ā and a caller that assumes the return value is always a real object. The fix is either checking for None right where the value comes back, before calling anything on it, or having the source function raise a specific, named exception instead of quietly returning None when nothing was found.
Suggesting a blanket if x: check without recognizing that "falsy but not None" values (empty list, 0, empty string) can trigger the same branch incorrectly if the check isn't specifically is None.
"Why is 'is None' preferred over just 'if not x' here?" (Because a valid-but-falsy value like an empty dict or 0 would be wrongly treated the same as None.)
6 Your custom exception is being raised correctly but a caller's error handling is swallowing it. How do you catch that in code review?
Look specifically at what every except block up the call chain catches ā except Exception: (or bare except:) will catch a specific custom exception right alongside genuine bugs, and treat both the same way. In review, I'd flag any except Exception: that doesn't re-raise or at least log what it caught, and ask whether the more specific exception type should be caught (and handled meaningfully) instead.
Not recognizing that "the exception was raised correctly" and "the exception was handled correctly" are two separate things that both need checking.
Follow-up"What's the danger of a caught exception that fails silently (no log, no re-raise)?" (There's no signal anywhere that anything went wrong ā the only evidence is the operation quietly not doing what it should have.)
7 A recursive function crashes with RecursionError. Walk me through your diagnosis.
The base case either doesn't exist, or exists but can be stepped over rather than landed on exactly. I'd check the base-case condition against every value the recursive parameter could actually take ā an equality check like n != 0 is a common trap, since a value that skips past 0 (e.g. counting down from a negative start) never satisfies it. The fix is usually switching to an inequality that can't be skipped, like n <= 0, or validating the input before recursion begins.
Suggesting sys.setrecursionlimit() as "the fix" ā that just delays the same crash, it doesn't address a genuinely broken or unreachable base case.
"When, if ever, is raising the recursion limit actually the right call?" (Only when the recursion is genuinely correct and bounded, but legitimately deep ā e.g., a known, finite, deep tree structure ā never as a workaround for a broken base case.)
8 Where should you validate a value that might be zero before it's used as a denominator ā right before the division, or earlier?
As close to the division as the function boundary allows, ideally right inside the function that performs the division, since that function is the one that actually knows zero is unsafe there ā relying on every caller to remember to check first is fragile and easy to forget once. The check should also decide what "zero reviews" or "zero total" actually means for the caller (a real 0, a None, a "not enough data" message), not just avoid the crash.
Red flags"Wrap it in try/except ZeroDivisionError" as the only answer ā that avoids the crash but doesn't decide what a meaningful zero-case result actually is.
Follow-up"Is 0 reviews a bug, or a legitimate state?" (Legitimate ā a brand-new product with no reviews is normal, so the function needs to handle it as expected input, not as an error case.)
9 What's the difference between FileNotFoundError and PermissionError, and why does conflating them matter?
FileNotFoundError means the path doesn't exist; PermissionError means the path exists but the OS denies the process access to it. They call for genuinely different responses: a missing file is often fine to treat as "nothing here yet," while a permission error usually means the deployment or environment itself is misconfigured and should fail loudly with an actionable message. Code that only catches FileNotFoundError will let a real PermissionError propagate as an unhandled crash in exactly the environment (a locked-down production server) where it's most likely to happen.
Red flagsTreating "file-related exception" as one bucket and reaching for a single broad except OSError: without distinguishing what each specific case should actually do.
Follow-up"What's a real production scenario where this distinction matters?" (A deploy script that fails on a locked-down directory it doesn't have read access to ā treating that identically to "first run, no file yet" hides a genuine infrastructure misconfiguration.)
10 An API call succeeds (200 OK... or does it?) but json.loads() on the response body raises JSONDecodeError. What do you check first?
Whether the code checked the response status code before assuming the body was JSON at all. A very common real-world cause is that the request didn't actually succeed ā a login redirect, a rate-limit response, or a "503 Service Unavailable" page, all of which return HTML or plain text, not JSON ā and the calling code skipped that check and went straight to json.loads(). I'd check status_code (or equivalent) first, and wrap the parse itself in its own try/except so a genuinely malformed response produces a clear, specific error instead of a raw parser traceback.
Red flagsAssuming "the API sent bad JSON" as the only possible cause, without considering that it may not have sent JSON at all.
Follow-up"Where's the right layer to handle this ā inside the function that calls json.loads(), or the caller of that function?" (Inside the function making the request, right after getting the response ā that's the only place that actually knows whether the response looks like an error page before parsing is even attempted.)
11 A function is fast in testing but slows down dramatically as the real dataset grows. What's your first hypothesis?
An accidental O(n²) (or worse) algorithm hiding inside what looks like straightforward code ā most commonly a membership check (in) against a list inside a loop, or a nested loop scanning one collection once per item of another. Both look completely reasonable at small scale, since the difference between O(n) and O(n²) is invisible on a 10-item test list and severe on a 100,000-item production dataset. I'd look specifically for any in check against a list, or any loop nested inside another loop over a different collection.
Reaching for a vague "add caching" or "use numpy" answer without first identifying the actual algorithmic shape of the slowdown.
Follow-up"How would you confirm that hypothesis before changing any code?" (Time it at a few different input sizes and see whether runtime grows linearly or quadratically with size ā that distinguishes a real algorithmic issue from a constant-overhead one.)
12 Why is list.insert(0, x) in a loop a performance problem, and what's the fix?
Inserting at index 0 has to shift every existing element over by one to make room, which is O(n) per call. Doing that n times to build an n-item list makes the whole operation O(n²). The fix is to append to the end instead (O(1) amortized) and reverse the whole list once at the end if order matters ā one O(n) pass total instead of n separate O(n) shifts.
Red flagsNot recognizing that this is the exact same underlying problem as a quadratic membership check ā repeated O(n) work inside a loop that runs n times.
Follow-up"Is list.append() always O(1)?" (Amortized O(1) ā occasionally Python has to resize the underlying array, which is O(n) for that one call, but averaged over many appends the cost per append is O(1).)
13 When is caching a function's result actually safe, and when does it introduce a bug?
Caching is safe exactly when the function is "pure" with respect to its cache key ā the same input reliably produces the same output every time, with no dependency on anything that changes between calls (time, external state, randomness). A tax rate for a fixed region during one checkout is safe to cache; a live stock price or a random value is not ā caching either of those would silently return stale or wrong data instead of just being slow.
Red flagsTreating caching as a universal "add it and things get faster" trick without checking whether the cached function's output can legitimately change between calls.
Follow-up"How would you cache a function whose result SHOULD occasionally change (e.g. refreshed every hour)?" (Cache with an expiration ā store a timestamp alongside the cached value and recompute once it's older than some threshold, rather than caching forever.)
14 Two lists of records need to be joined by ID. Walk me through the slow way and the fast way.
The slow way: for each record in list A, loop through the entirety of list B looking for a matching ID ā O(n·m) total. The fast way: build a dict mapping ID to record for list B once, up front (O(m)), then look up each record in list A against that dict in O(1) ā O(n+m) total. The dict-building step is the whole trick: it trades a one-time O(m) cost for turning every subsequent lookup from O(m) into O(1).
Red flagsSuggesting sorting both lists and doing a merge-join as the only alternative ā that works but is more complex than necessary when a dict solves it directly, especially before joins on more than one field are involved.
Follow-up"What if list B has duplicate IDs?" (A dict keyed by ID can only hold one record per ID, so the last one written wins ā if duplicates need to be preserved, use a dict of lists instead: dict[id].append(record).)
15 Is re.compile() always worth doing over calling re.search() directly? Why or why not?
Nearly always worth doing as a habit, though the actual speedup is often modest rather than dramatic, since CPython internally caches a small number of recently-used uncompiled patterns already. It's clearly worth it when the same pattern is used repeatedly (a loop, a function called many times) and the pattern itself is complex. For a truly one-off match against a simple pattern, the difference is negligible either way ā but there's essentially no downside to compiling once, so it's a safe default.
Red flagsClaiming re.compile() always produces a dramatic speedup ā overselling a real but modest optimization undermines credibility on the bigger, genuinely dramatic fixes in this same category.
Follow-up"Where would you put the compile() call if the pattern is used inside a function called many times?" (Outside the function, at module level or passed in, so it's compiled exactly once regardless of how many times the function itself is called.)
16 Someone writes sorted(scores)[-1] to get the highest score. What would you say in code review?
sorted() is O(n log n) ā it fully orders the entire list even though only the single largest value is actually needed. max() gets the same answer in a single O(n) pass without sorting anything. I'd suggest max() (or min() for the smallest) whenever only one extreme value is needed, and reserve sorted() for when the full order actually matters downstream.
Red flagsNot recognizing sorted()[-1] and max() as behaviorally identical (same result) but algorithmically different (different Big-O) ā this is exactly the kind of code that "works" and passes review on correctness alone.
Follow-up"What if they needed the top 3 values, not just the top 1?" (heapq.nlargest(3, scores) gets the top k in better than O(n log n) for k much smaller than n ā worth knowing exists, though sorted()[-3:] is a reasonable, simpler answer too for a small, fixed k.)
17 A while loop checks i < len(items) on every iteration. Is that a real performance problem?
A real but small one ā len() on a list is already O(1), so this isn't a Big-O issue like the others in this category. It's about the repeated overhead of a function call happening on every single iteration, which adds up across millions of iterations even though each call is individually cheap. Hoisting len(items) into a variable before the loop removes that repeated overhead. In practice, using a plain for item in items: loop sidesteps the whole question, since it never needs an explicit index or length check at all.
Red flagsClaiming this is an O(n) vs O(n^2) issue ā it isn't; conflating "real, measurable overhead" with "algorithmic complexity problem" shows a gap in understanding Big-O.
Follow-up"When would you actually need a while loop with a manual index instead of a for loop?" (When the index needs to jump around non-sequentially, or change by more than 1 per iteration ā a plain for loop can't do either of those.)
18 A function re-opens and re-reads the same file once per search term. What's the fix, and why does it matter?
Read the file into memory exactly once, then run every search against that in-memory string. Disk I/O is slow relative to in-memory work, and the file's contents don't change between searches in this scenario, so there's no reason to pay that I/O cost more than once. This matters more, not less, at scale ā the same bug against a real production log file (megabytes, not a small test file) or over a network filesystem would be dramatically worse than a local test run suggests.
Red flagsNot distinguishing this from an in-memory algorithmic issue ā the bottleneck here is I/O, not computation, so the fix is about minimizing disk access, not about a smarter algorithm.
Follow-up"What if the file is too large to fit comfortably in memory?" (Then reading it all upfront isn't viable either ā that's a genuinely different problem, needing a streaming/single-pass approach that processes the file once while computing all needed results together, rather than one read per file.)
19 Why can a generator expression be faster than a list comprehension, not just more memory-efficient?
A list comprehension computes and stores every value immediately, before anything downstream even runs. A generator expression computes values lazily, one at a time, only as they're requested. If the code consuming the values might stop early (a for loop with a return/break once some condition is met), the generator version never computes the values that were never needed ā while the list comprehension already did that work regardless, up front. So it's not just about peak memory (Chapter 25) ā it's a real speed difference whenever early exit is possible.
Red flagsTreating "generators are memory-efficient" and "generators can be faster" as the same fact ā they're related but distinct, and this question is specifically testing the speed angle.
Follow-up"If the loop always processes every single value with no early exit, is the generator still faster?" (Not meaningfully ā if nothing exits early, both versions end up computing every value; the generator's advantage specifically comes from skipped work on early exit, not from generators being inherently faster to compute each value.)
20 Is if key in some_dict.keys() wrong, or just suboptimal?
Not wrong ā it produces the correct result. It's suboptimal: key in some_dict already checks the dict's keys by default and is O(1) average case, so appending .keys() adds an unnecessary view-object layer for zero benefit. It's a small, free fix (delete four characters), and a good habit to build since it signals a slightly clearer understanding of how dict membership actually works.
Red flagsClaiming .keys() changes the Big-O complexity ā it doesn't; both are O(1) average case, this is purely about removing unnecessary indirection, not fixing an algorithmic problem.
Follow-up"Is there ever a real reason to write .keys() explicitly?" (Yes ā when you need the keys view itself for something else, like set operations (dict.keys() & other_set) or iterating just the keys explicitly for readability; for a plain membership check, it's unnecessary.)
21 A service's memory grows steadily over days of uptime and never comes back down. Where do you start looking?
I'd look for something that's reachable and keeps growing: an unbounded module-level cache, a global "recent items" list with no size cap, a closure capturing a list it never trims, or a class attribute accidentally shared and appended to by every instance. Python's garbage collector reclaims anything genuinely unreachable, so a leak here almost always means "still reachable, longer than intended" rather than a language-level failure. I'd start with anything holding a dict or list at module or class scope that's mutated on every request.
Red flagsTreating this as a mysterious, unfixable "Python leaks memory" problem ā Python's memory model makes this a solvable, mechanical search for a reachable reference, not a black box.
Follow-up"What's the fastest way to confirm your hypothesis before changing code?" (A tool like tracemalloc, or simply watching a specific collection's len() over time in a long-running process ā measurement, not just code reading, is how memory leaks get diagnosed.)
22 What's the difference between Python's reference counting and its cyclic garbage collector, and why do both exist?
Reference counting frees an object the instant its reference count hits zero ā fast, deterministic, and how most objects are actually cleaned up. It can't handle a reference cycle, though ā two objects that reference each other never reach a count of zero on their own, even when nothing outside the cycle refers to either one. The separate cyclic garbage collector runs periodically specifically to detect and break cycles like that, since reference counting alone would leak them forever.
Red flagsClaiming Python "doesn't really garbage collect" or conflating the two mechanisms as if they're the same thing ā they solve different problems and understanding why both exist is the actual point of the question.
Follow-up"How would you break a parent/child reference cycle without waiting for the cyclic collector?" (Store the back-reference, e.g. child-to-parent, as a weakref.ref instead of a normal reference, so reference counting alone can free the parent.)
23 An object that should be garbage-collected the moment it's no longer used stays alive instead. What's a common, easy-to-miss cause?
Subscribing a bound method to an event bus or callback registry ā that hands the registry a reference to the method, which keeps the whole instance (self) alive too, since a bound method holds a reference to the object it belongs to. The caller can drop every other reference to the object, but as long as the registry's subscriber list still references the callback, the object can't be collected. The same shape shows up with a plain dict registry holding strong references to values it was only ever meant to look up, not own.
Red flagsOnly considering "did I forget to set a variable to None" ā that's rarely the real cause; the actual culprit is almost always a reference held by something else the code doesn't obviously think of as "holding onto" the object.
Follow-up"What's the fix that doesn't require every caller to remember to clean up after itself?" (Have the registry hold weak references ā weakref.WeakValueDictionary for a dict, or weakref-based subscriptions for a callback list ā so entries disappear automatically once nothing else references them.)
24 A class defines history = [] at the class level instead of inside __init__. What actually goes wrong?
There's exactly one list object, created once when the class body runs, and every instance's self.history resolves to that same shared object unless an instance explicitly overrides it. Two supposedly independent instances end up appending to the exact same list ā this is the class-level cousin of the mutable default argument trap, and just as easy to miss because the code reads as obviously per-instance.
Red flagsNot immediately connecting this to the mutable default argument bug ā recognizing the shared pattern (a mutable object created once, at definition time, silently shared across every subsequent use) is the actual skill being tested.
Follow-up"What's the fix?" (Create the list inside __init__ as self.history = [], so it's created fresh, once per instance, instead of once per class.)
25 Eight threads increment a shared counter, and the final total is consistently lower than expected. What's happening?
counter += 1 isn't one atomic step ā it's read the current value, add 1, write the result back, three separate steps. If two threads both read the same value before either writes its update back, one thread's increment is silently lost. Python's GIL prevents two threads from executing bytecode at the exact same instant, but it does not make a multi-step operation like this atomic ā a thread can still be switched out in the middle of it, which is exactly where the race lives.
Red flagsClaiming "the GIL means Python is thread-safe by default" ā that's a common and dangerous misconception; the GIL prevents simultaneous bytecode execution, not interleaving between the steps of a multi-step operation.
Follow-up"What's the fix, and why does it work?" (Wrap the read-modify-write in a threading.Lock, so only one thread can execute that whole sequence at a time ā turning three separate steps back into one effectively atomic one.)
26 Two threads occasionally deadlock while transferring funds between two accounts in opposite directions. What's the classic cause, and the classic fix?
One function acquires lock_a then lock_b; the other acquires lock_b then lock_a ā the opposite order. If both threads grab their first lock at roughly the same time, each ends up waiting forever for the lock the other is holding, and neither can proceed or release anything. The fix is establishing one global lock-acquisition ordering that every code path follows ā e.g. always lock the lower-ID account first ā which makes this exact deadlock shape structurally impossible, not just less likely.
Red flagsSuggesting "just add a timeout and retry" as the actual fix rather than a stopgap ā that can reduce the symptom's visibility without removing the structural cause, and can still fail under sustained contention.
Follow-up"Is this deadlock random?" (No ā it's fully deterministic given the exact interleaving of thread execution; it *feels* random because that interleaving depends on timing that varies from run to run, but the underlying cause is a fixed, structural lock-ordering conflict.)
27 Someone splits a pure-computation task across two threads expecting a 2x speedup on a multi-core machine, and gets no speedup at all. Why?
CPython's GIL allows only one thread to execute Python bytecode at a time, regardless of how many CPU cores are available. Threading genuinely helps when threads spend most of their time waiting ā for a network response, for disk I/O ā because the GIL is released during that wait. A tight, CPU-bound pure-Python loop never waits for anything, so the GIL keeps the threads running one at a time, same as sequential execution, plus a bit of thread-switching overhead.
Red flagsSuggesting "just add more threads" as the fix ā that makes a CPU-bound problem no better, sometimes measurably worse from added overhead.
Follow-up"What's the right tool instead?" (multiprocessing ā separate processes each get their own interpreter and their own GIL, so they can genuinely run in parallel across cores; threading stays the right tool for I/O-bound work specifically.)
28 A function starts several background threads and immediately checks a shared results list ā and finds it empty, even though the work clearly did finish moments later. What's missing?
thread.start() is non-blocking ā it schedules the thread and returns immediately, without waiting for it to finish. If the function never calls t.join() on the threads it started, it returns before any of them have necessarily completed, so anything they were supposed to produce isn't there yet. join() blocks until that specific thread has actually finished, which is the whole point of calling it before reading results those threads were responsible for producing.
Red flagsAssuming a short sleep() after starting threads is an acceptable substitute for join() ā it happens to work by luck on some timings and is not a reliable fix.
Follow-up"What does join() actually block on?" (The specific thread object it's called on finishing its target function entirely ā not on any other thread, and not on the process as a whole.)
29 A producer/consumer setup using queue.Queue processes everything correctly, and then the whole program hangs forever. What's the likely bug?
q.get() blocks by default when the queue is empty, waiting for the next item. If the producer stops after putting its items with no mechanism telling the consumer "that was the last one," the consumer's loop is left waiting on an item that will never come. The fix is having the producer put a sentinel value (like None) once it's done, with the consumer breaking its loop when it sees that sentinel ā or coordinating shutdown through a separate signal, like a threading.Event, alongside q.join()/task_done().
Red flagsNot recognizing that the processing itself succeeded ā the bug is purely that the consumer thread never learns to stop, which is a different failure mode than "the work was done wrong."
Follow-up"Would daemon threads fix this?" (Only in the narrow sense that the *process* could still exit even with a hung consumer thread ā the underlying design flaw (no shutdown signal) is unchanged, and any code waiting on that consumer's results would still hang.)
30 A pool of worker threads pops tasks off a shared list, each explicitly checking if not shared_list before popping ā and it still occasionally crashes with IndexError: pop from empty list. Why doesn't the check prevent that?
The check and the pop are two separate steps, and nothing stops another thread from running its own pop in between them ā thread A can see a non-empty list, get interrupted, and by the time it actually calls .pop(), thread B has already emptied it. The check was true when made, but false by the time it's acted on. This is the general "check-then-act" race condition, the same underlying shape as a lock-ordering deadlock or an unprotected counter increment: multiple steps that need to be atomic, but aren't.
Red flagsAssuming that "we checked first" is inherently safe ā a check is only meaningful if nothing else can invalidate it before the corresponding action runs.
Follow-up"What are two different valid fixes here?" (Wrap the check-and-pop in the same lock so it's atomic, or just attempt the pop and catch IndexError as "someone else got there first" rather than treating it as fatal.)
31 Why does an exception raised inside a concurrent.futures.ThreadPoolExecutor worker sometimes seem to just vanish?
A Future captures an exception raised inside its worker function rather than letting it propagate immediately ā it's stored on the Future, waiting to be re-raised the moment someone calls .result() on it. If nothing ever calls .result() on a given future, that captured exception is simply never looked at again, and the program continues as if every task succeeded.
Red flagsAssuming "submitting to a pool" is enough on its own to surface errors ā submission only schedules the work; observing the outcome (success or exception) requires actually reading the Future.
Follow-up"What's the safest pattern for handling a batch of futures?" (Call .result() on every future the pool produced ā often via concurrent.futures.as_completed() ā so every exception a worker raised gets re-raised somewhere it can actually be seen.)
32 A function makes a copy of a dict with .copy(), changes a plain string field on the copy, and the original is unaffected. But changing a list field on the copy also changes the original. Why the inconsistency?
.copy() is a shallow copy ā it creates a new dict, but every value inside it is the exact same object as in the original, not a new copy of that value. Reassigning a key on the copy (copy["status"] = "shipped") only affects the copy, since that changes which object the key points to. But mutating a shared nested object in place (copy["items"].append(...)) changes the one list both dicts are still pointing at ā nothing about a shallow copy makes nested mutable values independent.
Red flagsDescribing this as "some fields are copied and some aren't" ā that's not accurate; every top-level key is copied, the distinction is reassignment vs. in-place mutation of a shared nested object.
Follow-up"What's the fix when a copy genuinely needs to be fully independent?" (copy.deepcopy(), which recursively copies every mutable value nested inside, not just the top-level container.)
33 Why shouldn't you compare two floats that came from arithmetic using ==?
Most decimal fractions, including something as simple as 0.1, can't be represented exactly in binary floating point ā the same way 1/3 can't be written exactly in decimal. Every arithmetic operation accumulates a tiny rounding error, and after enough additions the result can be off from the "obviously correct" value by a sliver too small to see when printed, but large enough that == reports False. The fix is math.isclose() for a tolerance-based comparison, or decimal.Decimal instead of float entirely when exact decimal representation genuinely matters, like money.
Red flagsCalling this "a bug in Python" rather than a fundamental property of binary floating-point representation shared by essentially every programming language.
Follow-up"When is Decimal clearly the better choice over float, from the start?" (Money and any other domain where exact decimal values and exact decimal arithmetic actually matter ā not just "close enough," but precisely correct to the cent.)
34 A paginated API's "page 1" is silently missing the first several records, with no error anywhere. What's the likely bug?
An off-by-one error from mixing a 1-based page number with 0-based slicing math ā computing start = page_number * page_size treats page 1 as if it were already page 0, landing on where the second page actually starts. The fix is converting the 1-based page number to a 0-based offset explicitly before slicing: start = (page_number - 1) * page_size. A quick test asserting "page 1 includes the very first record" would catch this immediately.
Red flagsAssuming this would show up as a crash ā it doesn't; every individual page request "succeeds" and returns valid-looking data, which is exactly why boundary bugs like this are so easy to ship unnoticed.
Follow-up"Why is this category of bug more dangerous than a KeyError?" (No exception ever fires ā the program runs, returns something plausible-looking, and the damage is silently wrong data rather than a visible crash someone would investigate.)
35 Code that works on every developer's machine crashes at startup on a freshly deployed server with a KeyError on an environment variable name. What's going on?
This is the same KeyError pattern as a missing dict key, except the missing key lives in os.environ. A developer's shell profile or a local .env file quietly exports variables like an API key every time a terminal opens ā a freshly provisioned server has no such setup unless someone explicitly configured that variable in the deployment platform. The fix is validating every required environment variable at startup, before the service accepts any traffic, and failing with a clear message naming exactly which variable is missing ā turning a runtime crash deep in request-handling code into an immediate, unambiguous deployment failure.
Red flagsTreating this as purely a deployment/ops problem with no code-level fix ā validating config at startup is an application-code responsibility, not something that can only be fixed by "configuring things correctly" externally.
Follow-up"Why is failing loudly at startup better than the KeyError happening later, mid-request?" (It fails before any traffic is served, with a message naming exactly what's missing ā instead of an obscure crash on whichever request happens to be the first to touch that code path.)
36 A username that comfortably fits under a database column's stated character limit still fails to insert as "too long." What's the likely mismatch?
len() on a Python string counts characters, but many database column limits are actually enforced in bytes. Once text is encoded to UTF-8, characters outside the basic ASCII range take up 2, 3, or 4 bytes each ā so a 10-character string can easily be 12+ bytes, silently exceeding a byte-based limit that character-based truncation or validation never accounted for. The fix is knowing which unit a given limit is actually measured in, and truncating (carefully, without splitting a multi-byte character) against the encoded byte length when the limit is byte-based.
Red flagsAssuming len(text) always tells you how much storage a string will consume ā that's only true for pure-ASCII text under UTF-8; it stops being true the moment accented characters, emoji, or non-Latin scripts are involved.
Follow-up"Where else does this character-vs-byte confusion show up in this chapter?" (Reading a file with the wrong encoding assumption, or comparing two visually identical strings that are actually different Unicode code point sequences ā both are the same underlying category: assuming a string's on-the-wire representation matches its in-memory character count.)
37 An endpoint listing "books with their authors" is fast in testing and slows down sharply in production, roughly proportional to the number of books. What's the likely cause, and the fix?
The N+1 query pattern: one query fetches all the books, then a separate query fetches each book's author, one at a time, inside a loop ā for 150 books, that's 151 total round-trips to the database. This is the exact same nested-loop shape as an in-memory O(n²) bug, just expressed as network round-trips instead of list scans, which makes it much more expensive per unit since each one is a real network call, not an in-memory operation. The fix is a JOIN that fetches books and their authors together in one query ā databases are specifically built to do that combination efficiently in a single round-trip.
Red flagsReaching straight for "add caching" without first recognizing the actual query-count problem ā caching can mask this for a while, but the underlying per-request query count is still wrong.
Follow-up"Why is this worse than an equivalent-shaped in-memory O(n²) bug?" (Every one of the n extra operations is a full network round-trip to the database, not a cheap in-memory scan ā the constant factor per extra operation is dramatically higher.)
38 A payment retry mechanism, meant to make the system more reliable, ends up charging a customer twice. What's the underlying mistake?
Retrying is only safe when the operation is idempotent ā doing it twice has the same effect as doing it once. A payment charge is not naturally idempotent: if the server-side charge succeeded but the response was lost on the way back (a timeout, a dropped connection), the client has no way to know that, and blindly retrying the same request charges the customer a second time for what it believes is still a single failed attempt. The fix is attaching a unique idempotency key to the request, generated once per logical operation and reused on every retry, so the server can recognize "I've already processed this exact request" and return the original result instead of charging again.
Red flagsSuggesting "just don't retry payment operations" as the fix ā that trades a double-charge risk for a worse reliability problem; the actual fix is making the retry safe, not avoiding retries altogether.
Follow-up"What's a real-world example of an API that supports this pattern natively?" (Stripe's idempotency keys ā a client-generated key attached to a charge request that Stripe uses to deduplicate retried requests server-side.)
Rapid-Fire Review
Quick recall check — fill in each blank and hit Check.