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 open a PR that contains 25 files with mixed issues: a bug in a provisioning script, a security misconfiguration in Terraform, and many minor style issues. As the reviewer, explain how you would triage and classify comments into 'must-fix before merge', 'should-fix before merge', and 'optional', and give two example comments for each category with justification.
Sample Answer
Direct answer
On a 25-file pull request (PR, a proposed code change submitted for review), I triage by actual risk and blast radius, not by diff size: the provisioning-script bug and the Terraform security misconfiguration are must-fix because they change behavior or expose risk, most naming or structure issues are should-fix depending on whether they'll cost real time later, and pure style preferences that a linter could enforce are optional or shouldn't be a manual comment at all.
Structured elaboration
How I classify
- Must-fix before merge: anything factually wrong, or that causes an outage or security exposure, or violates a hard team rule. If I can point to a concrete failure scenario, it's must-fix.
- Should-fix before merge: real quality issues that won't break anything today but will cost real time later (unclear naming, missing error handling on a path likely to be hit, no test for new logic). Negotiable in a specific stated case, but the default is fix it.
- Optional: preference, style, or a nice-to-have that doesn't change correctness or meaningfully affect future maintainability. If a linter or formatter could enforce it, it shouldn't be a manual comment at all.
Two example comments per category
Must-fix
- "The provisioning script writes the instance ID to a temp file before checking whether the previous run's file still exists, so a retried run silently appends stale data instead of failing loudly. This will misconfigure real instances on retry." Justification: a concrete correctness bug with an observable, harmful production effect.
- "This Terraform resource sets the security group's inbound rule to allow all internet addresses on port 22 (SSH, the protocol used for remote server access). This needs to be scoped to the internal network's address range before merge." Justification: an active security exposure, not a style question; shipping it creates real risk the moment it's applied.
Should-fix
- "This function handles three unrelated things: validation, provisioning, and notification. Pulling the notification piece out would make this testable in isolation and easier for the next person to change on its own." Justification: doesn't break anything today, but the coupling will slow down every future change to this function.
- "There's no test covering the retry path this PR adds. Given the must-fix bug above lived exactly in that retry path, a test here would have caught it." Justification: directly tied to the risk just found, not a generic "add more tests" comment.
Optional
- "nit: could use an f-string here instead of string concatenation, purely a style preference, not blocking." Justification: no functional or long-term readability cost either way, and explicitly labeled non-blocking so the author knows they can skip it.
- "nit: consider renaming the loop variable for clarity, but it's also readable as-is from context." Justification: minor and defensible either way, flagged as optional rather than demanded.
Worked example
Given all three issue types in the same PR, I'd leave the two must-fix comments first, clearly marked (a "BLOCKING:" prefix, or the review tool's "request changes" status), and ask for a re-review specifically on those two before anything else. The should-fix comments go in the same review round but don't need a second look; I'd trust the author to either fix them or explicitly push back with a reason. The optional style comments get grouped at the bottom, or left as a single batch of nits, so they don't compete visually with the two things that actually block merge, and I say explicitly that the PR is approvable once the two blocking items are addressed, regardless of whether the nits are touched.
Trade-offs and pitfalls
- Leaving 15 style nits with the same visual weight as the security misconfiguration buries the one comment that actually matters; always lead with, and visually separate, the must-fix items
- Treating "should-fix" as a synonym for "must-fix" just because you feel strongly about it erodes the whole point of the tiering; if it isn't tied to a concrete failure or real future cost, it isn't must-fix
- Style-only nits that a formatter or linter could catch shouldn't be manual review comments at all, that's a signal to add the check to continuous integration (CI, the automated build/test pipeline) instead of repeating the same comment on every PR
Leadership: You're in a large engineering org where reviewers are overloaded and PR latency is high. Propose a scalable manual-review strategy combining automation, triage, reviewer assignment rules, and code ownership. Explain how to maintain quality while reducing time-to-merge and preventing reviewer burnout.
Sample Answer
Direct answer
At org scale, "review faster" doesn't work, the fix is redesigning how review load is distributed: automate everything mechanical before a human ever opens a diff, route each pull request (PR, a proposed code change submitted for review) to the right owner instead of a free-for-all queue, triage by risk so low-risk changes take a lightweight path, and make reviewer load a metric leadership actually watches, the same way they'd watch on-call load.
Structured elaboration
Automation removes load before a human sees the diff
- Continuous integration (CI, the automated build/test pipeline) blocks on lint, type checks, unit tests, and coverage delta, so reviewers never comment on things a machine already caught
- A bot flags PR size and touched-file risk (for example, "this modifies auth middleware") so a reviewer knows what they're walking into before opening it
Triage by risk
- Classify changes into tiers: low-risk (docs, config, isolated feature-flagged code) gets a single reviewer or even auto-merge after CI passes; medium risk gets normal review; high-risk (shared libraries, security, data migrations, billing) gets a mandatory named owner plus a second reviewer
- This concentrates scarce senior reviewer attention on what actually needs it instead of spreading it thin and evenly
Reviewer assignment and code ownership
- CODEOWNERS-style routing (a config file mapping directories to the team or person who owns that code) auto-assigns based on what the PR actually touches, instead of a random queue
- Load-balance assignment within an ownership group (round robin or least-loaded) instead of everyone requesting the one person known to be thorough
- Rotate a weekly "on-call reviewer" role per team so load doesn't permanently concentrate on the same two or three people
Preventing burnout while cutting time-to-merge
- Cap how many PRs a single reviewer is expected to have open at once, visible on a shared dashboard
- Protect a daily review block instead of letting review compete with deep work as constant interrupts
- Track reviewer load as a first-class metric leadership actually looks at, not an afterthought
Worked example
An org of 300 engineers has PR latency (open to merge) at a median (the middle value, half of PRs merge faster and half slower) of 3 days, driven by 15% of reviewers absorbing 60% of review volume, the people everyone requests because they're known to be thorough. The plan: introduce CODEOWNERS-based auto-assignment for the 20 highest-traffic directories, add a bot that classifies PRs into risk tiers from touched paths and diff size, and set a rule that low-risk PRs need one reviewer with a 4-business-hour service-level agreement (SLA, an explicit response-time target) while high-risk PRs need a named owner with a 1-business-day SLA. Leadership adds a dashboard showing open-review-count per person, and anyone over a threshold (say, 8 open reviews) gets rebalanced by their lead. After a quarter, median latency for low-risk PRs drops sharply because they no longer queue behind high-risk items, and concentration on the top reviewers eases because ownership-based routing spreads assignments across each team instead of funneling everything to a few known-good individuals.
Trade-offs and pitfalls
- Automated risk-tiering can misjudge risk (a one-line change to a rate limit is "small" but dangerous), keep a human override on the classification
- CODEOWNERS routing can create silos where only the "owner" ever reviews a path, losing the cross-pollination review normally provides; rotate ownership periodically
- Cutting time-to-merge by lowering the bar (fewer required reviewers everywhere) trades quality for speed; the real lever is distributing existing rigor better, not removing it
- A reviewer-load dashboard used punitively instead of for rebalancing damages trust fast; be explicit it's a load-balancing signal, not a performance metric
You are reviewing a short Bash script authored by an operations engineer. Identify bugs, anti-patterns, portability and safety concerns, and propose fixes. The script:
#!/bin/bash
DIR=$1
if [ ! -d $DIR ]; then
mkdir $DIR
fi
for file in $(ls $DIR); do
sudo echo 'Processing' $file
rm -rf $DIR/$file
done
What would you comment on in the PR, and how would you rewrite or patch this script to be safer and idempotent?
Sample Answer
Direct answer
The two most serious problems are unquoted variables, which break on filenames containing spaces, and using ls in a for loop, which word-splits its output the same way. On top of that, sudo echo doesn't do what it looks like it does, and the script has no error handling and isn't safely idempotent (running it twice wouldn't produce the same safe result as running it once). I'd rewrite it to quote everything, use find instead of ls for the loop, and add explicit error handling.
Structured elaboration
- Word-splitting from unquoted variables.
$DIRand$fileare used unquoted throughout. The shell splits an unquoted variable's value on whitespace before using it, so a filename likemy file.txtbecomes two separate words,myandfile.txt, wherever it's used unquoted. lsin aforloop.for file in $(ls $DIR)runsls, then word-splits its output the same way as above, and additionally can misbehave on filenames containing newlines or glob characters. Iterating a directory's contents should usefind(or a glob directly), neverls's text output.sudo echodoes nothing useful.sudoelevates the single command that follows it, hereecho, not any of the commands after it in the loop. Therm -rftwo lines later still runs as the invoking user, with no elevated permissions at all, so this line is misleading: it looks like it's setting up privileged execution and it isn't.- No error handling. There's no
set -e(exit on any command failing) and no check thatmkdiror the loop itself succeeded, so a failure partway through is silent. - Destructive with no safety.
rm -rf $DIR/$fileruns unconditionally, with no dry-run option and no check that$DIRis actually the directory intended, which is dangerous if$DIRis ever accidentally empty or wrong.
Worked example
The original script's word-splitting bug, demonstrated on a real directory containing three files, one of which has a space in its name (report.txt, my file.txt, data.csv):
#!/bin/bash
DIR=$1
if [ ! -d $DIR ]; then
mkdir $DIR
fi
for file in $(ls $DIR); do
echo 'Processing' $file
done
Run as ./orig.sh testdir, output:
Processing data.csv
Processing my
Processing file.txt
Processing report.txt
my file.txt was silently split into two separate "files," my and file.txt, neither of which actually exists on disk; the original script's rm -rf $DIR/$file line would then try to remove two nonexistent paths instead of the one real file, silently failing to do what it was clearly meant to do.
The rewritten, safe version:
#!/usr/bin/env bash
set -euo pipefail
DIR="${1:-}"
if [[ -z "$DIR" ]]; then
echo "Usage: $0 <directory>" >&2
exit 2
fi
mkdir -p -- "$DIR"
while IFS= read -r -d '' file; do
echo "Processing: $file"
rm -rf -- "$file"
done < <(find "$DIR" -mindepth 1 -maxdepth 1 -type f -print0)
find ... -print0 prints each filename terminated by a NUL byte (\0) instead of a newline, since NUL is the one character that can never appear in a filename. read -r -d '' then reads up to that NUL byte instead of splitting on whitespace or newlines, so a name containing spaces, tabs, or even a literal newline comes through as one intact string. IFS= clears the input field separator for the read, which stops it from trimming leading or trailing whitespace off each name. Together the three pieces replace ls's whitespace/newline-based splitting with a delimiter no filename can ever contain.
Run on the same directory, output:
Processing: testdir/my file.txt
Processing: testdir/data.csv
Processing: testdir/report.txt
Every filename, including the one with a space, is now handled as a single, correct unit. Running the script a second time on the now-empty directory produces no output and exits 0, since mkdir -p is idempotent and there are no more files to process.
Complexity
This is O(n) in the number of directory entries, one find traversal plus one removal per entry; there's no algorithmic complexity concern here, the risk was entirely in correctness and safety, not performance.
Edge cases
- An empty directory:
find -mindepth 1returns nothing, the loop body never runs, no error. Both the buggy and fixed versions handle this the same, trivially. - A subdirectory inside
$DIR: the fixed version above adds-type fspecifically so it only processes files, not subdirectories, because the original script's intent (process and remove files) was ambiguous about whether subdirectories should also be recursively wiped; that's worth confirming with the script's author rather than guessing. $DIRpointing somewhere unintended (an empty variable, a typo): the fixed version exits early with a usage message if the argument is missing, rather than silently operating on the wrong path or failing confusingly deep inside the loop.
Trade-offs and pitfalls
set -euo pipefail is safer by default but has a real gotcha: a command that's expected to sometimes return nonzero (a grep that finds no match, for example) will abort the whole script unless it's explicitly handled, which surprises people the first time they hit it. Given this script's line calls rm -rf in a loop, I'd also want a --dry-run flag added before trusting it against anything that matters, printing what would be removed without removing it, since a subtle bug in a real deletion script is far more costly than the same bug in a read-only one.
You find a change in a PR that appears to add API keys and database passwords as plain text constants in a repository. As the reviewer, what steps do you take immediately and what long-term code-review policies and automated checks would you recommend to prevent credentials from being committed? Include remediation for secrets already committed to history.
Sample Answer
Direct answer
My immediate steps are to block the merge, notify whoever owns those credentials so they can be rotated right away, and treat every exposed key or password as compromised regardless of whether the PR has merged yet. Long term, I'd push for two things together: automated secret scanning that blocks a push before it ever lands, and a real secrets-manager so hardcoding a credential as a source constant stops being something a developer would even reach for.
Structured elaboration
Immediate steps.
- Block the PR with a clear comment: which lines, why they can't merge as-is.
- Notify the owner of each credential (the team responsible for that database, that API) so rotation starts immediately, in parallel with fixing the code, not after.
- Treat the credentials as compromised the moment they were pushed, even to a non-default branch, since they were already visible in the hosting platform's systems and any CI run's logs.
Remediation if already committed to shared history. Rotate every exposed credential first; that's the step that actually stops them being usable. Separately, decide whether history needs rewriting: if the branch is shared or already merged, a tool like git filter-repo can remove the secret from history, but that requires a force-push and everyone with a clone re-syncing, which is real coordination overhead, not a quick fix.
Long-term prevention policy.
- Automated secret scanning wired into CI on every PR, and ideally as a server-side push-protection check that rejects the push outright before the secret ever lands in the repository, which is strictly better than catching it in review after the fact.
- A pre-commit hook (the
pre-commitframework, running something likedetect-secretsorgitleaks) catches most cases even before a push happens. - A managed secrets store (a cloud provider's secrets manager, or a tool like Vault) so credentials are injected at runtime rather than living in source at all; combined with short-lived, role-based credentials instead of long-lived static keys where the platform supports it.
- A written policy in the contribution guidelines stating plainly that credentials never go in source, plus periodic scans of existing history to catch anything that predates the automated checks.
Worked example
A reviewer notices DB_PASSWORD = "hunter2" hardcoded in settings.py, already merged two releases ago. Immediate step: rotate the database password right away, since it's been live and exposed in history for two full release cycles, not just caught in an open PR. Then: add settings.py's pattern to the secret-scanner's ruleset so this specific style of hardcoded constant is caught automatically going forward, replace it with a read from the team's secrets manager, and separately schedule the history rewrite (or accept the rotated-but-not-rewritten trade-off, documented as a deliberate decision) since this secret already reached the default branch and every existing clone.
Trade-offs and pitfalls
Push-protection style scanning that blocks a push outright is the strongest prevention, but it will occasionally false-positive on something that looks like a secret and isn't, which needs a fast override path or it trains developers to route around the check entirely. Migrating fully to a secrets manager and short-lived credentials is a real engineering investment, not a one-line config change, so a reasonable interim step is "no new hardcoded secrets, enforced by CI" while the migration for already-existing ones happens on its own timeline. The most common pitfall in the immediate response is fixing the code (removing the line from the diff) while forgetting that the review only ever showed you the PR, not everywhere else that credential might already be exposed.
Advanced technical domain: A long-running monitoring agent has a memory leak in production. As a reviewer of the agent's codebase, describe the steps you would take to identify leaking code during review: which profilers and CI checks to add, which code patterns to look for (circular refs, global caches, goroutine leaks), and what automated tests or metrics would catch regressions early.
Sample Answer
Direct answer
I would not try to find a production memory leak purely by reading code. I'd combine dynamic evidence, actually profiling the running agent under load, with a targeted code-review checklist for the patterns most likely to cause a slow, steady leak, and then lock in whatever I find with a CI check so the same class of bug can't silently come back.
Structured elaboration
Profilers and dynamic evidence. Before trusting any code-review guess, I'd reproduce the leak under a controlled, repeatable workload and watch memory over time: resident set size (RSS, the actual physical memory the process holds) climbing steadily and never coming back down after garbage collection runs is the signature of a real leak, as opposed to a memory spike that a full garbage collection cycle reclaims. For a compiled agent, a built-in heap profiler (Go's pprof, for example) can take a heap snapshot before and after a workload and show exactly which allocations are still retained; for an interpreted agent, an allocation tracer (Python's tracemalloc, for example) does the equivalent by snapshotting live allocations and diffing two points in time.
Code patterns to look for. The question names circular references specifically, and it's worth being precise about when that's actually the cause: in a language with a tracing garbage collector (which reclaims anything unreachable from a root, cycles included), a circular reference on its own is usually NOT what leaks memory, since the collector can free a cycle nobody outside it points to. What actually leaks in that kind of runtime is something still reachable that shouldn't be:
- Unbounded global caches or maps: a cache or dictionary that only ever grows, with no eviction policy or size cap, is one of the most common leak sources in a long-running service, since every entry is reachable from a live root for the life of the process.
- Leaked lightweight concurrent tasks (goroutines, in Go, or the equivalent worker/coroutine in another runtime): a task that's spawned per request or per event but never exits, most often because it's blocked forever waiting on a channel or queue that nothing will ever write to, keeps itself and everything it captured in its closure alive indefinitely. Every hung task is a small, permanent leak.
- Forgotten deregistration: an event listener, callback, or subscription that's added but never removed when the thing that registered it goes away, so a long-lived object (say, a connection pool) keeps growing a list of listeners that should have been cleaned up.
- Circular references DO matter directly in a reference-counted runtime (no tracing collector, or one that only handles simple cases), where two objects each holding a strong reference to the other can prevent the count from ever reaching zero; if the agent embeds any component like that, it's worth checking specifically.
CI checks and metrics that catch regressions early.
- A memory-regression test: run the agent against a fixed, deterministic synthetic workload (a set number of requests or events, not "for N minutes," so the result is reproducible), take a heap snapshot before and after, and fail the build if retained memory grows past a set threshold.
- A task-leak assertion: after the synthetic workload finishes and drains, assert that the number of live background tasks (goroutines, threads, whatever the runtime calls them) has returned to its known baseline count, not just "isn't growing forever."
- Production metrics and alerting: track RSS trend, heap object count, and live background-task count over time, and alert on sustained upward trend rather than a single spike, since a spike that recovers after garbage collection is expected behavior, not a leak.
Worked example
A concrete pattern this would catch: the monitoring agent spawns one background task per incoming metric batch to forward it to an upstream collector over HTTP, and that HTTP call has no timeout or deadline. If the upstream collector stops responding, every task blocked on that call never returns, and each one keeps its metric-batch buffer alive in its closure. Under normal conditions this is invisible, since tasks come and go quickly; the moment the upstream collector gets slow or unresponsive, the agent starts accumulating one leaked task (and its buffer) per batch, forever, which shows up as a slow, steady RSS climb that never plateaus.
The review-time catch: does every code path that spawns a background task per request or event pass it a context or deadline, so a hung downstream call can't block that task forever? The CI catch: a synthetic test that sends, say, 500 metric batches to a fake upstream collector that never responds, then asserts the live background-task count returns to its pre-test baseline (not zero, since some fixed background workers are expected) once the test workload finishes, rather than staying elevated by roughly 500.
Trade-offs and pitfalls
Continuous production profiling has real overhead, so it's usually run on-demand or sampled, not left on all the time. A CI memory-regression gate with an absolute byte threshold is prone to flaking across different CI runner hardware; a relative threshold (percent growth over baseline, measured on the same run) is more stable. The most common wrong turn is fixing the symptom instead of the cause: bounding a growing cache with a size limit stops the crash but, if entries are evicted on a schedule that doesn't match how they're actually used, can just delay the same leak rather than fix it, so the review should ask why the cache grows unbounded in the first place, not just cap it and move on.
Unlock Full Question Bank
Get access to all 31 Code Review and Working with Existing Codebases interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.