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.
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.
You are reviewing a Helm chart for a critical service and notice templates that duplicate labels, interpolate values unsafely, and use imagePullPolicy: Always with latest tags. The Chart.yaml and templates are large. What templating anti-patterns would you flag, and how would you refactor the chart to be safer, testable, and reusable? Include unit-test strategies for Helm charts.
Sample Answer
Direct answer
Flag four things: labels duplicated by hand across every template instead of coming from one shared definition; values interpolated into templates without validation or escaping; a floating latest tag paired with imagePullPolicy: Always, which together mean a routine pod restart can silently run different code than yesterday with no corresponding deploy or review; and no schema validating what values are even allowed. Fix each with Helm's own built-in mechanisms, named template helpers and a values schema, and add automated tests that render the chart and assert on its output, not just "it deployed and looked fine in staging."
Structured elaboration
Helm is a templating and packaging tool for Kubernetes configuration, and a "chart" is Helm's name for a packaged, templated set of Kubernetes manifests.
Duplicated labels. When the same label block is copy-pasted into every template file, a future edit, adding a label, renaming one, has to be applied everywhere by hand, and it's easy to miss one file. That mismatch commonly shows up as a Deployment and its Service ending up with inconsistent selector labels, which silently breaks traffic routing.
Unsafe interpolation. Values pulled from .Values and dropped straight into a template without quoting or escaping can break YAML parsing if the value happens to contain a colon or a newline. If the tpl function is used on a value that itself came from user input, that value can be evaluated as a template, an injection-style risk rather than a simple substitution.
imagePullPolicy: Always with a :latest tag. This combination means every pod restart may pull whatever latest currently points to, so the exact code running in production can change silently, with no corresponding deploy or code review. This defeats reproducibility: two "identical" deployments a day apart can be running different code.
No schema. Without a values.schema.json, a typo'd or wrong-typed value, a string where a number was expected, either fails late, at template-render time, or worse, silently produces a broken manifest instead of a clear, upfront error at the point someone actually made the mistake.
Worked example
The label-duplication fix, using a Helm named template, a reusable snippet defined once and included wherever it's needed:
{{- define "mychart.labels" -}}
app.kubernetes.io/name: {{ include "mychart.name" . }}
app.kubernetes.io/instance: {{ .Release.Name }}
{{- end -}}
used in every template as:
metadata:
labels:
{{- include "mychart.labels" . | nindent 4 }}
so a future label change happens in exactly one place instead of N copy-pasted ones. The image fix, moving from a hardcoded floating tag to a pinned, values-driven one:
image:
repository: repo/name
tag: "1.2.3"
pullPolicy: IfNotPresent
referenced in the template as image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}", with a continuous integration (CI) check that rejects a chart whose values.yaml still sets tag: latest.
Unit-test strategy. Use a Helm-specific unit-test tool (for example, the helm-unittest plugin) to render the chart with a specific set of values and assert directly on the resulting YAML: one test asserting the Deployment and the Service end up with identical app.kubernetes.io/name labels, which catches the exact duplication bug above if it ever regresses, and another asserting the rendered image string matches values.image.repository:values.image.tag across a couple of different input value sets. Add a policy check, for example using Conftest with Open Policy Agent (OPA) policies, that scans the rendered manifests and fails the build if it finds an image tag of :latest or imagePullPolicy: Always in a production values file. Run helm lint --strict plus helm template piped into a schema validator as a cheap smoke test that the chart at least produces well-formed manifests for a few representative value combinations.
Trade-offs and pitfalls
Centralizing labels into one named template is strictly safer overall, but if the helper itself has a bug, it now affects every resource at once instead of just one, so the helper deserves its own direct unit test, exactly the coverage gap this refactor is meant to close. Pinning image tags is the right default, but it does mean a rollback or a security patch has to bump the pinned tag explicitly rather than "just redeploy," a small process cost worth accepting for the reproducibility it buys. A values schema catches type errors early but adds its own maintenance surface, the schema has to be kept in sync with values.yaml by hand unless the team invests in generating one from the other.
You are responsible for integrating static-analysis tools for a compiled monitoring agent written in Go. As a reviewer, which tools/checks would you require in CI and which classes of defects do they catch (formatting, race conditions, undefined behavior, performance issues)? Explain how to prioritize fixes found by these tools in PR reviews.
Sample Answer
Direct answer
I'd require a small, layered set of tools in CI rather than one do-everything linter: an auto-fixable formatter for style, a vet-style correctness checker for undefined-behavior-class bugs, the language's built-in data-race detector for concurrency bugs, and benchmarks for performance regressions. Then I'd prioritize fixes by what class of defect they represent, not by which tool happened to report it: races and correctness bugs block the merge, performance and style don't.
Structured elaboration
Formatting. Go ships a canonical formatter (gofmt, plus goimports for import ordering) that produces one deterministic output for any given source file. Running this in CI and failing on any diff removes formatting from human review entirely, since there's no room for a style opinion once the formatter is authoritative.
Undefined behavior and correctness. go vet catches a specific, well-known set of suspicious constructs (a Printf-style call whose format string doesn't match its arguments, a struct copied by value that embeds a mutex, which silently breaks that mutex's locking guarantee for the copy). staticcheck goes further: unreachable code, an unused error return, or a comparison that can never be true.
Race conditions. Go's toolchain has a built-in data race detector (a data race is two goroutines, Go's lightweight concurrent tasks, accessing the same memory at the same time with at least one of them writing, and no synchronization between them), invoked with go test -race. This instruments the binary and reports real races observed while the tests run; it can't find a race that no test path exercises, so it's only as good as test coverage of the concurrent code paths.
Performance. Go's benchmark tooling (go test -bench, combined with the same heap/CPU profiler used for leak hunting, pprof) surfaces regressions when compared against a stored baseline, rather than trying to guess at performance from source alone.
Prioritizing fixes in review. I'd rank findings by consequence, not by tool:
- Blocking: data races, and any
go vet/staticcheckfinding that represents an actual correctness bug (the mutex-copy example above is a real bug, not a style nit). - Strongly recommended before merge: ignored errors on operations that can fail meaningfully, and confirmed performance regressions with a benchmark to back them up.
- Follow-up acceptable: non-blocking staticcheck suggestions, dead code that adds noise but no risk.
- Auto-fixed, not discussed: formatting and import ordering, since a human should never spend review time on something a formatter already fixed for them.
Worked example
A PR modifies a shared Stats struct that's passed around by value and embeds a sync.Mutex. go vet flags this: copying a struct that embeds a lock triggers its copylocks check, warning that the assignment copies a lock value. That's not a style nit, it's a real bug: copying a struct that contains a mutex creates a second, independent lock, so code holding the copy's lock provides no actual protection against code holding the original's lock, and the two sides can now race on the data the mutex was supposed to protect. Separately, go test -race flags a genuine concurrent map write elsewhere in the same PR, and gofmt reports three files with import-order diffs.
Prioritization: the mutex-copy bug and the concurrent map write are both blocking, since both are real correctness/concurrency bugs, not opinions; the import-order diffs get auto-fixed by running goimports -w and are never discussed in review at all.
Trade-offs and pitfalls
Running -race on every test invocation roughly doubles memory use and meaningfully slows the run, so most teams run it in a dedicated CI lane rather than on every local go test. Turning on a strict linter for the first time in a legacy repo produces a wall of pre-existing findings that block every future PR unless you baseline them (only fail on NEW findings in changed lines) rather than demanding the whole codebase get fixed at once. The most common pitfall in review is treating every tool finding as equally urgent: burying a genuine data race in the same list as ten cosmetic suggestions makes it likely the race gets the same "eh, later" treatment as the cosmetics.
Security review: you find an IaC change that opens a security group to 0.0.0.0/0 for SSH and stores a service account key in a repo variable file. As the reviewer, propose a remediation plan that enforces least privilege, performs minimal disruption, and includes a migration path to rotate credentials and tighten rules. Include both code changes and rollout steps.
Sample Answer
Direct answer
Treat this as two separate, both-urgent problems: the network rule is wide open (0.0.0.0/0, meaning any IP address on the internet, on port 22, the SSH, or secure shell, port), and there's a live credential sitting in version control where anyone with repository access, including in its full history, can read it. Block the pull request (PR) immediately, revoke the exposed key as a first action independent of the rest of the fix, then land a staged remediation: narrow the network rule, move the credential to a secrets manager, and roll both changes out in an order that doesn't lock out legitimate access.
Structured elaboration
IaC (infrastructure as code) means infrastructure like network rules is defined in version-controlled configuration files rather than clicked together manually.
Immediate actions, before any code review of the fix itself. Revoke or rotate the exposed service-account key right away. Removing a secret from the current version of a file does not remove it from that file's git history, so treat the leak as effectively public the moment it's committed, whether or not it's actually been read by anyone yet.
Code changes for least privilege. Replace the 0.0.0.0/0 SSH rule with either a narrow allow-list of known admin IP ranges, or, stronger, remove inbound SSH entirely and require a bastion host (a single hardened server that's the only machine allowed to SSH into everything else, so you lock down one entry point instead of every server having its own open port) or a managed session broker, such as a cloud provider's session-manager service, that needs no open inbound port at all. Move the service-account key out of the repository variable file and into a managed secrets store, and change the consuming code to read the secret from there via a scoped identity, an instance or task role, rather than a static key baked into config.
Minimal-disruption rollout. Land the network-rule change in a lower environment first and verify admin access still works through the new path before touching production. For the secret migration, run the new secret-store-based access path in parallel with the old key briefly, so nothing breaks mid-cutover, then remove the old key from the variable file and from the running configuration once the new path is confirmed working.
The credential-rotation path specifically. Generate a new key inside the secrets store, deploy the change that reads from the secrets store, verify functionality against the new key, then revoke the old key, in that order. Never revoke the old key first and hope the new path works, that risks an outage instead of a security fix, except for the already-leaked key itself, which is the one case where the security risk of leaving it live outweighs the availability risk, so it gets revoked immediately, even ahead of the rest of the remediation.
Preventing recurrence. Add a CI (continuous integration) check that scans for secrets in commits before merge, and a policy check that rejects an inbound rule allowing 0.0.0.0/0 on an administrative port like 22, so this same class of mistake can't land again without an explicit, reviewed exception.
Worked example
An illustrative before-and-after in Terraform-style HCL (HashiCorp Configuration Language, the syntax Terraform configuration files are written in; the exact resource and argument names vary by IaC tool and cloud provider, so verify these against the actual provider docs the team uses before merging):
# Before: open to the world
resource "example_security_group_rule" "ssh" {
type = "ingress"
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
# After: narrowed to a known admin range (or remove entirely if using a session broker)
resource "example_security_group_rule" "ssh" {
type = "ingress"
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = var.admin_cidr_allowlist # e.g. the office/VPN egress range, not the whole internet
}
The secret migration follows the same before-and-after shape: the old file held a plaintext value (service_account_key = "...") checked directly into the repository; the new code instead reads a reference to a secrets-store entry, a name or identifier, not the key value itself, and the actual key material lives only inside the secrets store and in the running process's memory, never in a file version control tracks.
Rollout steps, in order. (1) Revoke the exposed key immediately, independent of everything else. (2) Merge and deploy the network-rule narrowing to a non-production environment first, and confirm admin access still works. (3) Generate a new key in the secrets store and deploy the code change that reads from it. (4) Verify the service still functions against the new key. (5) Roll the network and secret changes to production the same way. (6) Add the CI secret-scanning and network-policy checks so this class of issue can't silently recur.
Trade-offs and pitfalls
Narrowing the SSH rule to an office or VPN IP range is simpler to roll out than removing inbound SSH entirely, but it's weaker, since anyone on that network segment still has network-level access; removing inbound SSH in favor of a session broker is the stronger fix but a bigger change that needs its own testing. Rotating a credential before its new access path is verified working risks an availability incident, which is why the rollout order above deploys the new path first and only then revokes the old key, with the sole exception of the already-leaked key, whose security risk outweighs that availability concern.
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.