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.
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.
List five types of automated checks you would want running before a human ever looks at the code, and explain why each one earns its place in the pipeline. Which would you consider mandatory, and which optional?
Sample Answer
Direct answer
Before a human looks at the code, I want checks that are cheap, deterministic, and fast: build/compile, the existing test suite, correctness-oriented linting, formatting, and security or secret scanning. Build, tests, correctness linting, formatting, and security scanning are effectively mandatory since each is cheap and prevents real harm; a coverage-delta threshold is the one I'd keep optional or advisory.
Structured elaboration
| Check | Why it earns its place | Mandatory or optional |
|---|---|---|
| Build or compile | Nothing else is worth reviewing if the code doesn't build; catches syntax and type errors instantly | Mandatory |
| Existing test suite | Confirms the change didn't break behavior the team already relies on; a human can't hold hundreds of existing test cases in their head | Mandatory |
| Linting for correctness patterns (unused variable, unreachable code, obvious bug shapes) | Catches whole classes of bugs a quick human skim easily misses, for free, every time | Mandatory |
| Auto-formatting or a format check | Removes style disagreement entirely from human review, the single biggest source of low-value review comments | Mandatory |
| Security or secret scanning (hardcoded credentials, known-vulnerable dependency versions) | A missed hardcoded secret or vulnerable dependency is a real incident, and exactly the kind of thing that's easy to miss skimming a large diff | Mandatory |
| Coverage delta (does the pull request (PR, a proposed code change) add tests proportional to the code it adds) | Useful signal, but a blunt one; a PR can legitimately have low delta coverage, for example a config-only change | Optional / advisory |
Why this ordering matters
Machines are fast, consistent, and never get tired or skip a check under time pressure, exactly the trait humans lose in a rushed review. This reframes the human reviewer's job: not "did the tests pass," but "does this change make sense, is the design right, are there edge cases the tests don't cover."
Worked example
A PR adds a new /export endpoint. Continuous integration (CI, the automated build/test pipeline) runs: the build passes; the existing 340-test suite passes; linting flags an unused import, requiring a one-line manual fix; the secret scanner catches a hardcoded key accidentally left in a test fixture and blocks the merge until the author replaces it with an environment-variable reference; the coverage-delta check shows the new endpoint added 0 new tests against 45 new lines and posts an advisory warning, not a block, prompting the author to add a test before requesting review. Only after the build, existing tests, and the secret-scan block clear does the PR reach a human reviewer, who focuses entirely on whether the endpoint's authorization check is correct, something none of the automated checks could evaluate.
Trade-offs and pitfalls
- Too many mandatory gates slows every PR for marginal benefit; keep the mandatory set to checks that catch real, expensive-to-miss problems, not personal style preferences
- A coverage-delta threshold enforced as a hard block gets gamed with low-value tests written just to hit a number; keep it advisory and let a human interpret it
- Automated checks can produce false confidence, "CI is green" means the mechanical bar was cleared, not that the design is right
- Security or secret scanners produce false positives; if they cry wolf too often, engineers start ignoring or bypassing them
As part of a code review, you are asked to ensure that a change respects the team's API stability policy. Describe how you would verify backwards compatibility, what kind of tests you'd want in place, and how you'd document and communicate an intentional breaking change to downstream consumers.
Sample Answer
Direct answer
Treat this review as three linked jobs: prove the change doesn't break the existing contract, or clearly flag that it intentionally does; have tests that catch a break automatically rather than relying on a human noticing during review; and if it IS a breaking change, run an explicit communication and coordination process across every downstream team before it ships, not just a changelog entry after the fact.
Structured elaboration
Verify backward compatibility. Diff the public API (application programming interface) surface, endpoints, request and response schemas, public method signatures, against the previous version using an automated schema-diff tool. Check that the semantic-versioning bump (version numbers like 2.1.0, where the first number only increases for a breaking change) actually matches the impact: a removed field or endpoint is a major-version break, not a minor one. Manually scan for the classic breaking patterns an automated diff might present too dryly to flag on its own: a field that used to be optional becoming required, a removed enum value, or a changed error code that a consumer's error-handling logic depends on.
Tests to require. Unit and integration tests for the new behavior, plus consumer-driven contract tests: each known consumer publishes a "contract" describing what it expects from this API, and the provider's continuous integration (CI) pipeline runs every consumer's contract against the new code before merge, so a break shows up as a failing build instead of a production incident weeks later.
Documenting and communicating an intentional break. If a break is genuinely necessary, it needs a migration guide with concrete before-and-after request or response examples, a deprecation timeline (announce now, remove after an agreed grace period), and a version bump that signals the change to anyone watching semantic versioning.
The multi-team angle. This is the part that's easy to skip. Different downstream teams often run on different release cadences: one team deploys daily, while another ships a mobile client that goes through app-store review on a multi-week cycle. "We announced it in the changelog" is not the same as "every consumer had a realistic window to migrate before the old behavior disappeared." The reviewer's job includes checking that the deprecation window is long enough for the SLOWEST consumer's release cadence, not the average one, and that there's a direct, tracked notification, not just a changelog line, to every known downstream team: who owns each consumer, has that owner acknowledged the timeline, and is there a release-coordination step, such as a shared rollout calendar or a required sign-off from each consuming team, before the old behavior is actually removed.
Worked example
A concrete scenario: a payments API removes a deprecated legacy_currency_code field. Applying the process: an automated schema diff confirms the field is gone, which requires a major-version bump. Contract tests run for the three known consumers (a web checkout, a mobile app, and a partner integration), and the partner integration's contract still references the old field, so its test currently fails, that failure is the exact signal that should hold the release, not something to work around. A migration guide is written showing the old request shape next to the new one. The deprecation timeline is set to match the partner integration's slowest release cadence, which, per that team, needs six weeks of notice because their deploys go through a change-advisory process, not the web team's daily-deploy pace. Each of the three consuming teams gets a direct message naming the field, the deadline, and a link to the migration guide, and the field's actual removal is gated on each team explicitly acknowledging the change, not merely being notified of it.
Trade-offs and pitfalls
Coordinating across three teams' release cadences is slower than shipping the break and hoping consumers keep up, but the alternative, a downstream team's production system silently breaking because nobody saw a changelog entry, is far more expensive to unwind afterward. A common pitfall is confusing "we deprecated it" with "it's now safe to remove": the deprecation period only did its job if every consumer actually acted on it, which needs active follow-up, for example a dashboard tracking remaining callers of the old field, rather than passively waiting out the clock.
List five elements you always include in a pull request description to make reviews efficient for team members and new joiners. Explain why each element matters for maintainability, discovery, and onboarding.
Sample Answer
Direct answer
A good pull request (PR, a proposed code change submitted for review) description answers what changed, why, how it was tested, what the reviewer should focus on, and what's deliberately out of scope. Each element saves a reviewer from reconstructing context from the diff alone, and later saves an engineer doing archaeology on why the code looks the way it does.
Structured elaboration
Five elements and why each matters
- What changed (a one-to-two sentence summary): gives the reviewer a frame before reading the diff line by line; without it they infer intent from code, which is slower and more error-prone
- Why (the motivating problem, with a linked ticket or incident if there is one): this is the piece that survives long after the code changes again; an engineer later using
git blameor the commit log to understand "why is this here" finds the why in the description, not the diff - How it was tested: tells the reviewer what confidence already exists (unit tests added, manually verified in staging), so they know what's already covered versus what still needs scrutiny
- What to focus review on: the author usually knows which part of the diff is riskiest or most novel; naming it directs a time-constrained reviewer's attention where it matters most
- What's explicitly out of scope: prevents scope-creep comments ("why didn't you also fix X") and tells a future reader that a related-looking issue was a deliberate non-goal, not an oversight
Why this matters beyond the immediate review
- Maintainability: the description becomes permanent documentation attached to the commit history; months later it's often the only record of intent
- Discovery: someone tracing "why does this function do X" through the commit log finds the description as the answer, faster than re-deriving it from the diff
- Onboarding: a new engineer reading recent PR history to understand a codebase's evolution gets a narrated version of the system's history instead of bare diffs
Worked example
A PR titled "Fix race condition in session refresh" with the description "fixes bug, see diff" forces the reviewer to reverse-engineer what race condition, why this fix addresses it, and whether it was actually reproduced. Contrast: "What: adds a lock around session-token refresh. Why: intermittent authentication failures under concurrent requests, traced to two requests refreshing the same token at once and one overwriting the other's write. Tested: added a test that fires 50 concurrent refresh calls and asserts exactly one network call happens; manually reproduced the original bug on staging before the fix and confirmed it no longer reproduces after. Focus review on: the lock's scope, it needs to cover the full read-modify-write, not just the write. Out of scope: the underlying token storage isn't thread-safe either, that's a separate, larger fix tracked elsewhere." A reviewer can now scrutinize exactly the risky part (the lock's scope) instead of re-deriving the whole problem, and anyone reading this PR later understands both the bug and the deliberate boundary around the fix.
Trade-offs and pitfalls
- A template that's too long or bureaucratic gets filled in with boilerplate nobody reads; keep it to the elements that actually change reviewer behavior
- A "why" section that just restates the ticket title without the actual reasoning doesn't help; the value is in the reasoning, not a ticket number
- Descriptions get stale if the PR's scope changes mid-review and nobody updates them; treat the description as something to revisit before merge, not only before opening the PR
Your team wants to improve the code-review process to reduce blind approvals and improve quality without slowing delivery. Propose concrete process changes, tooling adjustments, and rollout/feedback mechanisms to increase review effectiveness and collaboration.
Sample Answer
Direct answer
To cut blind, rubber-stamp approvals without slowing delivery, I'd fix the conditions that cause rubber-stamping (diffs too large to actually read, unclear expectations, no accountability for what slips through) rather than just tell people to "review harder": smaller pull requests (PRs, proposed code changes submitted for review) nudged by automation, a short reviewer checklist embedded in the PR template, and a feedback loop that closes on real outcomes, piloted before it's rolled out broadly.
Structured elaboration
Diagnose first
Blind approvals usually trace to one of: PRs too large to actually read, unclear expectations about what "reviewed" means, the reviewer having no stake in what slips through, or review being enough of a bottleneck that people route around it.
Process changes
- Require a PR description template (what changed, why, how it was tested), a reviewer with no context defaults to skimming
- Require two reviewers only on genuinely high-risk paths (payments, auth, data migrations), not blanket everywhere, to avoid adding friction where it doesn't earn its cost
- A short reviewer checklist in the PR template (did you trace at least one changed code path, is there a test for the change) that must be acknowledged before approving, not a hard blocker but a nudge that makes rubber-stamping visible to the reviewer themselves
Tooling adjustments
- CI (continuous integration, the automated build/test pipeline) gates lint, type checks, and coverage delta so reviewers spend attention on logic and design, not mechanics
- A diff-size bot that flags, but doesn't block, PRs over a threshold and suggests a split
- Track a "zero-comment approval" rate as a smell to investigate, not to punish
Rollout and feedback mechanism
- Pilot on one team for 2-4 weeks before rolling out org-wide
- Collect qualitative feedback (does this feel like friction, does it feel useful) alongside the metrics
- Keep an escape hatch (an "emergency" label that skips the strict checklist for genuine hotfixes) so the process doesn't get quietly worked around
Worked example
A team pilots this on their payments-adjacent service. Before: 40% of PRs are approved within 10 minutes with zero comments, a rough proxy for rubber-stamping. They add the PR template, the checklist, and a required second reviewer scoped only to payments/ paths via CODEOWNERS (a config file that routes specific paths to required reviewers). After a three-week pilot, zero-comment approvals drop from 40% to 18%, median time-to-merge rises from 6 to 9 hours (a real but survivable cost), and in a retro the team reports catching two logic bugs that previously would have gone through. They keep the change, but scope the two-reviewer rule to only where CODEOWNERS actually flags it, since it was adding delay outside genuinely risky paths without a matching quality benefit.
Trade-offs and pitfalls
- Adding process without removing an existing friction source (large PRs) just slows everything down while blind approvals continue on the same underlying diffs
- A checklist that's too long becomes its own rubber-stamp, people tick boxes without doing the work; keep it to 3-5 items tied to real failure modes
- A blanket two-reviewer requirement is one of the fastest ways to slow delivery for marginal quality gain; scope it to genuinely risky code
- Watch for a "must comment" norm getting gamed with a low-value nit just to look engaged
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.