Code Review and Working with Existing Codebases Questions
Reviewing others' code and navigating unfamiliar systems: giving and receiving actionable review feedback, spotting correctness and design issues, and reading and understanding large or legacy codebases before changing them. Covers collaborative coding norms, incremental change in shared repositories, and verifying changes against existing behavior. The team-facing side of day-to-day engineering.
You are reviewing a data migration that renames a heavily used column and requires backfilling millions of rows. Design a rollback-safe migration strategy that can be reviewed and approved. Cover schema changes, dual-write/read strategies, backfills, verification, monitoring, and how code review should verify each migration step.
Sample Answer
Direct answer
A rollback-safe rename plus backfill never touches the old column or existing readers directly. It adds the new column alongside the old one, writes to both while backfilling the new one in batches, verifies the backfilled data matches, only then switches reads over behind a flag, and keeps the old column around for a retention window so any step can be reversed just by flipping the flag back, not by undoing a destructive change.
Structured elaboration
Each phase below names what code review should specifically confirm before approving it, as a "Review check," plus what to monitor once it ships.
1. Schema change. Add the new column as nullable, with no constraints yet:
ALTER TABLE events ADD COLUMN new_name text NULL;
Review check: confirm this specific statement is additive only and backward-compatible, meaning every existing reader and writer keeps working unmodified the moment this ships, with zero application changes required yet.
2. Dual-write. Deploy an application change, behind a feature flag, that writes both the old and new column on every write to a row. Review check: is the write to both columns transactional or otherwise guaranteed consistent (not "write old, then separately and non-atomically write new"), and is the flag off by default so this ships dormant before anything depends on it?
3. Backfill. A batched, idempotent job fills in the new column for existing rows, only where it's still NULL, ordered by primary key, with a checkpoint so it can resume after an interruption instead of restarting from row one:
UPDATE events
SET new_name = old_name
WHERE id BETWEEN :batch_start AND :batch_end
AND new_name IS NULL;
Review check: is progress persisted somewhere durable (not just in the running process's memory), and does re-running an already-completed batch do nothing (true idempotence), not create incorrect data? Monitoring: track batches completed, rows backfilled, replication lag, and write error rate on the table for the duration of the backfill, and pause automatically if replication lag crosses an agreed threshold.
4. Verification. Before trusting the backfill, sample a random set of rows and confirm new_name matches what old_name implies for each. Review check: is the sample size and comparison method actually specified in the PR, not just asserted as "we verified it"?
5. Read cutover. Only after verification passes, flip the flag so reads prefer the new column, falling back to the old one if the new one is somehow still empty for a given row. Review check: is the fallback logic actually tested, not just written? Monitoring: application error rate and query latency on this table specifically, right after the flag flips, since a regression here is the trigger for the rollback shown in the diagram below.
6. Cleanup. Once reads have run on the new column successfully for a defined retention window, make it NOT NULL, add any index it needs, and only then drop the old column, in a separate, later PR. Review check: is dropping the old column genuinely a separate step from everything above, so it can never accidentally ship bundled with a change that hasn't been verified yet?
flowchart LR
A[Step 1: add new_name column, nullable] --> B[Step 2: dual write old_name plus new_name]
B --> C[Step 3: backfill new_name in batches where NULL]
C --> D{Verification: sampled row values match}
D -- mismatch found --> C
D -- fully verified --> E[Step 4: flip reads to new_name behind a flag]
E --> F{Error rate normal after cutover}
F -- regression --> G[Rollback: flip flag back to old_name, dual write stays intact]
F -- healthy --> H[Step 5: make new_name NOT NULL, add index concurrently]
H --> I[Step 6: drop old_name after a retention window]
Worked example
Renaming user_email to primary_email on a table with 40 million rows, backfilled in batches of 5,000 rows: that's 40,000,000 / 5,000 = 8,000 batches total. With a short pause between batches to keep replication lag bounded, the job runs as a background process over however long it takes to work through all 8,000 batches, checkpointing its position after each one so a restart resumes from the last completed batch instead of row one. Verification samples 10,000 random rows after the backfill reports complete and confirms primary_email equals user_email for every one of them before the flag is ever flipped to prefer reads from the new column.
Trade-offs and pitfalls
Every step here is reversible specifically because the old column and old read path stay intact until the very last, separate cleanup step, which is exactly what makes this slower and more code than a single rename statement; that trade is worth it for a heavily-used column and wrong for a rarely-touched internal table, where a single migration with a maintenance window might be simpler and perfectly safe. The most dangerous version of this pattern to review is one that quietly combines two of these steps, most often shipping the read cutover and the old-column drop in the same change, which collapses the rollback safety the whole design exists to provide.
Technical coding: Given the following Python function used in a deployment script, write pytest unit tests that cover normal behavior and edge cases. Mock external API calls.
import requests
def get_latest_image(repo):
r = requests.get(f'https://registry.example/api/{repo}/latest')
r.raise_for_status()
return r.json()['tag']
Provide at least three tests and explain why you chose them.
Sample Answer
Direct answer
I'd write at least four tests, covering the success path, an HTTP error response, a malformed JSON body missing the expected key, and a network-level failure like a timeout, all with requests.get mocked so no test makes a real network call. Each test targets a distinct way this function can fail in production, not just variations on the happy path.
Structured elaboration
Approach. Mock requests.get so the function's own logic, not the network, is what's under test. For each test, build a fake response object with just enough behavior to drive the code path being tested (raise_for_status either does nothing or raises, json() returns a controlled payload), then assert on get_latest_image's return value or on the exception it raises.
Why these specific tests.
- Success proves the normal path works and the correct value is extracted from a realistic JSON payload.
- HTTP error (a 4xx or 5xx status) proves the function surfaces the failure via
raise_for_status()rather than silently returning something wrong. - Missing key in the response body proves that if the API's response shape doesn't match what the code expects, the caller gets a clear exception rather than a confusing downstream error somewhere else.
- Network-level failure (a timeout, a connection error) proves the function doesn't swallow or mask an infrastructure problem, which matters specifically because this function is used in a deployment script where a caller needs to know the difference between "the deploy image genuinely doesn't exist" and "we couldn't reach the registry at all."
Worked example
# deploy_utils.py
import requests
def get_latest_image(repo):
r = requests.get(f'https://registry.example/api/{repo}/latest')
r.raise_for_status()
return r.json()['tag']
# test_deploy_utils.py
from unittest.mock import Mock, patch
import pytest
import requests
from deploy_utils import get_latest_image
def make_response(json_data=None, raise_error=None):
resp = Mock()
resp.raise_for_status = Mock(side_effect=raise_error) if raise_error else Mock()
resp.json = Mock(return_value=json_data or {})
return resp
def test_get_latest_image_returns_tag_on_success():
resp = make_response(json_data={'tag': 'v1.2.3'})
with patch('deploy_utils.requests.get', return_value=resp) as mock_get:
result = get_latest_image('myapp')
assert result == 'v1.2.3'
mock_get.assert_called_once_with('https://registry.example/api/myapp/latest')
def test_get_latest_image_raises_on_http_error():
resp = make_response(raise_error=requests.exceptions.HTTPError('404 Client Error'))
with patch('deploy_utils.requests.get', return_value=resp):
with pytest.raises(requests.exceptions.HTTPError):
get_latest_image('missing-repo')
def test_get_latest_image_raises_keyerror_on_malformed_body():
resp = make_response(json_data={'digest': 'sha256:abc'})
with patch('deploy_utils.requests.get', return_value=resp):
with pytest.raises(KeyError):
get_latest_image('myapp')
def test_get_latest_image_propagates_network_timeout():
with patch('deploy_utils.requests.get', side_effect=requests.exceptions.Timeout):
with pytest.raises(requests.exceptions.Timeout):
get_latest_image('myapp')
Actually run with pytest, output:
test_deploy_utils.py::test_get_latest_image_returns_tag_on_success PASSED
test_deploy_utils.py::test_get_latest_image_raises_on_http_error PASSED
test_deploy_utils.py::test_get_latest_image_raises_keyerror_on_malformed_body PASSED
test_deploy_utils.py::test_get_latest_image_propagates_network_timeout PASSED
4 passed
Complexity
This is straightforward, constant-time mocked I/O per test, no algorithmic complexity to speak of; the interesting design decision is which failure modes are worth a dedicated test, not runtime cost.
Edge cases
- A 500 server error takes the exact same code path as a 404, since both raise via
raise_for_status(); one test covering "any HTTP error" is representative, a second status-specific test adds little. - A response that's valid JSON but not a dict at all (a bare list, for example) would raise
TypeErrorrather thanKeyErrorwhen['tag']is applied; worth a fifth test if this API's contract is genuinely uncertain. - Real production code often uses a
requests.Sessionwith a configured retry adapter rather than a barerequests.get; mocking at therequests.getlevel, as done here, doesn't exercise that retry behavior at all, which would need a different test approach.
Trade-offs and pitfalls
Mocking at the requests.get level is fast and has zero network flakiness, but it also means these tests can't catch a real integration problem, like the registry's actual response shape changing; a smaller number of separate integration tests against a real or realistic staging registry are worth having alongside these, not instead of them. A common pitfall is mocking so aggressively that the test asserts almost nothing about get_latest_image's own logic, for example forgetting to assert on the exact URL called, which would let a bug in the f-string (a wrong path, a typo) slip through unnoticed.
Explain the primary goals of a code review in a software team. List at least three concrete categories reviewers typically evaluate (for example correctness, tests, readability) and give a one-sentence example of what a reviewer might look for in each category when reviewing a pull request.
Sample Answer
Direct answer
Code review exists to catch problems before they reach production and to spread knowledge across the team. In practice, a reviewer evaluates a pull request (PR, a proposed code change) against a handful of concrete categories rather than judging "is this good code" in the abstract.
Structured elaboration
At least four concrete categories, each with an example of what a reviewer looks for:
- Correctness: does the change do what it claims, including realistic edge cases? Example: does a date-parsing function handle a leap year or an empty string, not just the happy-path date.
- Tests: is the new or changed behavior actually verified? Example: does the PR add a test that would fail if the retry logic were removed, rather than a test that merely calls the function without checking its result.
- Readability and maintainability: can a teammate understand this in six months without asking the author? Example: is a variable named
daysSinceSignupinstead ofd, so the next reader isn't tracing it back through the function. - Design and scope: does the change fit the existing architecture without unnecessary coupling? Example: does a new class reach directly into another module's internals instead of going through its public interface.
Beyond the per-PR checklist, review also serves the team as a whole: it spreads context across more than one person (so no single engineer is a single point of failure for understanding a piece of code), and it builds a shared, consistent bar for what "done" looks like.
Worked example
A PR adds a coupon-discount calculation to a checkout flow. Correctness: does it handle a coupon that expired mid-request, or a discount that would make the total negative? Tests: is there a test asserting the discounted total for a specific input, not just that the function runs? Readability: is the function named applyCoupon rather than calc2, with the discount type spelled out instead of a bare integer code? Design: does the discount logic live in the pricing module rather than being pasted directly into the checkout controller, so it can be reused at the cart-preview step too?
Trade-offs and pitfalls
Reviewing for everything at once with no priority causes review fatigue and slows everyone down. The common failure mode is spending review time on style and readability nits while missing a correctness or security issue underneath. A good reviewer explicitly triages: correctness and anything security-adjacent first, then tests, then design and readability.
You find this Python function in a PR: def append_to_list(item, lst=[]): lst.append(item); return lst. As a reviewer, explain the bug, why it occurs, how you would phrase the review comment, propose a corrected implementation, and write one unit test that would have caught the bug.
Sample Answer
Direct answer
This is Python's classic mutable-default-argument bug. def append_to_list(item, lst=[]): looks like a fresh empty list is created every call, but Python evaluates a default argument's value exactly once, when the def statement itself runs, not on every call. Since [] is mutable, every caller who doesn't pass their own lst shares that same one list object across every call to the function, for the lifetime of the program. The fix: default to None, an immutable sentinel, and create a new list inside the function body when the caller didn't provide one.
Structured elaboration
Approach. Python binds a function's default argument values once, at definition time, to the function object itself, not per call. For an immutable default like 0 or None this is invisible, since you can't mutate an int or None in place, so nobody notices the "only once" behavior. For a mutable default like [], {}, or a custom mutable object, it means every call that relies on the default is silently operating on the same shared object, so state written by one caller leaks into every subsequent caller.
Review comment. "Bug: lst=[] is a mutable default argument. Python evaluates it once, at function-definition time, so every call that doesn't pass its own lst shares and mutates the same list, and state leaks between unrelated calls. Please default to None and create a new list inside the function body, and add a regression test asserting two calls with the default argument don't share state."
Worked example
The buggy behavior, demonstrated by actually calling the function twice with no lst argument:
def append_to_list_buggy(item, lst=[]):
lst.append(item)
return lst
print(append_to_list_buggy(1))
print(append_to_list_buggy(2))
Output:
[1]
[1, 2]
The second call's result contains 1 from the first call, that's the state leak the review comment flags: the caller of append_to_list_buggy(2) almost certainly expected [2], not [1, 2].
The corrected implementation and a unit test that would have caught the bug:
def append_to_list(item, lst=None):
if lst is None:
lst = []
lst.append(item)
return lst
def test_append_to_list_does_not_share_state():
a = append_to_list(1)
b = append_to_list(2)
assert a == [1]
assert b == [2]
test_append_to_list_does_not_share_state()
print("test_append_to_list_does_not_share_state: PASS")
Output:
test_append_to_list_does_not_share_state: PASS
Complexity
Appending one item is O(1) amortized (meaning an occasional slower operation averages out across many calls) time and O(1) additional space per call, aside from the list's own growth. The fix doesn't change that complexity, it changes which list object gets mutated: a fresh one per call instead of one shared object.
Edge cases
- A caller who explicitly passes their own list should still get in-place appending onto that list, that behavior is preserved by both versions.
- A caller who passes something that isn't a list (a tuple,
Noneexplicitly) needs a decision: raise a clear error, or duck-type accept anything with an.appendmethod, either is defensible, but it should be intentional and documented, not accidental. - The bug bites hardest in a loop calling the SAME function repeatedly with no
lstargument across many call sites, since the shared list keeps growing without bound, which starts as a correctness bug and becomes a memory-safety concern too.
Trade-offs and pitfalls
The same pattern applies to any mutable default, a dict, a set, or a custom mutable object, not just a list, so a reviewer who's learned to spot this once should generalize the check rather than pattern-matching on lst=[] specifically. A linter (Python's Pylint rule W0102, or Ruff's rule B006) can catch this entire class of bug automatically; it's worth suggesting the team turn that check on in continuous integration (CI) so it doesn't depend on a human catching it in review every time, though that's a process improvement to raise as a follow-up, not a reason to skip flagging this instance now.
Design a set of static analysis rules to detect common concurrency bugs in a Java codebase. Provide at least four rules, explain the detection heuristic and likely false positives for each, and suggest mitigations.
Sample Answer
Direct answer
Design this as four independent, mechanical checks over the code's abstract syntax tree (AST, a tree representation of parsed source code a tool can walk programmatically), each targeting one well-known Java concurrency bug pattern, rather than trying to prove general thread-safety, which isn't something a static tool can fully decide. The four rules: an unsynchronized mutable field shared across threads, double-checked locking without volatile, a non-thread-safe collection shared across threads without synchronization, and a silently swallowed InterruptedException. Each rule trades some false positives for being cheap and mechanical to run in continuous integration (CI).
Structured elaboration
Rule 1: unsynchronized mutable shared field. Heuristic: find non-final, non-volatile fields that are written in one method and read in another that can run on a different thread (a public method, a Runnable/Callable implementation, a listener callback). Flag if no synchronization (a synchronized block or an explicit Lock) guards the reads and writes, and the field carries no documented @GuardedBy annotation (a marker showing which lock protects that field, so a reader does not have to guess). False positives: a field that's set once during safe, single-threaded initialization before being published, or one only ever touched under an external framework lock the tool can't see. Mitigation: mark the field final or volatile, encapsulate access behind a synchronized method or lock, or use an Atomic* type from java.util.concurrent.atomic.
Rule 2: double-checked locking without volatile. Heuristic: detect the lazy-initialization idiom, a null check, a synchronized block, then a second null check, on a field that isn't declared volatile. False positives: rare cases where construction is genuinely safe to publish without one, but this is easy to get wrong, so the rule should default to flagging it. Mitigation: declare the field volatile, or switch to the initialization-on-demand holder idiom, or use java.util.concurrent.atomic.AtomicReference.
Rule 3: non-thread-safe collection shared across threads. Heuristic: find a java.util.ArrayList, HashMap, or similar mutable, non-thread-safe collection whose mutating methods (add, put, remove) are called from more than one method reachable by different threads, without synchronization. False positives: a collection that's locally scoped, guarded by a higher-level lock elsewhere, or effectively immutable after construction. Mitigation: replace with ConcurrentHashMap, CopyOnWriteArrayList, Collections.synchronizedList(...), or make the collection immutable after building it.
Rule 4: swallowed InterruptedException. Heuristic: a catch block for InterruptedException that's empty, only logs, or rethrows as an unrelated exception, without restoring the thread's interrupt status via Thread.currentThread().interrupt(). False positives: test code, or a framework-specific handler that deliberately converts the exception into a controlled shutdown. Mitigation: restore the interrupt status if not rethrowing the original exception, and exit any loop promptly rather than continuing to run after an interrupt was requested.
Worked example
Rule 2 applied end to end, since it's the most concrete of the four:
// Flagged: double-checked locking without volatile
private Connection instance;
public Connection get() {
if (instance == null) {
synchronized (this) {
if (instance == null) {
instance = new Connection();
}
}
}
return instance;
}
// Fixed: mark the field volatile so a write becomes visible to other
// threads before the reference is published
private volatile Connection instance;
Why this matters: without volatile, another thread can, under the Java memory model (the rules that define when one thread's writes become visible to another thread), observe a non-null reference to instance before the constructor's writes to that object are actually visible to it, a partially-constructed object leaking out. This is a real, documented hazard in the Java memory model, not a hypothetical one, and it's exactly the kind of bug that can pass every functional test and still fail intermittently in production under load.
Trade-offs and pitfalls
These rules are local and syntactic, so none of them can reason across method or class boundaries, a lock acquired somewhere else in the call chain won't be seen, which means real false negatives on anything indirect are expected, this is a floor, not a guarantee. Tune the false-positive rate by supporting a documented @GuardedBy annotation or a suppression comment that requires a stated justification, so the rule stays actionable instead of getting bulk-suppressed the first time it's noisy. Prioritize findings by realistic blast radius (how much damage this specific bug could do if it shipped, not just whether it technically exists), a shared field in a class used by every incoming request is worse than the same pattern in a rarely-instantiated helper, rather than treating every hit as equally urgent. Before building all four from scratch, check what an existing, actively maintained tool already covers: SpotBugs, the maintained successor to the now-unmaintained FindBugs, and Google's Error Prone both catch some of these patterns out of the box.
Unlock Full Question Bank
Get access to all Code Review and Working with Existing Codebases interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.