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.
Explain how you'd keep a team's style and formatting consistent without turning every review into a style debate. What tooling or process would you put in place, and how would you handle a one-off style exception an author asks for?
Sample Answer
Direct answer
Push style and formatting entirely to automated tooling, an auto-formatter and linter run in CI (continuous integration) and ideally on save, so it's never a human opinion sitting in the review thread. Reserve human review time for correctness, design, and readability, and treat a request for a one-off style exception as a signal to either update the rule for everyone or explain why it holds, not as a private negotiation inside one PR.
Structured elaboration
Tooling: an auto-formatter (a tool like Prettier or Black that rewrites code to one canonical style) plus a linter that catches what formatting alone can't, unused variables, inconsistent naming. Both run automatically in CI and block merge on failure; ideally they also run locally on save or commit, so the author never sees a style comment from a human at all.
Process: the team's style rules live in the linter's configuration file, not in people's heads or a wiki page nobody rereads. If reformatting a whole file would drown out a small behavior change in the diff, keep the formatting change in its own separate PR (pull request) so the actual change stays reviewable.
Handling a one-off exception request: treat it as data, not a special case. If it's genuinely justified (a generated file, or a block that's clearer left unformatted), add a scoped ignore with a one-line reason directly in the code or config, so it's documented and repeatable rather than a private favor. If it isn't clearly justified, the answer is: the rule applies to everyone, and if you disagree, propose changing the linter config for the whole team, which keeps the reviewer from personally overriding a shared standard.
Worked example
An author asks to keep a manually aligned table of constants instead of letting the formatter collapse it into the standard one-per-line style. The reviewer checks whether the formatter supports a scoped ignore comment for that block; it does, so it gets added with a one-line reason ("kept aligned for readability, formatter ignored here"). If the formatter had no such escape hatch, the reviewer would decline and suggest raising it as a team discussion about the formatter's config, rather than merging an inconsistent one-off that nobody else knows about.
Trade-offs and pitfalls
Over-configuring the linter with too many exceptions defeats its purpose, and each exception becomes its own small maintenance burden. A common pitfall is letting a senior engineer's exception slide without documenting it, which quietly erodes the "the tool decides, not the person" norm and reopens style debates for everyone else on the team.
A PR adds a nested loop that appears O(n*m) where n is number of users and m is number of groups; assume n and m can both be in the tens of thousands. As reviewer, how do you assess the performance risk, what data and tests would you request, and how would you recommend optimizing it? Provide concrete alternative approaches.
Sample Answer
Direct answer
Don't guess at the performance risk, ask for the actual expected scale of n and m in production, then reason about it using Big O notation, a way to describe how an algorithm's run time grows as its input grows. A nested loop checking group membership for every user against every group is O(n*m) work (n times m operations); swapping the inner check for a set or hash lookup usually turns it into roughly O(n+m).
Structured elaboration
Assess the risk: ask what n and m actually are in production today, and their growth trend, not just "tens of thousands" in the abstract. O(n*m) at 100 users is invisible; at 10,000 it is not.
Request data: ask for, or add, a benchmark or test using production-representative sizes, and check whether this runs on every request (much worse) or in a background or batch job (more tolerable, but still worth fixing before it becomes the bottleneck).
Recommend optimizing: the usual fix for "is X in this collection" checked repeatedly is to build a set or hash index of the smaller collection once, then do average-case O(1) membership checks inside the loop, turning O(n*m) into roughly O(n+m).
Concrete alternatives beyond a set: if this is database-backed, push the membership logic into a single indexed query or join instead of looping in application code at all. If it must stay in memory and the groups are static across the request, precompute the set once outside the loop rather than rebuilding it per user.
Worked example
Trace it by hand with a small example: 4 users, 3 groups, checking whether each user belongs to a group they were assigned. The nested-loop version compares every user against every group: 4 x 3 = 12 comparisons in the worst case. Building a set of the 3 group IDs first costs 3 operations, then each of the 4 users does one average-case O(1) lookup, so total work is roughly 3 + 4 = 7 operations instead of 12. Scaled to the size named in the question, n = m = 10,000: the nested loop does up to 10,000 x 10,000 = 100,000,000 comparisons, while the set-based version does roughly 10,000 + 10,000 = 20,000 operations, a gap of about 5,000x at that size, the kind of difference that turns a fast endpoint into a timeout.
Illustrative (not executed) code showing the shape of the fix:
# O(n*m): nested loop
result = []
for user in users:
for group in groups:
if user.group_id == group.id:
result.append(user)
break
# O(n+m): index the smaller side once
group_ids = {g.id for g in groups} # built once
result = [user for user in users if user.group_id in group_ids]
Trade-offs and pitfalls
Not every nested loop needs this treatment. If n and m are both small and bounded, a fixed list of five config options, the O(n*m) version is simpler to read and the "optimization" adds complexity for no real benefit. The reviewer's job is to ask about actual scale before insisting on a rewrite. A common wrong turn is fixating on the algorithmic complexity while missing that the real fix might be a database query instead of loading everything into application memory in the first place.
How would you establish a healthy code review culture for a team of 10 engineers? Include guidelines (e.g., review SLAs, size limits), tooling or automation you'd use, ways to keep reviews constructive, and metrics to track review health over time.
Sample Answer
Direct answer
Healthy review culture for a 10-person team rests on four things: norms that are written down instead of living only in people's heads, automation that handles anything mechanical so humans only judge what machines can't, feedback habits that separate blocking issues from opinions, and a couple of lightweight metrics you watch as a team trend, not a scorecard on individuals.
Structured elaboration
Guidelines to write down explicitly
- A review service-level agreement (SLA, an explicit response-time target): for example, first response (even just an acknowledgment) within one business day
- A soft pull request (PR, a proposed code change submitted for review before merging) size guideline, around 300-400 changed lines, as a norm that prompts a conversation, not a hard block
- Who reviews what: at minimum one reviewer, with a config file like CODEOWNERS (a file that maps directories or paths to the people or team required to review changes there) routing risky areas to the right person
- A shared convention for what blocks merge versus what's a nit, e.g. prefixing non-blocking comments with "nit:"
Tooling and automation
- Continuous integration (CI, the automated pipeline that builds and tests every push) must pass before a human review even starts, so reviewers spend attention on logic, not formatting or broken builds
- An auto-formatter enforced in CI so style is never a discussion
- A PR template with a description and testing section, so reviewers get context before they open the diff
- A stale-PR reminder (a bot nudge after 24-48 hours with no review) instead of a person having to nag
Keeping it constructive
- Comment on the code, not the person; phrase feedback as a question or suggestion ("what happens if this is empty?") rather than a command
- Call out good patterns in-line, not only problems
- Have the author explicitly separate "must fix" from "worth considering" in their own replies, so an optional suggestion doesn't turn into a blocking argument
Metrics to track over time
- Median time-to-first-review, to see if the SLA is actually being met
- Median PR size, to catch it drifting upward before it becomes a review bottleneck
- Review iteration count, a high number can mean unclear expectations or real scope creep, worth a look either way
- Report these at the team level over weeks or a quarter, never as an individual leaderboard, since metrics used to grade people get gamed
Worked example
A 10-engineer team starts tracking a rolling two-week median time-to-first-review. It's sitting at 30 hours against a one-business-day (roughly 8-hour) target. Looking at PR size alongside it, the median has crept from 150 to 420 lines over two months. Instead of telling people to "review faster," the team addresses the size trend directly: they add a bot that comments (not blocks) suggesting a split when a diff exceeds 400 lines, and a daily digest listing PRs waiting over 24 hours. Four weeks later, median size is back near 200 lines and time-to-first-review is under 12 hours, because smaller PRs are simply faster for people to unblock.
Trade-offs and pitfalls
- A hard size limit gets gamed, people split one change into artificial, badly-scoped pieces just to dodge it; keep it a norm with a conversation, not a blocking gate
- Metrics tied to individual performance reviews reliably erode trust and get gamed; keep them team-level and diagnostic
- Over-automating can remove judgment entirely, a linter should nudge a reviewer, not replace their read of whether a diff hangs together as a whole
- An SLA introduced without addressing capacity (too few reviewers for the review load) just adds pressure without fixing the real bottleneck
You are assigned to review a PR that adds extensive logging. What do you check for specifically when reviewing logging and observability changes? Provide a concrete example of logging you'd block a PR over and how you'd fix it.
Sample Answer
Direct answer
For a logging-heavy PR (pull request), review for three things: whether anything sensitive is being logged, whether the log level and volume are appropriate, and whether each line actually helps someone debug a real incident later. Logging that doesn't answer "what would I want to know when this breaks" is noise that makes the real signal harder to find.
Structured elaboration
Sensitive data: does any new log line include personally identifiable information (PII, such as email, name, or IP address), a credential, an auth token, or a full request or response body that might contain any of those? This is a blocking issue, not a nit, since logs are often long-retained and broadly readable.
Log level and volume: is a per-request or per-loop event logged at INFO or WARN when it happens thousands of times a minute? High-frequency, expected events belong at DEBUG, or as a metric instead of a log line entirely; INFO, WARN, and ERROR should be reserved for things a human would actually want to read or be paged on during triage.
Actionability: does the line include enough context to debug from, a request ID, the relevant entity IDs, what was attempted, or does it just note that something happened with no way to correlate it to a specific request?
Structured vs. free text: is this a structured log with queryable key-value fields, or a free-text string that only a human can grep, which stops being useful once volume gets high?
Concrete example to block over: logger.info(f"User {user.email} logged in with password {password}"). This should block the PR outright, it logs a raw credential and PII at a level everyone reads. The fix: logger.info("user login succeeded", extra={"user_id": user.id, "request_id": req_id}), structured, keyed on an internal ID instead of an email, with no credential material at all.
Worked example
A PR adds retry logging to a payment-processing service. Review pass: one log line dumps the full request payload, blocked, since it likely includes card metadata. Another fires at INFO on every cache hit, a high-frequency event moved to DEBUG or replaced with a counter metric instead. A third line, "payment retry attempt 2 of 3," is close but missing a correlation ID; the reviewer asks for a transaction ID to be added before approving.
Trade-offs and pitfalls
Stripping logging out entirely to "be safe" is its own failure mode, it leaves the team blind during the next incident. The right bar is specific and correlatable, not maximal or minimal. A common wrong turn is approving because "logging is generally good practice" without actually reading what's inside the string being logged.
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 Code Review and Working with Existing Codebases interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.