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.
How would you detect secrets leaked in a PR or git history, and what would you actually do about it: immediate reviewer actions, secret rotation, and cleaning up the history? Name the tools you'd reach for and walk through the trade-offs of your remediation approach.
Sample Answer
Direct answer
I detect leaked secrets with automated scanning, both in CI on every PR and as a pre-commit hook on developer machines, using a dedicated secret scanner rather than relying on human review to spot them. Once found, the sequence is always the same regardless of remediation approach: rotate the credential immediately, then separately decide whether the exposure also needs to be scrubbed from git history, since those are two different problems with two different urgencies.
Structured elaboration
Detection tools. gitleaks and truffleHog scan a repository or a diff for patterns that look like credentials (API key formats, private key headers, common token shapes); git-secrets is a lighter pre-commit-focused option. Many hosted platforms also offer built-in secret scanning on push, which can block the push entirely before the secret ever reaches a shared branch, which is strictly better than catching it after the fact in review.
Immediate reviewer actions. If it's caught in a PR that hasn't merged yet: block the PR, and if the branch hasn't been pushed to a shared/protected branch, the author can often just rewrite their local history (amend or interactive rebase) and force-push a clean version, meaning the secret may never actually land in the repository's permanent history at all. Either way, treat the credential as compromised the moment it left a developer's machine, since it may already be visible in CI logs, in anyone who pulled the branch, or cached by the hosting platform itself, regardless of whether it ever reaches the default branch.
Secret rotation. Rotate first, always, independent of whatever happens to git history: generate a new credential, update every system that consumes it (deployment pipeline, running services, other developers' local environments), verify the new one works, then revoke the old one. This is the step that actually closes the exposure; history cleanup on its own does not, since a secret already scraped or cloned by someone stays valid until it's rotated.
Cleaning git history. Only needed if the secret already reached a shared branch. git filter-repo is the currently recommended tool for rewriting history (it replaced the older, simpler BFG Repo Cleaner as the generally recommended option, though BFG is still common and simpler for basic cases). Both require a force-push and coordination: every existing clone and open PR based on the old history becomes stale and needs to be re-cloned or rebased, which is real organizational disruption, not just a technical step.
Worked example
An AWS access key literal shows up in config.py in an open PR. As reviewer, I block the merge immediately and comment describing exactly what to do: remove the key from the diff, and separately (in parallel, not instead of) notify whoever owns that AWS account to rotate the key right now, since the moment it was pushed to the PR's remote branch it was visible in GitHub's systems and CI logs regardless of whether the PR ever merges. Because the PR hasn't merged to the default branch, the author can amend the offending commit locally and force-push the corrected branch, meaning the key likely never needs a full history rewrite of the shared branch, only its own rotation.
Trade-offs and pitfalls
Rewriting shared git history is disruptive enough (a mandatory force-push, every collaborator needing to reset their local clone) that many teams choose to rotate-and-leave-history-alone rather than rewrite, accepting that the old, now-revoked value stays visible in history forever; that's a reasonable trade when the credential can be fully rotated, and a much weaker option when the "secret" is something that can't be rotated, like a hardcoded document containing real customer data. The most common pitfall is treating history rewriting as the fix and skipping or delaying rotation, when rotation is the step that actually stops the credential from being usable, and history cleanup by itself does nothing about a secret that was already copied somewhere before it was removed.
You are reviewing a large refactor that touches core library internals. Outline a plan to split the change into incremental PRs that are safe to merge independently. Include a proposed sequence, how to keep the system working at each step, feature flagging, test strategies, and rollback points.
Sample Answer
Direct answer
I sequence the refactor so the public interface changes land first, additively, before internals move; I migrate call sites one at a time behind a feature flag with small commits that each leave the system green, and I pick a rollback point at every seam so the whole plan is expand-migrate-contract rather than one big merge.
Structured elaboration
Sequencing principle: expand, migrate, contract
- Expand: add the new internal implementation alongside the old one, without removing anything
- Migrate: switch call sites over incrementally, one at a time, behind a flag
- Contract: once every call site is migrated and validated in production, delete the old code path in its own final, low-risk pull request (PR, a proposed code change submitted for review)
Interface first
If the refactor changes a library's public interface, not just its internals, land the new interface signature first as a strictly additive change (a new method or overload alongside the old one) before implementation work even starts. This lets consumer teams see or start adopting the new shape while the internals are still being built, instead of waiting for one giant landing.
Verify against real consumers, not just the library's own tests
Before merging any internal change, run each consumer's recorded expectations of the library (its actual inputs and outputs, sometimes called a consumer-driven contract) against the new implementation. This catches the case where the internals pass the library's own unit tests but silently break an assumption a downstream consumer relied on that the library never tested itself.
Branching and commit order
Prefer small commits on a short-lived branch or trunk-based development, with the feature flag doing the isolation, over a long-lived branch. A stale long-lived branch reintroduces the exact big-bang-merge risk this plan exists to avoid. Order commits so each one compiles, passes CI (continuous integration, the automated build/test pipeline), and leaves the system deployable: add the new path unused, add the flag defaulting off, migrate the lowest-risk call site, validate, migrate the rest in ascending risk order, then remove the old path.
Test strategy at each step
- Characterization tests (tests that pin down what the old code currently does, written before touching it) on the existing implementation first
- Consumer contract tests run on every PR in the sequence, not only the last one
- Shadow-run the new path against the old path's output on real traffic where feasible, before flipping the flag for real
Rollback points
Every PR that flips a flag default is a rollback point: flipping the flag back is the fast rollback, no code revert or redeploy needed. The final "delete the old path" PR is the one true point of no return, so it ships last, only after a full soak period with the flag on.
flowchart LR
A["PR1: add new path, flag off"] --> B["PR2: add consumer contract tests"]
B --> C["PR3: implement new internals"]
C --> D["PR4: migrate lowest-risk consumer"]
D --> E["PR5-7: migrate remaining consumers"]
E --> F["PR8: delete old path"]
Worked example
Refactoring a core PaymentValidator library used by 4 internal services, changing its algorithm from a synchronous rule chain to a rule-table lookup for performance. PR1 adds validate_v2() alongside the existing validate(), unused, behind a payment_validator_v2 flag defaulting off, plus characterization tests pinning validate()'s current output on 50 representative inputs. PR2 adds contract tests recording each of the 4 consumers' actual usage patterns against validate(). PR3 implements validate_v2(), which must pass every contract test. PR4 migrates the lowest-risk consumer, an internal reporting service, behind its own flag, monitored for a week. PR5-7 migrate the remaining 3 consumers one at a time, with live payment processing last, each with its own soak period. PR8, once all 4 consumers are on v2 and soaked through a full billing cycle, deletes validate() and the flag. If PR5's shadow comparison shows a discrepancy in production, the rollback is flipping that one consumer's flag back, not reverting code.
Trade-offs and pitfalls
- Expand-migrate-contract takes longer in calendar time and leaves two code paths live temporarily, itself a maintenance cost and a place bugs can hide (fixing one path and forgetting the other)
- Skipping consumer contract tests and relying only on the library's own unit tests is the classic way this goes wrong: internals look correct in isolation but violate an assumption a consumer depended on
- A stale long-lived branch reintroduces the exact big-bang-merge risk the plan exists to avoid; if small trunk-based commits aren't feasible, that's a signal the split needs to be finer-grained, not a reason to accept one large final merge
- Deleting the old path before every consumer has soaked removes the rollback safety net that made the whole plan low-risk in the first place
Technical coding: Given the following Python function used in a deployment script, write pytest unit tests that cover normal behavior and edge cases. Mock external API calls.
import requests
def get_latest_image(repo):
r = requests.get(f'https://registry.example/api/{repo}/latest')
r.raise_for_status()
return r.json()['tag']
Provide at least three tests and explain why you chose them.
Sample Answer
Direct answer
I'd write at least four tests, covering the success path, an HTTP error response, a malformed JSON body missing the expected key, and a network-level failure like a timeout, all with requests.get mocked so no test makes a real network call. Each test targets a distinct way this function can fail in production, not just variations on the happy path.
Structured elaboration
Approach. Mock requests.get so the function's own logic, not the network, is what's under test. For each test, build a fake response object with just enough behavior to drive the code path being tested (raise_for_status either does nothing or raises, json() returns a controlled payload), then assert on get_latest_image's return value or on the exception it raises.
Why these specific tests.
- Success proves the normal path works and the correct value is extracted from a realistic JSON payload.
- HTTP error (a 4xx or 5xx status) proves the function surfaces the failure via
raise_for_status()rather than silently returning something wrong. - Missing key in the response body proves that if the API's response shape doesn't match what the code expects, the caller gets a clear exception rather than a confusing downstream error somewhere else.
- Network-level failure (a timeout, a connection error) proves the function doesn't swallow or mask an infrastructure problem, which matters specifically because this function is used in a deployment script where a caller needs to know the difference between "the deploy image genuinely doesn't exist" and "we couldn't reach the registry at all."
Worked example
# deploy_utils.py
import requests
def get_latest_image(repo):
r = requests.get(f'https://registry.example/api/{repo}/latest')
r.raise_for_status()
return r.json()['tag']
# test_deploy_utils.py
from unittest.mock import Mock, patch
import pytest
import requests
from deploy_utils import get_latest_image
def make_response(json_data=None, raise_error=None):
resp = Mock()
resp.raise_for_status = Mock(side_effect=raise_error) if raise_error else Mock()
resp.json = Mock(return_value=json_data or {})
return resp
def test_get_latest_image_returns_tag_on_success():
resp = make_response(json_data={'tag': 'v1.2.3'})
with patch('deploy_utils.requests.get', return_value=resp) as mock_get:
result = get_latest_image('myapp')
assert result == 'v1.2.3'
mock_get.assert_called_once_with('https://registry.example/api/myapp/latest')
def test_get_latest_image_raises_on_http_error():
resp = make_response(raise_error=requests.exceptions.HTTPError('404 Client Error'))
with patch('deploy_utils.requests.get', return_value=resp):
with pytest.raises(requests.exceptions.HTTPError):
get_latest_image('missing-repo')
def test_get_latest_image_raises_keyerror_on_malformed_body():
resp = make_response(json_data={'digest': 'sha256:abc'})
with patch('deploy_utils.requests.get', return_value=resp):
with pytest.raises(KeyError):
get_latest_image('myapp')
def test_get_latest_image_propagates_network_timeout():
with patch('deploy_utils.requests.get', side_effect=requests.exceptions.Timeout):
with pytest.raises(requests.exceptions.Timeout):
get_latest_image('myapp')
Actually run with pytest, output:
test_deploy_utils.py::test_get_latest_image_returns_tag_on_success PASSED
test_deploy_utils.py::test_get_latest_image_raises_on_http_error PASSED
test_deploy_utils.py::test_get_latest_image_raises_keyerror_on_malformed_body PASSED
test_deploy_utils.py::test_get_latest_image_propagates_network_timeout PASSED
4 passed
Complexity
This is straightforward, constant-time mocked I/O per test, no algorithmic complexity to speak of; the interesting design decision is which failure modes are worth a dedicated test, not runtime cost.
Edge cases
- A 500 server error takes the exact same code path as a 404, since both raise via
raise_for_status(); one test covering "any HTTP error" is representative, a second status-specific test adds little. - A response that's valid JSON but not a dict at all (a bare list, for example) would raise
TypeErrorrather thanKeyErrorwhen['tag']is applied; worth a fifth test if this API's contract is genuinely uncertain. - Real production code often uses a
requests.Sessionwith a configured retry adapter rather than a barerequests.get; mocking at therequests.getlevel, as done here, doesn't exercise that retry behavior at all, which would need a different test approach.
Trade-offs and pitfalls
Mocking at the requests.get level is fast and has zero network flakiness, but it also means these tests can't catch a real integration problem, like the registry's actual response shape changing; a smaller number of separate integration tests against a real or realistic staging registry are worth having alongside these, not instead of them. A common pitfall is mocking so aggressively that the test asserts almost nothing about get_latest_image's own logic, for example forgetting to assert on the exact URL called, which would let a bug in the f-string (a wrong path, a typo) slip through unnoticed.
You're reviewing a SQL database migration script that will alter a large table used by a high-traffic service (5GB, heavy writes). List the code-review and operational items you would check specifically for migrations. Cover transactional behavior, lock duration, backfills, rollout strategy, monitoring, and rollback.
Sample Answer
Direct answer
For a migration touching a 5GB, heavy-write table, I check six things specifically: whether the change runs inside a transaction and what that actually implies for locking, how long any lock is held and what kind, whether backfills are batched instead of one giant statement, how the change rolls out (all at once or staged), what's monitored during and after, and whether there's a real rollback path, not just "revert the migration file."
Structured elaboration
- Transactional behavior. Some DDL (data definition language, schema-changing statements like
ALTER TABLE) is transactional and can be rolled back cleanly if something fails mid-statement; some isn't, and a failure partway through leaves the schema in a partially-changed state. This differs by database engine and even by the specific kind of ALTER, so I check what's actually true for the database and statement in question rather than assuming. - Lock duration. The real question is what kind of lock the statement takes and for how long. On Postgres,
ADD COLUMNwith a constant default has been a fast, metadata-only change since Postgres 11, but adding aNOT NULLconstraint that requires validating every existing row, or an index build withoutCONCURRENTLY, still takes a lock for the duration of that work. On MySQL 8.0+, manyALGORITHM=INSTANToperations (a modifier that changes only table metadata instead of rewriting existing rows, including some column adds) are near-instant, but not all ALTER variants qualify, and older MySQL versions may rebuild the whole table. I check which case this migration actually falls into for the target database and version, not just assume it's cheap. - Backfills. A backfill on a 5GB table should never be one giant
UPDATE, which holds locks and generates a huge amount of write-ahead log or binlog (the record every database write generates so changes can be replayed or recovered) in one shot. It should run in small batches (a boundedWHEREclause, a sleep or throttle between batches), be resumable from where it left off, and be idempotent (safe to re-run a batch that partially completed). - Rollout strategy. For anything beyond a trivial, fast schema change, I look for a staged rollout: add new structure first without changing behavior, deploy application code that can handle both old and new shapes, backfill, then only later switch behavior over, rather than one migration that changes schema and behavior simultaneously.
- Monitoring. During the migration I want to see replication lag, lock wait time, and query latency on this table specifically, not just overall database health, since a table-specific problem can hide inside a healthy-looking aggregate.
- Rollback. A real rollback plan says what to actually do if something goes wrong mid-migration, not just "we have backups." For a pure schema addition, that's usually just dropping the new column; for anything involving a backfill or application-visible behavior change, it needs to say how to safely stop and either resume or revert without leaving the table in a half-migrated state.
Worked example
The migration adds a NOT NULL column with a default to the 5GB table. On a database and version where that's not a metadata-only operation, the safe sequence is: add the column as nullable with no default first (cheap), backfill it in batches ordered by primary key, verify every row is populated, then add the NOT NULL constraint (which on Postgres can validate against already-known-good data faster once nothing is actually null). A batch looks like:
UPDATE big_table
SET new_col = <derived value>
WHERE id BETWEEN :batch_start AND :batch_end
AND new_col IS NULL;
run in a loop over consecutive primary-key ranges with a short pause between batches, so the migration never holds a lock or generates a burst of writes for longer than one small batch takes.
Trade-offs and pitfalls
Splitting a migration into more, smaller, safer steps is real added engineering and coordination work compared to "just run the ALTER," and for a genuinely small or low-traffic table that overhead isn't justified; the 5GB, heavy-write detail in the question is exactly what tips the balance toward doing it the careful way. A common pitfall is testing the migration only against a small local database, where an operation that's instant on a toy table can be a multi-minute, lock-holding operation on the real, much larger one, so the review should ask whether this was tested against production-scale data, not just correctness-tested against a handful of rows.
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.
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.