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.
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.
Medium: Create a short rubric (4–6 criteria) you would use to evaluate code clarity during code review that balances readability, performance, and maintainability. Explain how you weight conflicting criteria when they trade off.
Sample Answer
Direct answer
Score a change against five criteria, readability, correctness and safety, maintainability, performance, and testability, each on a simple 1-5 scale, then break ties with a stated priority order rather than a strict weighted sum: correctness always wins first, and performance only overrides readability when there's a real, demonstrated need, not a hypothetical one.
Structured elaboration
- Readability and intent (heaviest weight). Clear naming, small functions, a logical structure, and a short comment where intent genuinely isn't obvious from the code alone. This is what determines how expensive every future change to this code will be.
- Correctness and safety (high weight). Edge cases handled, input validated, errors handled rather than swallowed, and passing tests. This one is close to non-negotiable: a readable change that's wrong is still wrong.
- Maintainability (moderate weight). Duplication removed rather than copy-pasted, components decoupled, and a clear public interface. Ask whether this change makes the NEXT change to this area easier or harder.
- Performance (lighter weight, situational). Whether the algorithmic complexity is appropriate for the expected data size, not a micro-benchmarked improvement measured in isolated nanoseconds that nobody will ever notice in production.
- Testability (lighter weight). Is the new logic actually covered by a test, and is it structured so it CAN be tested without heavy, brittle mocking?
How to weight conflicts. When performance and readability conflict, default to readability unless there's real evidence of a need, a benchmark, a known hot path, or a user-visible complaint, since premature optimization that sacrifices clarity is a far more common mistake in review than an under-optimized path that turns out to matter. When maintainability and short-term velocity conflict, prefer maintainability, but if a shortcut is taken anyway, track it explicitly with a TODO and a ticket rather than letting it pass silently.
Worked example
A concrete PR (pull request): it extracts a repeated validation block into a shared helper function, but the helper is named generically (doCheck) and is called from three unrelated modules. Scoring it against the rubric: readability 3 out of 5 (works, but the name doesn't say what it actually validates); maintainability 4 out of 5 (removes real duplication across three modules, a genuine improvement); correctness 5 out of 5 (behavior-preserving, has passing tests); performance not really applicable here; testability 4 out of 5 (the helper is small and easy to unit test in isolation). The net call: the underlying design decision, extracting the duplication, is correct, so request one specific, scoped fix (rename the helper to describe what it actually checks) rather than asking for a broader rewrite.
Trade-offs and pitfalls
The biggest pitfall in using any numeric rubric is treating the total score as an objective verdict: two very different profiles, for example all 3s across the board versus one 5 and one 1, can add up to a similar total but represent very different actual risk, so the rubric is a structure for the conversation, not a replacement for reading the diff. A second pitfall is applying it identically regardless of context, a small internal tool and a payment-processing module should not weight correctness the same way in practice, even though the rubric's criteria stay the same.
You are reviewing a new REST endpoint PR. Describe a complete test strategy to validate behavior, including unit tests, integration tests, contract tests, load tests, and edge case tests. For each test type give a concrete example case that must be covered and what the reviewer should verify in the test code.
Sample Answer
Direct answer
Reviewing a new REST (Representational State Transfer, the common web API style) endpoint's test coverage means checking five distinct layers: unit tests for the endpoint's own logic in isolation, integration tests against real dependencies, contract tests that pin the API's shape for consumers, load tests for realistic traffic, and explicit edge-case tests. Each layer catches a different class of bug, and none of them substitutes for the others.
Structured elaboration
| Test type | Concrete example case | What the reviewer verifies |
|---|---|---|
| Unit tests | Given a valid request body, the handler returns the expected response shape and status code; given an invalid field, it returns a 400 with a specific error message | The test exercises the real logic, not just that a mock was called, and covers both the success path and at least one validation failure |
| Integration tests | Create a resource via the endpoint, then confirm it's actually persisted and retrievable via a separate read call | The test uses a real or realistic data layer, not mocks, so it would catch a broken query or a schema mismatch |
| Contract tests | A field a known consumer depends on, e.g. createdAt, must always be present and always an ISO 8601 timestamp string; the test fails if a future change removes or reshapes it | The contract covers every field an actual known consumer depends on, not just a generic happy-path shape check |
| Load tests | Simulate the expected peak requests-per-second and confirm the p95 latency, the 95th-percentile response time, meaning 95% of requests are at least this fast, stays under the team's target with near-zero error rate | The load profile reflects realistic expected traffic, and the test checks a latency or error threshold, not only that requests completed |
| Edge case tests | An empty request body, a request at the maximum allowed payload size, a duplicate submission with the same idempotency key (a client-generated ID sent with a request so retrying it doesn't create a duplicate), a request from an unauthenticated caller | Each case has an explicit assertion about expected behavior, a specific status code and body, not just "doesn't throw an unhandled exception" |
Worked example
A PR (pull request) adds POST /orders. Unit test: a valid order payload returns 201 with an order ID; a missing items field returns 400. Integration test: after the POST, a subsequent GET /orders/{id} returns the same order from the real test database. Contract test: the response always includes id, status, and createdAt in the shape the frontend's order-confirmation page depends on. Load test: simulate the expected peak checkout traffic and confirm p95 latency and error rate stay within the team's targets. Edge cases: an empty items array, a duplicate submission with the same idempotency key that should not create two orders, and a request with an expired auth token that should return 401, not 500.
Trade-offs and pitfalls
Not every endpoint needs all five layers at full weight, a low-traffic internal admin endpoint may not need load testing, and a purely internal endpoint with no external consumers may not need a formal contract test. Calibrate to the endpoint's actual risk and consumers rather than mechanically requiring every category on every PR. A common wrong turn is treating a high unit-test count as sufficient while skipping integration tests entirely; unit tests with everything mocked can pass while the real database query underneath is broken.
When reviewing code that touches user data storage and retrieval, what privacy and data-protection checks should you perform, and what would you want to see as concrete verification (not just an assurance) for each one?
Sample Answer
Direct answer
When a PR (pull request) touches how user data is stored or retrieved, review for four concrete things, what's collected, who can access it, how it's protected, and how it can be deleted, and insist on evidence for each one in the diff or PR description, since a comment claiming "it's handled" is exactly the gap that causes real incidents.
Structured elaboration
| Check | What to verify concretely |
|---|---|
| Data minimization | Does the PR description name the specific reason each new stored field is needed, not just "might be useful later"? |
| Access control | Point to the actual authorization check in the diff, a permission check or a row-level filter, not a comment asserting it's protected |
| PII (personally identifiable information) in logs | Grep the diff for new log statements touching user-supplied fields (email, name, IP, raw request bodies) and confirm they're redacted or omitted, not assumed safe because it's "just for debugging" |
| Encryption and handling | For a new field holding sensitive data (credentials, tokens, anything regulated), check it goes through the team's existing encryption or hashing utility rather than being stored raw, and that it can't leak into a client-facing API response by accident |
| Retention and deletion | If this data needs to be deletable later, e.g. for an account-deletion request under a privacy regulation such as GDPR (the EU's General Data Protection Regulation), check whether the PR updates or at least mentions the existing deletion or export path, or whether it silently creates a new place data lives that path doesn't know about |
Worked example
A PR adds a "recently viewed items" feature that stores a user's view history in a new table. Review pass: data minimization, does the feature need the full page content, or just an item ID and timestamp? Access control, is the table filtered by the requesting user's ID at the query level, not just hidden in the UI? Logging, a new debug log line dumps the entire view-history payload including the user's session token; flagged and removed. Retention, the existing account-deletion job doesn't touch this new table yet; raised as a blocking comment before merge.
Trade-offs and pitfalls
Treating this checklist as something only a dedicated security or privacy reviewer does means it gets skipped on every "small" PR by everyone else, and most real incidents come from exactly this kind of small, unglamorous change. Blocking every PR pending a full compliance review for genuinely low-risk data is its own failure mode, it trains people to route around the review entirely. Calibrate scrutiny to the actual sensitivity of the specific field, rather than treating all user data as equally high-risk.
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.