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.
A provisioning script currently creates thousands of cloud resources in a tight loop and runs for hours. As a reviewer, analyze the likely bottlenecks and propose an architecture-level and implementation-level redesign to scale provisioning to tens of thousands of resources reliably. Discuss batching, async/concurrency, provider API limits, idempotence, retries, and cost control.
Sample Answer
Direct answer
The core bottleneck is that a tight, sequential loop makes every provisioning call wait on the previous one, so total time scales linearly with resource count and is bounded by the provider's per-call rate limit rather than by anything the script controls. Scaling this reliably to tens of thousands of resources needs three things together: bounded concurrency with batched, idempotent calls to use the available rate-limit budget efficiently, a persisted state store so a crash mid-run can resume instead of restarting from zero, and explicit cost controls so parallelism doesn't turn a slow mistake into an expensive one.
Structured elaboration
Likely bottlenecks in the current script.
- Zero concurrency: each resource's API call, and any wait for that resource to become ready, blocks the next one from starting.
- No batching: one API call per resource where the provider likely supports a bulk-create call for many at once.
- No idempotence: a crash or timeout partway through leaves no reliable way to know what's already been created, so a naive retry either duplicates resources or requires a slow, careful manual reconciliation.
- No backpressure: nothing in a tight loop is watching for the provider's rate limit, so as request volume grows the script starts hitting throttling and retrying blindly.
Architecture-level redesign.
- A producer enqueues the full list of desired resource specs onto a work queue.
- A bounded pool of workers pulls specs off the queue and calls the provider API asynchronously and concurrently, batching where the API supports it and respecting a shared, client-side rate limiter across all workers (not per-worker, since the limit is per account or project, not per worker).
- A persisted state store (a simple table is enough) records desired versus actual state per resource, so progress survives a crash and a resumed run can skip anything already confirmed created.
- On a throttled response, a worker backs off with exponential delay and jitter and re-enqueues the item rather than retrying immediately.
flowchart TB
P[Producer: reads desired resource specs] --> Q[Work queue, one item per resource batch]
Q --> W1[Worker 1]
Q --> W2[Worker 2]
Q --> W3[Worker N, bounded pool]
W1 --> L[Client-side rate limiter shared across workers]
W2 --> L
W3 --> L
L --> API[Cloud provider API]
API -- throttled 429 --> BO[Exponential backoff with jitter, re-enqueue]
BO --> Q
API -- success --> ST[(State store: desired vs actual, checkpoints)]
ST --> MON[Cost and progress dashboard plus budget alert]
Implementation-level details.
- Idempotence: every resource spec carries a stable, deterministic identifier (a name or tag derived from its input, not randomly generated), so a worker can check "does this already exist" before creating, and a re-run after a crash is safe.
- Retries: exponential backoff with jitter, a hard cap on attempts, and a circuit breaker that pauses the whole pool if failures spike (a sign the provider itself is struggling, where hammering harder only makes it worse).
- Cost control: a dry-run mode that reports what would be created without creating it, a budget check before the run starts, and tagging every resource so cost and orphaned resources can be tracked back to this run specifically.
Worked example
Suppose the provider allows 20 requests per second sustained, and each resource needs exactly one API call. Provisioning 20,000 resources one at a time, rate-limit-bound, takes at minimum 20,000 / 20 = 1,000 seconds (about 16.7 minutes), even with zero other overhead, since the loop can never exceed the rate limit regardless of how fast the code itself runs. If the provider's API supports a bulk-create call for up to 25 resources per request, the same 20,000 resources need only 20,000 / 25 = 800 API calls, and at the same 20 requests/second limit that's 800 / 20 = 40 seconds of rate-limit-bound time, a 25x reduction, purely from batching, before concurrency is even considered. (Actual wall-clock time will be higher once per-call network latency and the resources' own boot/ready time are added; the number above is the rate-limit floor, not a promised runtime.)
Trade-offs and pitfalls
The queue, state store, and worker pool are real added operational complexity compared to a single script, which is a cost worth paying at tens of thousands of resources but likely overkill at a few dozen. Pushing concurrency too high can itself trigger stricter throttling or account-level abuse detection, so the worker pool size and rate limiter need tuning against the specific provider's actual behavior, not just cranked up. A common wrong turn: adding concurrency without adding idempotence first, since concurrent, non-idempotent retries are how you end up with duplicate resources faster than a sequential script would have.
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.
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.
Case-study: After an outage caused by a deployment automation bug, outline the steps of a blameless post-incident code review. Include how to identify contributing code, assess test gaps, propose fixes, validate changes, and update process and tools to prevent recurrence. Give a short checklist a reviewer should follow during the post-incident review.
Sample Answer
Direct answer
A blameless post-incident code review traces the technical chain from symptom to the specific code or config that caused it, separately assesses why existing tests didn't catch it, proposes and validates a fix against the actual failure mode rather than a plausible-sounding one, and closes by asking what should change about process or tooling, never who should have caught it.
Structured elaboration
Identify contributing code
Start from the incident timeline (what alert fired, what changed right before) and trace backward through deploys and config changes in that window to the specific commit or config diff responsible. Distinguish the triggering change from contributing conditions, for example the deploy that shipped the bug versus a missing safeguard, like a canary stage, that would have caught it regardless of who wrote the bug.
Assess test gaps
For the specific failure mode, ask whether a test should have caught this, and if so, why it passed or didn't run; if not, why the team's test strategy didn't anticipate this class of failure. Distinguish "no test existed" from "a test existed but didn't cover this input or environment" from "a test existed, caught it, and was skipped or ignored." Each implies a different fix.
Propose fixes
Fix the immediate bug, but separately evaluate a fix at each layer the incident revealed a gap in: code (the bug itself), test (missing coverage), and deployment safety net (a canary stage, a staged rollout, an automated rollback trigger) that would have limited blast radius even if the bug had shipped. Prioritize fixes that reduce blast radius or detection time even if they don't prevent every possible future bug, since prevention alone never fully succeeds.
Validate changes
Reproduce the original failure against the fix, a regression test that fails on the old code and passes on the new code, rather than trusting that the fix looks right. Where feasible, replay the actual conditions from the incident (same input, same environment shape) against the fixed code path.
Update process and tools
Translate the specific gap into a durable change: a new automated check, a canary stage, an alert threshold, not just a one-time "be more careful" note. Assign an owner and a deadline to each process or tooling change, and track it like any other work item, or it won't happen.
Short reviewer checklist for the post-incident review itself
- Is the technical root cause traced to a specific code or config change, with the causal chain shown, not asserted?
- Is there a regression test that fails on the pre-fix code and passes on the post-fix code?
- Was the test or detection gap identified, meaning why existing tests or monitoring didn't catch this?
- Does the write-up name a process or tooling change, not just the code fix, and does it avoid naming who wrote the original bug?
- Does each proposed follow-up have an owner and a deadline?
Worked example
A deployment automation script pushes a config change that disables health checks during a rolling restart, causing traffic to route to not-yet-ready instances and a 20-minute partial outage. Tracing backward: the script change that removed the health-check wait was correct for a different use case, a fast path for non-traffic-serving batch jobs, but got applied to the traffic-serving deploy path too, because the script didn't distinguish job types. Test gap: there was no integration test exercising a rolling restart against a traffic-serving service, only the batch-job path was tested. Fix: reintroduce the health-check wait as the default, require an explicit opt-out flag instead of an implicit shared code path, and add an integration test that asserts traffic-serving deploys wait for health checks. Validation: the new integration test fails against the pre-fix script, reproducing the incident, and passes against the fix. Process update: add a required "deploy-path classification" field to the automation config schema so a future change can't silently apply batch-job behavior to a traffic-serving path, with a named owner and a two-week deadline to ship the schema change.
Trade-offs and pitfalls
- "Blameless" doesn't mean incurious: skipping past exactly which code or config changed, to avoid seeming to point fingers, makes the write-up useless for actually fixing the class of bug; separate "who wrote it," which is irrelevant, from "what specifically changed," which is essential
- A fix validated only by manual testing or code reading, without a regression test that fails on the old code, risks re-shipping the same bug months later
- Process or tooling recommendations without an owner and a deadline are the single most common way post-incident reviews produce a document nobody acts on
- Over-rotating to prevent this exact bug from ever recurring, while ignoring the detection and blast-radius layer, leaves the team exposed to the next different bug that slips past review the same way
You are reviewing a Kubernetes deployment manifest in a PR. The file (excerpt) is:
apiVersion: apps/v1
kind: Deployment
metadata:
name: ingest
spec:
replicas: 3
template:
spec:
containers:
- name: ingester
image: mycompany/ingester:latest
List missing operational and security best practices you would require (resource requests/limits, probes, image policies, RBAC, securityContext, labels, etc.) and provide the exact changes you would request in the PR.
Sample Answer
Direct answer
This manifest is missing almost every operational and security safeguard a production deployment needs: no resource requests or limits, no health probes, an unpinned floating image tag, no selector or labels, and no security hardening. Each of these is a specific, concrete change to request in the pull request (PR), not a vague "please harden this."
Structured elaboration
- Resource requests and limits. Without them, one noisy pod can starve its neighbors of CPU (central processing unit) and memory on the same node, or get evicted unpredictably under cluster pressure with no warning.
- Probes. A liveness probe restarts a pod that's stuck; a readiness probe stops traffic from being routed to a pod before it's actually ready to handle it. Without either, Kubernetes has no way to know this container is unhealthy until something downstream notices requests failing.
- Image policy.
image: mycompany/ingester:latestis a floating tag, meaning the same tag can point at different code tomorrow than it does today, so nobody can say with certainty what's actually running in production at any given moment. Pin an immutable version tag instead. - Selector and labels. The spec is missing
spec.selector.matchLabelsentirely, which Kubernetes requires to know which pods this Deployment actually manages. Missing labels also break anything, dashboards, alerting rules, that groups pods by label. - RBAC (role-based access control) and service account. No
serviceAccountNameis set, meaning the pod runs with the namespace's default service account and whatever permissions that happens to have, instead of a minimal, purpose-built identity scoped to what this workload actually needs. - securityContext. Nothing here prevents the container from running as root or gaining new privileges inside the pod.
Worked example
The exact corrected manifest to request in the PR:
apiVersion: apps/v1
kind: Deployment
metadata:
name: ingest
labels:
app: ingest
team: data-platform
spec:
replicas: 3
selector:
matchLabels:
app: ingest
template:
metadata:
labels:
app: ingest
team: data-platform
spec:
serviceAccountName: ingest-sa
containers:
- name: ingester
image: mycompany/ingester:v1.2.3
imagePullPolicy: IfNotPresent
resources:
requests:
cpu: "250m"
memory: "256Mi"
limits:
cpu: "1000m"
memory: "1Gi"
livenessProbe:
httpGet:
path: /healthz
port: 8080
initialDelaySeconds: 15
periodSeconds: 10
failureThreshold: 3
readinessProbe:
httpGet:
path: /ready
port: 8080
initialDelaySeconds: 5
periodSeconds: 5
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
runAsNonRoot: true
capabilities:
drop:
- ALL
securityContext:
fsGroup: 2000
cpu: "250m" means 250 millicpu, a quarter of one CPU core, a starting point to tune against real observed usage once the service is actually running, not a universal constant to copy everywhere unchanged.
Trade-offs and pitfalls
Setting limits too tight causes the container to be throttled or killed under normal load, so requests and limits should come from observed usage where possible, and get revisited after the service has run for a while, not be treated as set-once-and-forget. readOnlyRootFilesystem: true sometimes breaks an application that writes temp files to disk, if so, mount a small writable emptyDir volume for exactly that path rather than disabling the protection entirely. This level of hardening is a reasonable starting checklist; a real production rollout would also want a PodDisruptionBudget (limits how many pods can be down at once during voluntary disruptions like node maintenance) and, for a service with variable load, a HorizontalPodAutoscaler (automatically adds or removes pod replicas based on load), both reasonable to request as fast follow-ups rather than blocking this PR on.
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.