Learnings

Senior engineering skills

Code Review and Mentoring

What to look for in a pull request, in what order, and how to say it so the author fixes the code and still wants your next review. Eight small diffs on the bank each hide one planted bug: they are real git diff output from a scratch repository (Python 3.9, SQLite, pytest 8.4, ruff 0.17), and every failure shown was run.

What review is for

Part 1 of 6 · goals, place in the flow, order of attention

Goals, and non-goals

What review is for

Review is a second person understanding a change before it ships. Finding bugs is one of five results, and often not the largest.

Five things one review buys.
Review is not forWhat does that job
Style a tool can checkFormatter and linter in CI
Gatekeeping, proving who is seniorNothing. It only slows the team.
The first look at a big designA design review before the code
The only safety netTests, staged rollout, monitoring

Where review sits

What review is for

Machines go first, so a human never spends attention on what a tool can decide. The pipeline side is in CI/CD with GitHub Actions.

Two gates. The human one opens only after the machine one is green.
Machines checkHumans check
Formatting, import orderIs this the right change at all
Lint rules, type errorsDesign, names, where the code lives
Tests pass, coverage did not dropDo the tests test the behaviour
Known vulnerable packages, committed secretsFailure modes, rollout, what is missing

The order of attention

What review is for

Review from the top down. A naming comment on code that solves the wrong problem wastes two people's time.

Stop at the first level that fails, and say so before going lower.
LevelAsk
1. ProblemDoes the description say why? Does the change do that, and only that?
2. DesignIs this the right place and shape? What would the next change here look like? (design principles)
3. CorrectBoundaries, empty input, failure halfway, two requests at once
4. TestedWould a test fail if I broke this line?
5. Safe, operableCan it be rolled back? What will on-call see when it fails?
6. ReadableCould a new teammate change this in six months?
7. StyleNothing. If a tool did not complain, neither do you.

The checklist by area

What review is for

Not every row applies to every diff. Pick the rows the change touches.

AreaLook forWorked review
CorrectnessDoes each branch do what the description says1
Edge casesZero, one, the limit itself, empty, very large, duplicates1
Error handlingBroad except, errors turned into success, lost context4
ConcurrencyRead then write without a lock, shared mutable state, retries that repeat5
Data, migrationsSeveral writes in one transaction, reversible migration, old code against new schema2
SecurityInput trusted too early, missing permission check, secrets in logs8
PerformanceQuery in a loop, unbounded result, work repeated per request3
ObservabilityWill a failure be logged, counted and traceable to a request4
TestsAssertions exist, failure path covered, test fails when code breaks6
API compatibilityChanged field, type, default, argument order, error code7
Naming, readabilityNames that say what, comments that say why, dead code

Eight worked reviews

Part 2 of 6 · real diffs, one planted bug each, with evidence

The repository under review

Eight worked reviews

A small bank on SQLite: bank/ledger.py moves money, bank/api.py returns JSON-shaped views, six tests pass on main. Each review below is a branch off this main.

  • with conn: on a sqlite3 connection commits on success and rolls back on an exception.
  • Test accounts: ACC-1001 (Rishikesh Agrawani, 80000), ACC-1002 (Sandhya Agrawani, 12000), ACC-1003 (Subhash Agrawani, 800).
  • Diffs are shown without their diff --git and index lines. On every branch the full test suite passed.

1. The limit that rejects the limit

Eight worked reviews

The description says: "Transfers of up to 50,000 are allowed. Anything above is rejected."

Noticed: "up to 50,000" includes 50,000, and >= does not. The one new test uses 60,000, far from the edge, so nothing pins the boundary.

Fix and habit: > instead of >=, then 10 passed. For every comparison against a limit, ask for three tests: just under, exactly on, just over.

2. The tidy refactor that loses money

Eight worked reviews

The description says: "Simplify transfer: reuse withdraw and deposit." Fewer lines, same tests, all green.

Noticed: the docstring lost "Both sides happen, or neither", and it lost it honestly. withdraw and deposit each commit on their own, so the single transaction became two.

The second step fails after the first is already permanent.

That test, run against the branch, fails with AssertionError: assert 75000 == 80000 (1 failed, 6 passed).

Fix: restore the original five lines of transfer. With them the script prints after: 92000 and the suite is 7 passed.

3. The statement with N + 1 queries

Eight worked reviews

A new month-end endpoint returns every account with its entries. The test uses three accounts and passes in a blink.

Noticed: a query inside a loop over query results. One query for the accounts, then one more per account.

The cost is the round trip, not the query.

In-memory SQLite has no round trip, so the evidence script wraps the connection to count queries and add 1 ms to each, standing in for a database on another host.

Trap: an ORM hides the loop. for account in accounts: account.entries is the same bug with no SQL in sight.

4. The batch that never fails

Eight worked reviews

A monthly job runs standing orders. The description says: "One bad order must not stop the run."

Noticed: the goal is right and the method hides everything. A failed order is counted as processed, nothing is logged, and except Exception also swallows real bugs such as a TypeError.

Tooling: ruff check --select S,BLE flags this diff as S110 (try-except-pass) and BLE001 (blind except). Neither group is in ruff's default rule set, so a default lint job stays green.

5. The default list shared by everyone

Eight worked reviews

Plain-text statement lines for the monthly email. The test calls the function once.

Noticed: lines=[] is built once, when def runs. Every call without lines appends to that same list.

State shared across calls, and in a server across requests.

After the fix the second line is ['ACC-1002 +700 deposit'] and ruff --select B passes.

Same family: module-level dicts used as caches, class attributes that are lists, and a client object reused across threads. Ask "who else can see this object?"

6. The tests that cannot fail

Eight worked reviews

A tests-only pull request: "Add coverage for overdraft and ledger entries." Eight passed, coverage went up.

Noticed: the first test passes whether or not the exception is raised. The second compares and throws the result away: there is no assert.

The proof is to break the code and watch the tests stay green. Here the overdraft check and the entry insert are both deleted from _post.

Against the same broken code the fixed tests fail: DID NOT RAISE InsufficientFunds and assert [] == [...], 2 failed. On the real code all 8 pass.

Tooling: ruff's B015 flags the missing assert (checked on this diff). Nothing in E, F or B flags the try/except/pass test, so that one needs a reader.

7. The response that changed shape

Eight worked reviews

The description says: "Return the currency with the balance." The module docstring says clients outside this repository read these views.

Noticed: an existing assertion had to be edited to keep the test green. That is the signal: balance changed from a number to an object, and every reader of it is outside the diff.

The diff shows the producer. The damage is in consumers it does not show.
Safe for old clientsBreaking
Adding a field, or an optional argument with a defaultRemoving or renaming a field or argument
Accepting more input than beforeChanging a type, a unit, a default or the argument order
A new endpoint or versionA new required input, a changed status code or error shape

8. The OTP in the log

Eight worked reviews

The description says: "Log transfer requests so support can trace them." A useful aim, and the diff looks harmless.

Noticed: the line above the new log call lists the payload keys, and two of them are otp and mobile. Logging the whole object logs both.

A log line is copied further and kept longer than the database row.

Rule: never log a whole request, payload, header set or exception that carries one. More in Security Basics.

Comments, and being reviewed

Part 3 of 6 · writing comments that land, and receiving them

Harsh or vague, against useful

Comments, and being reviewed

A useful comment has three parts: what you saw, why it matters, what you suggest. Write about the code, never about the author.

Harsh or vagueUseful
This is wrong.A transfer of exactly 50,000 is rejected here, and the description allows it. >?
Why did you do it this way?What made two calls better than one transaction here? I may be missing a constraint.
This will never scale.This is one query per account: 2001 queries for 2000 accounts. One grouped query would do.
Did you even test this?These tests pass with the check deleted. pytest.raises would make them bite.
You always swallow exceptions.This except Exception hides failed orders. Catch BankError and log it?
We don't do it like that here.The other views return flat fields (see account_view). Matching that keeps clients simple.
Security issue!!This logs the OTP. Logs reach support tools and backups. Log from, to and amount only.
LGTM (on 900 lines, in two minutes)Read the ledger change closely, skimmed the tests. Did not check the migration: who should?

Labels, questions and praise

Comments, and being reviewed

A label tells the author what each comment costs them. Without one, every comment reads as blocking.

LabelMeansAuthor must
blocking:Wrong, unsafe or breakingFix, or convince me
suggestion:I think this is betterConsider, then decide
question:I do not understand yetAnswer, ideally in the code
nit:Small taste pointNothing. Free to ignore.
praise:This is good, and whyNothing
SituationUseExample
You might be missing contextA real questionWhat happens if the credit fails after the debit?
You know it is a bugA plain statement with evidenceThis loses 5000 when the target is unknown: script attached.
You know, but ask anywayDo not. A quiz reads as a trap.Are you sure this is atomic?
Something is done wellSpecific praisepraise: testing the failed credit pins the behaviour that matters most.

Praise: "nice work" teaches nothing. Naming the choice and its effect tells the author what to repeat.

When to take it offline

Comments, and being reviewed

Text is slow for disagreement and bad at tone. Move to a call early, then write the outcome back on the pull request.

Three reasons to talk. The decision still gets written down.

A pull request that is easy to review

Comments, and being reviewed

The author controls review quality more than the reviewer does: one purpose, small, and a description that says why. Clean commits help, see Git in Depth.

Changed linesWhat the review is usually like
Under 100Read fully, in minutes, same day
100 to 400One careful sitting. A good upper target.
400 to 1000Skimmed. Comments drift to names and style.
Over 1000"LGTM". Split it, unless it is generated or a pure rename.
  • These numbers are rules of thumb, not measurements.
  • Review your own diff first, and comment on the lines you are unsure about.
  • Keep refactoring and behaviour change in separate pull requests.

Responding, and pushing back

Comments, and being reviewed

A comment is about the code, and the reviewer is spending time to make your change better. Answer every thread, even with one word.

The comment isRespond with
Right"Done" and the commit. No defence needed.
Right, but large"Agreed. Filed BANK-140, out of scope here because ..."
Unclear"Do you mean X or Y?" before changing anything
A matter of tasteTake it if it is cheap. Save disagreement for what matters.
Wrong, in your viewEvidence: a test, a measurement, a link to the decision
  • Push back on correctness, scope and cost. Give way on taste.
  • Push fixes as new commits during review, so the reviewer can see what changed.
  • Two rounds with no agreement: ask a third person, or follow the team's written standard.

Process, and reviewing as a senior

Part 4 of 6 · team choices, anti-patterns, the senior's extra duties

Process choices

Process, and reviewing as a senior

Each row is a team decision. Write the answer down once so it is not argued per pull request.

ChoiceCommon defaultTrade-off
TurnaroundFirst response within one working day, sooner for small changesFast review interrupts the reviewer. Slow review makes authors batch, so pull requests grow.
One reviewer or twoOne. Two for money paths, auth, migrations, public APIs.Two can mean each assumes the other looked
Code ownersA file maps paths to owning teams, who are asked automaticallyRight eyes on risky paths. Owners become a queue if the group is small.
Approve with commentsAllowed when nothing is blockingSaves a round trip. Relies on the author to act on the comments.
Stacked pull requestsFor a large change: a chain of small ones, each reviewable aloneSmall reviews. Rebasing the chain needs care or tooling.
Pairing insteadCounts as review for small or urgent changes, noted on the pull requestFastest feedback. No fresh pair of eyes, less written record.

What to automate

Process, and reviewing as a senior

Anything a tool can decide should never appear in a human comment. The Python tools are covered in Code Quality.

AutomateEnds the argument aboutSeen above
FormatterQuotes, line length, blank lines
LinterUnused code, mutable defaults, bare except5 (B006), 4 (S110), 6 (B015)
Type checkerWrong argument types, None not handled
Tests in CI"Did you run it?"Passed on all eight
Security scansVulnerable packages, committed secrets
PR template, size warningMissing "why", oversized changes

Limit: the tests passed on all eight diffs in Part 2. Tools remove noise, they do not replace the reader.

Review anti-patterns

Process, and reviewing as a senior

Anti-patternLooks likeFix
Rubber stampApproval in a minute, no comments, large diffSmaller pull requests. Say what you did and did not read.
Nitpick stormThirty comments, all names and spacing, bug missedAutomate style, label nits, cap them at a few
Design debate at the end"I would have built this differently" on finished workDesign review or a draft pull request before the code
Review as ambushComments drip in over days, new demands each roundOne complete pass, all blocking points in round one
The silent queuePull requests wait days, nobody owns themA turnaround rule and a visible queue
The single gatekeeperEverything waits for one seniorSpread review. The senior takes the risky paths only.

What a senior adds

Process, and reviewing as a senior

Anyone can check the lines in the diff. The senior's part is what the diff does not show.

DutyQuestionExample from Part 2
Design before codeWas the approach agreed before 600 lines were written?The nested balance shape in review 7
The missing pieceWhat should be in this diff and is not?No failed-transfer test in 2, no callers in 7
ConsistencyDoes this match how the codebase already does it?_post inside one with conn:, as transfer had
OperationsWho is paged, and what will they see?Silent failures in 4
The author's ownershipAm I improving their solution, or replacing it with mine?Suggest the direction, let them write it

Often missing from a diff: the failure-path test, the migration and its reverse, the callers, a log line or alert for the new failure, the rollback step, the docs.

Approving imperfect code

Process, and reviewing as a senior

The bar is "better than before and safe", not "how I would have written it". Holding out for perfect costs more than it saves.

Three questions. Schemas, public APIs and stored data are the hard-to-change cases.
  • Approve the missing paging in review 3 with a ticket. Block the N + 1.
  • A follow-up with no ticket and no owner is not a follow-up.

Mentoring

Part 5 of 6 · growing one engineer

Mentor, coach, sponsor

Mentoring

Three different jobs. A senior engineer does all three, and should know which one a moment needs.

MentorCoachSponsor
DoesShares experience and adviceAsks questions until they find the answerUses own credit to get them opportunities
Says"Here is what I did when ...""What options do you see?""She should lead this project."
Best whenThey lack knowledgeThey have the knowledge, not the confidenceThey are ready and not yet visible
RiskThey copy youSlow when they truly do not knowYour name is on the outcome

Stages of independence

Mentoring

The stage is per skill, not per person. Someone can work alone on API handlers and still need you beside them for a migration.

Move right one step at a time, and step back left when the task is new.
StageYour review looks like
I do, you watchThey review your pull request, and you explain your choices in it
We do togetherPair on the change. Review is a formality.
You do, I watchFull review, every level, with the reasons written out
You do aloneBlocking points and design only. Sometimes they review you.
Teaching through reviewInstead of
Name the problem and the evidencePasting the corrected code
Point at an example already in the codebaseDescribing your preferred version
Give the principle once, with a linkRepeating the same comment in six places
Let a harmless imperfection throughPushing your own commit onto their branch

Giving hard feedback

Mentoring

Situation, behaviour, impact: say when it happened, what you observed, and what it caused. Then ask, and listen.

DoAvoid
One event, with a date"You always", "you never"
What a camera would have recordedGuessed motives: "you don't care about quality"
Private, within daysIn a review thread, or saved for the yearly review
End with one agreed next stepA praise sandwich that hides the message

Running a one-to-one

Mentoring

Thirty minutes, every week or two, and it is their meeting. Status updates belong in the stand-up.

MinutesItemQuestion
0 to 10Their topics"What is on your mind?"
10 to 20Stuck points"What is slowing you down? What have you tried?"
20 to 25Feedback, both ways"One thing that went well, one thing I could do differently."
25 to 30Growth, next step"What do you want to be trusted with next?"
Is the mentoring working?Sign
Review rounds per pull requestGoing down for the same kind of change
Kind of comments they receiveMoving from correctness to design
Their own reviewsThey find real bugs in other people's code
Scope they ownFunction, then feature, then service
Questions they askFrom "how do I" to "should we"

Caution: these are trends to watch over months. Used as targets, each of them can be gamed.

Delegating a stretch task

Mentoring

A stretch task is one they cannot yet do alone. Make it safe to attempt by fixing the scope, the checkpoints and the net before they start.

You hold the net, they hold the work. Early checkpoints are cheap, late ones are rescues.
PartExample: "add daily transfer limits"
ScopeDaily limit per account. Not per customer, no admin override. Two weeks.
Checkpoint 1A one-page plan after two days: schema, where the check runs, the race between two transfers
Checkpoint 2First pull request: the check behind a flag, with boundary tests
Safety netFeature flag off by default, your review on the money path, a rollback step
DoneThey demo it and answer the questions. Credit goes to them by name.

Trap: taking the task back at the first wobble. Ask what they would do next, and tighten the checkpoints instead.

Raising a team, and the cheat sheet

Part 6 of 6 · onboarding, standards, checklists, interview answers

The first 90 days

Raising a team, and the cheat sheet

A written plan with one named buddy. The new engineer should ship something small in the first week.

Each month has one aim and one visible result.
DaysThey doYou doResult
1 to 30Set up, read the service map, fix small bugs, review as an observerBuddy daily, pick starter tasks, explain every review commentFirst change in production in week one
31 to 60A small feature end to end, shadow on-call, review others' codeReview at the "you do, I watch" stage, weekly one-to-oneA feature shipped with its tests and its dashboard
61 to 90Own one area, join on-call, write or fix one guideStep back to design-level review, ask for their feedback on onboardingThey answer questions about their area

Loop: every new joiner fixes the setup guide where it failed them. The guide stays true without anyone owning the chore.

Standards and knowledge sharing

Raising a team, and the cheat sheet

A standard is a decision the team made once so that reviews do not remake it. If it is not written down or enforced by a tool, it is one person's opinion.

  • Trigger: the same review comment appears a third time.
  • Decide: a short written proposal, a fixed week for comments, one named decider.
  • Enforce: a lint rule or template if possible, a line in the guide if not. Anyone may reopen it with new evidence.
FormatGood forCost
Brown bag talkAwareness of a tool, an incident, a techniqueAn hour for everyone. Forgotten unless recorded.
Design reviewSpreading context before code existsNeeds a written document first
PairingPassing on habits that are hard to write downTwo people, one task
Written guideAnything asked more than twiceGoes stale without an owner
Code reviewDaily, in context, at no extra meetingOnly reaches the two people involved

The multiplier: a senior's output is the team's output with them in it, minus the team's output without them.

Reviewer and author checklists

Raising a team, and the cheat sheet

Reviewer, in orderFrom
Read the description first. Is it the right problem?Order
Is the design sound, and consistent with the codebase?Senior
Boundaries: under, on and over each limit1
Several writes: one transaction? What if step two fails?2
Queries or calls inside loops3
Every except: what is caught, logged, reported?4
Mutable defaults, module-level state, shared objects5
Would each test fail if the code broke?6
Changed shapes, signatures, defaults: who calls this?7
What is logged? Any secret or personal data?8
What is missing from the diff?Senior
Label every comment. Attach evidence to every blocker.Labels
Better than before, safe, rest is a follow-up: approve.Approve
Author, before asking for review
One purpose. Refactors and behaviour changes are separate.
Under about 400 changed lines, or split and stacked
Description has why, what, not in scope, how to test, risk
CI is green: format, lint, types, tests
Tests cover the failure path and the boundary
You read your own diff and commented on the doubtful lines
Callers, clients, migration and rollback are accounted for
Every review thread gets an answer

Interview questions

Raising a team, and the cheat sheet

Each answer is a shape to fill with your own story. Name a real change, what you did and what happened next.

QuestionShape of a good answer
How do you review code?Top down: problem, design, correctness, tests, operability, readability. Style is the tools' job. Blockers come with evidence.
Tell me about a time you disagreed in a review.The technical point, the evidence each side had, moving to a call, the written outcome. Include a time you were the one who was wrong.
What do you look for that juniors miss?What is not in the diff: callers, failure path, migration, rollback, monitoring.
A pull request of 2,000 lines arrives. What do you do?Ask for a split or a walkthrough, review design first, state what you did not read. Then fix the cause: earlier design review, stacking.
When do you approve code you would have written differently?When it is better than before, safe, and the rest is easy to change later. Different is not wrong.
How do you mentor a junior engineer?Find the stage per skill, give a scoped stretch task with checkpoints and a net, review to teach, step back on purpose. Give one result.
How do you handle someone who keeps making the same mistake?Private, specific, soon: situation, behaviour, impact. Then ask why. Often the fix is a missing tool, guide or test.
How do you raise the quality bar of a team?Automate the arguable, write down the decided, keep pull requests small, review fast, and model it in your own pull requests.

Back to Senior Skills.