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
Technical debugging: review the following Python snippet intended to concurrently fetch metadata for hosts. Identify race conditions and concurrency issues, and propose a corrected, thread-safe implementation with reasoning.
import threading
hosts = ['a','b','c']
results = []
def fetch(h):
data = get_metadata(h)
results.append((h, data))
threads = []
for h in hosts:
t = threading.Thread(target=fetch, args=(h,))
threads.append(t)
t.start()
for t in threads:
t.join()
print(results)
Assume get_metadata may raise exceptions and is non-blocking I/O bound.
Sample Answer
Direct answer
The real problem isn't a low-level data race on results.append (a single list append happens to be safe from internal corruption in CPython for this simple case). The real problem is that this code has no way to catch a per-host exception: if get_metadata raises inside fetch, that entire thread dies silently, its host's result never makes it into results, and neither the join() calls nor the final print reveal that anything went wrong. Replace hand-rolled threading.Thread objects with a ThreadPoolExecutor and Future-based error handling, and key the results by host in a dictionary, which is what actually makes this both thread-safe and debuggable.
Structured elaboration
Approach. A race condition is an outcome that depends on unpredictable timing between threads. Here, the more serious issue is a swallowed exception, not data corruption: none of the threads' exceptions are caught anywhere, so a single failing host silently vanishes from the output with no error and no trace. There's also no bound on concurrency, one raw thread is spawned per host with no limit, which doesn't scale if hosts ever has thousands of entries instead of three.
Key points. concurrent.futures.ThreadPoolExecutor manages a bounded pool of worker threads instead of spawning one thread per item. Each submitted call returns a Future, and calling .result() on it either returns the value or re-raises whatever exception the underlying function raised, which is exactly what makes per-host errors visible instead of silent. Writing results into a dict keyed by host, rather than appending tuples to a shared list, avoids any ambiguity about which result belongs to which host regardless of completion order.
Worked example
import concurrent.futures
def get_metadata(h):
if h == 'b':
raise ValueError(f"no metadata for host {h}")
return {"host": h, "region": "us-east-1"}
def fetch(h):
data = get_metadata(h)
return h, data
hosts = ['a', 'b', 'c']
results = {}
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as ex:
futures = {ex.submit(fetch, h): h for h in hosts}
for fut in concurrent.futures.as_completed(futures):
h = futures[fut]
try:
host, data = fut.result()
results[host] = data
except Exception as e:
results[h] = {"error": str(e)}
for h in sorted(results):
print(h, "->", results[h])
This uses a stub get_metadata that deliberately fails for host b, so the demo exercises both the success and failure paths. Output (printed in sorted host order, so it's stable across runs regardless of which thread finishes first):
a -> {'host': 'a', 'region': 'us-east-1'}
b -> {'error': 'no metadata for host b'}
c -> {'host': 'c', 'region': 'us-east-1'}
Host b's failure is now visible as {'error': 'no metadata for host b'} in the output, instead of silently disappearing the way it would in the original code.
Complexity
O(n) total work across n hosts, bounded to at most max_workers requests in flight at once, rather than n simultaneous raw threads for however large hosts happens to be.
Edge cases
An exception from get_metadata is now captured and reported per host instead of silently vanishing, as demonstrated above. An empty hosts list makes the loop do nothing and produces an empty result, with no error. A host that takes far longer than the others doesn't block collecting the ones that finish first, since results are consumed via as_completed in actual completion order, not submission order.
Trade-offs and pitfalls
ThreadPoolExecutor is the right tool for I/O-bound work waiting on network calls, which is what the question states get_metadata is. For CPU-bound work, Python's global interpreter lock means threads don't actually run Python bytecode in parallel, so a process pool, or a different approach entirely, would be needed instead. At genuinely large scale, many thousands of hosts, asyncio avoids the per-thread memory and context-switching overhead altogether; that's worth knowing as the next step up, not something every small fetcher like this one needs from day one.
Behavioral: Tell me about a time when you found a critical bug or security issue in infrastructure code during a code review. Use the STAR format: describe the Situation, the Task you had, the Actions you took as reviewer and with the team, and the Results (including any follow-up changes to process or automation).
Sample Answer
Direct answer
I'll walk through a real example from reviewing infrastructure-as-code: catching a security group change that would have opened a database to unrestricted inbound access, and how that turned into both an immediate fix and a lasting change to how the team reviews that class of change.
Structured elaboration
Situation. I was reviewing a routine-looking Terraform PR meant to let a new internal reporting service reach a database. Task. As the reviewer, my job was to catch anything that changed the actual security posture of that database, not just check that the Terraform plan applied cleanly. Action. I noticed the PR's security group rule used 0.0.0.0/0 for the inbound CIDR range (CIDR, Classless Inter-Domain Routing, is the notation for writing a whole block of IP addresses as one value; 0.0.0.0/0 specifically means "every possible IP address"), instead of the reporting service's specific subnet, almost certainly copy-pasted from an example rather than deliberately chosen. Result covers what happened next, both the immediate fix and the longer-term process change, below.
Worked example
I marked the PR as blocking with a specific comment explaining the exposure: this rule would allow any host on the internet to attempt a connection to the database's port, not just the internal reporting service the PR was supposedly scoping access to. I proposed the concrete fix, scoping the rule to the reporting service's actual subnet CIDR instead, and pushed a one-line diff to make it easy for the author to just take. Given the severity, I also flagged it in the team's on-call channel rather than waiting for an asynchronous PR reply, since an already-merged version of a similar mistake elsewhere in the account was worth checking for immediately, not after the PR conversation finished. The PR was updated and merged with the corrected, scoped rule within the hour. Separately, I proposed and helped add an automated policy check (using Open Policy Agent, a policy-as-code tool that can evaluate Terraform plans against written rules) to the CI pipeline that specifically rejects any security group rule opening a sensitive port to 0.0.0.0/0 without an explicit, reviewed exception, so this exact mistake can't reach production again without a deliberate override.
Trade-offs and pitfalls
The judgment call in a story like this is deciding how loudly to escalate: raising it in a live channel instead of just a PR comment was the right call given the actual exposure, but that same urgency would be the wrong tone for a much lower-severity finding, and using it there would just train the team to tune out urgent-sounding messages. A pitfall to watch for when telling this kind of story is stopping at "I found the bug and it got fixed," without the automation follow-up: the more convincing version of this story is one where the process change means the same category of mistake gets caught automatically next time, not just this one instance.
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.
Design a code-review checklist specifically for Terraform modules in a large, multi-team organization, covering everything from module interface design to security posture. Provide the checklist and explain why each item matters at organizational scale.
Sample Answer
Direct answer
A Terraform-module checklist at org scale has to cover four layers: the module's public interface (inputs and outputs), its internal implementation quality, its security posture, and its operational safety (versioning, blast radius). Each layer matters more, not less, as more teams consume the module, because a mistake in a shared module multiplies across every consumer's pull requests (PRs, proposed code changes submitted for review) instead of staying contained to one team.
Structured elaboration
| Checklist item | Why it matters at scale |
|---|---|
| Input variables have types, descriptions, and validation blocks | Undocumented or untyped inputs force every consuming team to read the module source just to call it correctly; validation blocks catch a bad value at plan time instead of a failed apply in someone else's environment |
| Outputs expose only what consumers need, named consistently | A module that leaks internal resource attributes as outputs creates an implicit contract that's expensive to change once dozens of consumers depend on it |
| No hardcoded account IDs, regions, or environment-specific values | A shared module with an environment baked in either breaks in every consumer's context or gets silently overridden inconsistently across teams |
| Pinned provider and module version constraints | A floating version constraint means every consuming team gets a different, unreviewed version at apply time, an interface change nobody actually agreed to |
No hardcoded secrets or credentials; sensitive outputs marked sensitive = true | A leaked secret in a module used by 20 services is a 20-service incident, not a 1-service incident |
| Clean on a security scanner (misconfiguration checks for open security groups, unencrypted storage, overly broad identity and access management (IAM) policies) | These are exactly the mistakes that are easy to miss in a manual review and expensive across every consumer once shipped |
| State isolation (keeping each team's Terraform state, the file that maps declared resources to the real infrastructure Terraform already created, separate so one team's apply can't affect another's) and blast-radius awareness (does this create resources that would force a destroy and recreate affecting other consumers) | In a multi-team org, a change here can silently ripple beyond the immediate PR's obvious blast radius |
| A documented usage example in the module's README | New teams adopting the module correctly the first time removes the biggest source of misuse-driven incidents in a large org |
| Backward-compatible change discipline (additive by default, a deprecation path for removed variables) | Once many teams consume a module, breaking its interface is effectively a breaking API change across the whole org, not a local refactor |
Worked example
A platform team reviews a change to a shared vpc Terraform module used by 30 downstream service repositories. The change adds a new enable_flow_logs variable defaulting to true, and removes an old legacy_subnet_cidr variable outright. Applying the checklist: the new variable has a type, a description, and a sensible default, so the interface item passes. But removing legacy_subnet_cidr outright fails the backward-compatibility item, since any of the 30 consumers still passing that variable would fail their next terraform plan with an "unsupported argument" error, all at once, with no warning. The reviewer requires the author to deprecate it first (keep the variable, mark it deprecated in the description, stop using it internally) rather than remove it in the same release, and to bump the module's major version so consumers opt in on their own schedule instead of being broken automatically on their next terraform init.
Trade-offs and pitfalls
- A checklist this thorough adds real review time to every module PR; scope its strictness to modules with many consumers, a single-team internal module doesn't need the same bar
- Security scanners produce false positives on legitimate exceptions, like an intentionally public storage bucket for static assets; the checklist needs an explicit, documented suppression mechanism, not a blanket bypass
- Over-indexing on interface stability can make a module slow to evolve; balance it with a clear deprecation and major-version-bump policy rather than freezing the interface forever
- Skipping the "why it matters at scale" framing turns this into generic Terraform best practices instead of an org-scale review lens; the whole point is that consumer count changes the cost of every mistake
Unlock Full Question Bank
Get access to all 32 Code Review and Working with Existing Codebases interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.