Code Review & Engineering Standards
- Review a change in priority order — correctness, design, security, observability, tests — instead of starting with style
- Apply a payment-specific checklist: money types, idempotency, concurrency, PSP outcomes, PCI DSS, migrations
- Give feedback that is clear about severity and easy to act on, and receive feedback without friction
- Set engineering standards that automate the mechanical parts of review (linters, commit conventions, templates, CODEOWNERS)
- Describe how an architect contributes to reviews at scale without becoming a bottleneck
TL;DR
- Review for risk first: correctness, money movement, security and failure handling; then design fit; then tests and observability; style last — and automate style away.
- The standard (from Google's engineering practices): approve when the change improves overall code health, even if it is not how you would have written it.
- In payment code, the recurring blockers are:
float64money, check-then-act races on balances, missing idempotency, treating a PSP timeout as failure, and card data or PII in logs. - Label every comment's severity (
issue (blocking),suggestion,nitpick) and explain the why. - Small PRs get better reviews. Separate refactors from behavior changes; merge incomplete features dark behind flags.
- Standards as code:
golangci-lintin CI, conventional commits, a PR template with risk and rollback sections, ADR links, CODEOWNERS and branch protection. - The architect reviews designs before code (RFCs, ADRs), owns the cross-cutting boundaries (APIs, events, schemas), and scales through standards and mentoring — not by approving every PR.
Why it matters
Code review is the last human checkpoint before code that moves money reaches production. In banks it is often a control: change-management policies typically require that someone other than the author approves every production change (maker-checker, four-eyes), and the PR history is the audit evidence. In e-commerce, a single unreviewed change to inventory reservation or promotion logic can oversell a flash sale or give away margin in minutes.
Review is also how a team shares knowledge and converges on a style of design. A team that reviews well has fewer "only Minh understands the settlement job" situations. As an architect, the quality bar your teams apply in reviews is the architecture that actually gets built.
Core concepts
What review is for — and what it is not for
| For | Not for |
|---|---|
| Finding defects and risks the author missed | Formatting and import order (gofmt, goimports) |
| Checking the change fits the design and its boundaries | Re-litigating an agreed design (that belongs in the RFC/ADR) |
| Spreading knowledge of the codebase and the domain | Personal style preferences presented as requirements |
| Keeping standards consistent across the team | Gatekeeping or demonstrating seniority |
What to look for, in priority order
| Area | Questions to ask |
|---|---|
| Correctness | Does it do what the description says? Edge cases: zero, negative, max, empty, duplicates, concurrent calls? What happens on every error path? |
| Design | Right place and layer? Does domain code import infrastructure? Is a new abstraction justified? Does it fit existing patterns? |
| Security | Input validation, authorization (can user A act on account B?), injection, secrets, sensitive data in logs or errors? |
| Failure handling | Timeouts on every outbound call? Retries safe (idempotent)? Partial failure between steps? |
| Observability | Can on-call tell what happened from logs, metrics and traces? Correlation IDs propagated? Errors logged once with context? |
| Tests | Do tests cover the risky paths, not just the happy path? Would they fail if the code were wrong? |
| Data and contracts | Backward-compatible migrations, API and event changes? Rollback possible? |
| Readability | Names in domain language, functions at one level of abstraction, comments explaining why |
| Performance | Only where relevant: N+1 queries, unbounded loops or goroutines, missing indexes, hot-path allocations |
A useful reading order: the PR description and linked ticket or ADR first, then the tests (they show intent), then the core logic, then the wiring. Also review what is not in the diff: the missing migration rollback, the missing test for the decline path, the config that was not added for production.
Review checklist for payment code
Keep a version of this in the repository (for example docs/review-checklist.md) and link it from the PR template.
Money
- Amounts use a money type (integer minor units or decimal) with currency — never
float64, never a bareint64without currency. - Rounding mode and point of rounding are explicit and match the agreed rule; allocation (splits, installments, partial refunds) preserves totals.
- Currency mismatches are rejected, not silently converted.
Idempotency and retries
- Every mutating API and consumer is idempotent on a key (idempotency key, event ID), enforced by a unique constraint, not only by an in-memory check.
- Retries reuse the same idempotency key toward the PSP; retry loops have backoff and a cap.
Concurrency and transactions
- No check-then-act on balances or stock outside a lock or atomic statement (
SELECT ... FOR UPDATE, conditionalUPDATE ... WHERE balance >= $1, or optimistic versioning). - Transaction boundaries are correct and short; no network calls inside a transaction; lock ordering avoids deadlocks.
External calls (PSPs, banks, partners)
- Timeouts set; a timeout or unknown status is treated as unknown outcome (pending + reconciliation), never as failure or success.
- Webhooks are authenticated (signature check) and handled idempotently; out-of-order delivery is safe.
State and audit
- State changes go through the state machine; invalid transitions are rejected.
- Every balance change has a ledger or audit entry; who/what/when is recorded.
Security and compliance
- No PAN, CVV, full account numbers, passwords, tokens or unnecessary PII in logs, errors, metrics labels or traces (PCI DSS and data-protection obligations).
- Authorization checks on every resource ID taken from the request (no IDOR); inputs validated; parameterized SQL; secrets from the secret manager, not config files.
Data, rollout, operations
- Migrations are backward-compatible (expand/contract) and safe on large tables; rollback path documented.
- Risky behavior is behind a feature flag; metrics and alerts exist for the new path; runbook updated if on-call behavior changes.
A review in practice
A change arrives for a wallet withdrawal:
func (s *Service) Withdraw(ctx context.Context, walletID string, amount float64) error {
w, err := s.repo.Get(ctx, walletID)
if err != nil {
return err
}
if w.Balance < amount {
return errors.New("insufficient funds")
}
w.Balance -= amount
log.Printf("withdraw %v from wallet %s card %s", amount, walletID, w.CardNumber)
return s.repo.Save(ctx, w)
}
Review comments, using the Conventional Comments format:
- issue (blocking):
amount float64— money must usemoney.Money(minor units + currency). Float rounding will produce off-by-one-cent balances. - issue (blocking): check-then-act race. Two concurrent withdrawals can both read balance 100, both pass the check, and both debit. Make the check and the debit one atomic statement, or lock the row.
- issue (blocking, security): the full card number is logged. That puts PAN in our log pipeline (PCI DSS scope). Log the wallet ID and a transaction ID only.
- issue (blocking): no idempotency key — a mobile client retrying after a timeout withdraws twice.
- question: where is the ledger entry for this withdrawal? A balance change without a journal entry cannot be reconciled.
- suggestion (non-blocking): return a sentinel
ErrInsufficientFundsso the handler can map it to 422, and wrap other errors with context. - question: is the caller authorized for
walletID? If that check lives in the handler, a comment pointing to it would help reviewers.
A version that addresses them:
// Withdraw debits the wallet if funds suffice and records a journal entry.
// It is idempotent on cmd.IdempotencyKey (unique index on wallet_txns).
func (s *Service) Withdraw(ctx context.Context, cmd WithdrawCmd) (TxnID, error) {
var id TxnID
err := s.uow.Do(ctx, func(tx Tx) error {
existing, found, err := tx.Txns().ByIdempotencyKey(ctx, cmd.IdempotencyKey)
if err != nil {
return fmt.Errorf("check idempotency key: %w", err)
}
if found {
id = existing.ID
return nil
}
// The balance check and the debit are one atomic statement, so
// concurrent withdrawals cannot both pass the check.
debited, err := tx.Wallets().DebitIfSufficient(ctx, cmd.WalletID, cmd.Amount)
if err != nil {
return fmt.Errorf("debit wallet %s: %w", cmd.WalletID, err)
}
if !debited {
return ErrInsufficientFunds
}
txn, err := tx.Txns().RecordWithdrawal(ctx, cmd) // journal entry + idempotency key
if err != nil {
return fmt.Errorf("record withdrawal: %w", err)
}
id = txn.ID
return nil
})
return id, err
}
-- DebitIfSufficient: 1 row affected = debited; 0 rows = insufficient funds
-- (or a wallet/currency mismatch, which the caller distinguishes beforehand).
UPDATE wallets
SET balance_minor = balance_minor - $2,
version = version + 1
WHERE id = $1
AND currency = $3
AND balance_minor >= $2;
The point of the example: none of the blocking issues would be caught by a linter or by a reviewer who starts with naming and formatting.
Giving feedback
Conventional Comments gives each comment a label and optional decorations, so the author knows what must change:
| Label | Meaning |
|---|---|
issue (blocking) | Must be fixed before merge: bug, risk, standard violation |
suggestion | A concrete improvement; say whether it is blocking |
question | You do not understand something — maybe a bug, maybe missing context |
nitpick | Trivial and non-blocking; if it recurs, automate it |
thought | An idea for later; not a request for change |
praise | Something done well, specifically — it teaches as much as criticism |
| Instead of | Write |
|---|---|
| "This is wrong." | "issue (blocking): two concurrent calls can both pass this check — can we make it a conditional UPDATE?" |
| "Why didn't you use the outbox?" | "question: if the publish fails after commit, how is the event recovered? The outbox pattern would cover that." |
| "Rename this." | "nitpick: amt → refundAmount would match the rest of the package." |
| Twenty style comments | Fix the linter config once, then link to it |
Habits that make reviews faster and kinder: comment on the code, not the person ("this function", not "you"); explain the reason and, where possible, offer an alternative; ask when unsure instead of asserting; respond within a business day (sooner for small PRs); and if a thread goes past two rounds, switch to a call and write the outcome back into the PR.
Receiving feedback
- Assume good intent; the reviewer is spending time to make your change safer.
- Answer every comment — fixed, explained, or deferred to a linked ticket. Do not silently resolve.
- Push back with evidence (a test, a benchmark, an ADR), not seniority.
- Keep scope: valuable but unrelated suggestions become follow-up tickets, not PR growth.
- If the same debate keeps recurring across PRs, it is a missing standard — propose a linter rule or style-guide entry.
PR size and shape
Large diffs get shallow reviews: past a few hundred changed lines, reviewers skim. An often-cited heuristic from industry studies of code inspection is to review no more than a few hundred lines at a time; treat it as a rough guide, not a law. Techniques to keep PRs small:
- Separate refactoring from behavior change (see Code Smells & Refactoring).
- Stack PRs: migration first, then repository, then use case, then API — each reviewable and mergeable.
- Merge dark behind feature flags so incomplete features do not need long-lived branches.
- Isolate generated and vendored code so reviewers can skip it safely.
- Write the description for the reviewer: what, why, risk, how tested, rollout and rollback.
Engineering standards
Standards turn recurring review comments into automation and templates, so humans can spend their attention on design and risk.
Linting with golangci-lint. One shared configuration, run locally, in pre-commit and as a required CI check:
# .golangci.yml (golangci-lint v2 configuration format)
version: "2"
linters:
default: standard # errcheck, govet, ineffassign, staticcheck, unused
enable:
- bodyclose # unclosed HTTP response bodies
- errorlint # errors.Is/As instead of == and type switches
- gosec # security: SQL string building, weak crypto, file perms
- noctx # HTTP requests without a context
- rowserrcheck # unchecked rows.Err()
- sqlclosecheck # unclosed sql.Rows and sql.Stmt
- revive # naming, doc comments, style
- gocognit # cognitive complexity
- misspell
settings:
gocognit:
min-complexity: 20
exclusions:
rules:
- path: _test\.go
linters:
- gosec
formatters:
enable:
- gofumpt
- goimports
issues:
new-from-rev: origin/main # on legacy code, lint only what changed
Option names differ between golangci-lint v1 and v2; check the version your team runs. Add govulncheck (known-vulnerable dependencies) and a secret scanner as separate CI steps.
Conventional commits. A commit format that makes history readable and enables automated changelogs and semantic versioning:
feat(payments): require idempotency key on refund API
Refunds retried by the mobile app after a timeout could execute twice.
POST /refunds now requires an Idempotency-Key header; a duplicate key
returns the original refund.
Refs: PAY-1423
ADR: docs/adr/0042-idempotency-keys.md
fix(ledger): round FX conversions half-even per ADR-0031
refactor(checkout): extract pricing into pure Quote function
feat(api)!: remove deprecated /v1/checkout endpoint
BREAKING CHANGE: clients must call /v2/checkout.
Types such as feat, fix, refactor, perf, test, docs, chore also make reviews easier: a refactor: commit claims no behavior change, and the reviewer can hold it to that.
PR template with ADR links. Significant design decisions are recorded as ADRs before or alongside the code; the PR links them so reviewers check the implementation against the decision rather than reopening it (see Documenting Architecture).
## What and why
One paragraph. Ticket: PAY-1423. ADR: docs/adr/0042-idempotency-keys.md
## Risk
- [ ] Moves money or changes balances, ledger or fees
- [ ] Changes a public API, event schema or database schema
- [ ] Security-sensitive: auth, PII, card data, secrets
## How it was tested
Unit / integration / contract tests added; manual checks with evidence.
## Rollout and rollback
Feature flag name, migration order, how to roll back safely.
Ownership and protection. CODEOWNERS routes reviews to the people who own the risk; branch protection makes the rules non-optional.
# .github/CODEOWNERS
/internal/ledger/ @acme/ledger-owners
/internal/payments/ @acme/payments-owners @acme/security-champions
/migrations/ @acme/db-reviewers
/api/ @acme/api-guild
Typical protection for money paths: no direct pushes to main, required status checks, at least one approval from a code owner who is not the author (two for ledger or payment-core changes in many banks), dismissal of approvals on new commits, and signed commits where policy requires them.
The architect's role in reviews
- Review designs before code. Catching a wrong boundary in a 2-page RFC costs an hour; catching it in a 2,000-line PR costs a sprint and goodwill. Push teams to write short RFCs/ADRs for anything that is a one-way door.
- Own the boundaries, not every line. Be a reviewer (or delegate) on public APIs, event schemas, database migrations, cross-service dependencies and security-sensitive code. Do not be a required approver on every PR — that makes you the bottleneck and teaches teams to wait.
- Scale through standards. Linter configuration, PR templates, checklists, golden-path service templates, and example PRs that show what "good" looks like.
- Calibrate and coach. Periodically sample merged PRs across teams: are reviewers catching what matters? Pair-review with newer reviewers. Feed incident postmortems back into the checklist (a double-charge incident should add a line about idempotency keys).
- Know when to veto. Most design feedback should be non-blocking guidance. Reserve blocking for one-way doors: data-model decisions, public contracts, security and money-correctness issues. See The Role of a Solution/System Architect.
Trade-offs
| Practice | Strengths | Weaknesses | Choose when |
|---|---|---|---|
| Pre-merge asynchronous review | Audit trail; knowledge sharing; catches defects | Waiting time; context switching | Default; required for regulated and money-moving code |
| Pair or mob programming | Continuous review; fast feedback; strong knowledge transfer | Costly per hour; weaker written trail unless a PR is still opened | Complex or high-risk changes; onboarding |
| Ship / Show / Ask | Matches review effort to risk | Needs strong CI and trust; may not satisfy regulatory controls | Low-risk changes in mature teams; not for payment paths in banks |
| Architect approves every PR | Consistency in the short term | Bottleneck; disempowers teams | Almost never — only for one-way-door changes |
| Automation only (linters, bots) | Fast, consistent, tireless | Cannot judge intent or design | Formatting, simple bug patterns, dependency updates |
In practice
- Budget review time. Treat reviews as real work: many teams aim for a first response within a few working hours and expect each engineer to spend a meaningful slice of every day reviewing.
- Measure flow, not people. Track time to first review, PR cycle time and PR size distribution (they feed DORA lead time). Never use comment counts or "bugs found in review" as individual performance metrics — they distort behavior.
- Make severity explicit. "Approve with comments" for non-blocking suggestions keeps changes moving; "request changes" only for issues.
- Review generated code by its generator. For protobuf, sqlc or mocks, review the source definition and confirm the generated output was regenerated, rather than reading thousands of generated lines.
- Close the loop. When a production incident passes review, ask in the postmortem what review could reasonably have caught and update the checklist or linters — not who approved it.
Common pitfalls
- Rubber-stamping. "LGTM" two minutes after a 1,500-line PR is opened. Symptom: review exists on paper but catches nothing; auditors may eventually notice.
- Nit storms. Thirty style comments and no comment on the race condition. Symptom: authors dread reviews; real risks slip through.
- Design debates at PR time. Symptom: PRs open for weeks; the design should have been agreed in an RFC/ADR.
- Reviewing only the diff. Missing what is absent: tests for failure paths, rollback for a migration, alerts for a new job.
- Long-lived PRs. Symptom: merge conflicts, stale approvals, big-bang merges before a release.
- Inconsistent standards. Each reviewer enforces personal preferences. Symptom: authors "shop" for lenient reviewers; codebase style drifts.
- Security-sensitive changes approved by non-owners. Symptom: PAN in logs or a missing authorization check discovered in a pentest or an incident.
Interview angle
- Prompts: "How do you run code reviews on your team?", "What do you look for first?", "Tell me about a disagreement in a code review", "As an architect, how do you keep quality consistent across ten teams?"
- A strong answer gives a priority order (correctness and risk before style), a concrete domain checklist (money types, idempotency, concurrency, PSP unknown outcomes, PCI DSS logging), explicit severity labels, PR-size discipline, automation of the mechanical parts, and an architect role focused on design reviews, boundaries and standards. Behavioral versions want a STAR story: a disagreement resolved with evidence, or a review that caught a serious defect (see Behavioral Stories).
- Expected follow-ups: "How do you handle a senior engineer who ignores review comments?", "How do you keep reviews fast?", "What do you automate?", "How do reviews satisfy audit requirements in a bank?"
- Red flags: style-first reviewing, "I approve everything myself", treating review as gatekeeping, no notion of blocking vs non-blocking, or no awareness of compliance-driven review controls in financial services.
Self-check
1. In what order do you review a PR, and why does style come last?
Read the description, ticket and ADR, then tests, then core logic, then wiring. Evaluate correctness and risk (money, concurrency, failure handling, security) first, then design fit, then tests and observability, then readability. Style comes last because it is the least risky and the most automatable — a linter should have already handled it, leaving human attention for what tools cannot judge.
2. List five blocking issues you would look for in a payment-related PR.
- Money as
float64or without currency. - Check-then-act on balances or stock without a lock or atomic statement.
- Mutating endpoint or consumer without idempotency (no unique key).
- PSP timeout or unknown status treated as failure or success instead of pending plus reconciliation.
- Card data, credentials or unnecessary PII in logs, errors or traces; missing authorization on a resource ID.
3. Why is "the change improves overall code health" a better approval standard than "the code is perfect"?
Perfect is unattainable and subjective; demanding it stalls delivery and pushes authors toward huge, infrequent PRs. Approving changes that make the codebase better, while flagging non-blocking improvements, keeps flow high and quality rising over time. Blocking is reserved for real defects, risks and standard violations.
4. How do Conventional Comments labels improve reviews?
They make severity and intent explicit — issue (blocking) vs suggestion vs nitpick vs question — so the author knows what must change before merge and what is optional. This reduces misunderstandings, unnecessary back-and-forth and the feeling of being blocked by preferences.
5. What should an architect review personally, and what should they delegate?
Personally: designs (RFCs, ADRs) before implementation, public API and event-schema changes, cross-service dependencies, data-model and migration strategy, and security- or money-critical boundaries. Delegate line-level review to code owners in each team, and scale quality through linters, templates, checklists, golden-path repositories and coaching — sampling merged PRs to calibrate rather than approving every one.
6. Scenario: a 1,800-line PR adds a new PSP integration, refactors the payment service and changes the refund rounding rule. How do you respond?
Ask the author to split it: (1) the pure refactor, behavior unchanged, tests green; (2) the rounding change as its own small PR, with finance sign-off and updated tests; (3) the new PSP adapter behind a feature flag, possibly stacked as migration, adapter and wiring. Offer to pair on the split. Each part then gets a meaningful review, and the rounding change cannot hide inside the refactor.
7. How does code review serve as a control in a regulated bank?
Change-management policies typically require that a person other than the author approves each production change (maker-checker), that approvals are recorded, and that security-sensitive areas are reviewed by designated owners. Branch protection, CODEOWNERS, required checks and the PR history together provide the evidence auditors ask for.
Exercise
Set up review standards for a payments repository and practice a review:
- Write
.golangci.yml(the configuration above is a starting point), addgovulncheckand a secret scanner to CI, and make them required checks. - Add a PR template with risk, testing and rollout sections, and a
docs/review-checklist.mdtailored to your domain (start from the payment checklist above). - Add CODEOWNERS for ledger, payments, migrations and API definitions, and branch protection requiring a code-owner approval.
- Review the original
Withdrawfunction from this page without looking at the comments above: write at least six comments using Conventional Comments labels, then compare with the list. - Write three example commit messages in conventional-commit form for a feature, a fix and a breaking change.
Done when: a PR that introduces float64 money, logs a card number or drops a rows.Err() check fails CI or is caught by the checklist; your review of Withdraw identified the race, the float, the PAN logging and the missing idempotency; and a teammate unfamiliar with the repository can open a compliant PR using only the template and checklist.
Further reading
- Google Engineering Practices: Code Review — the reviewer's and author's guides, including the "code health" standard.
- Titus Winters, Tom Manshreck, Hyrum Wright (eds.), Software Engineering at Google (2020) — chapter on code review.
- Conventional Comments
- Conventional Commits
- golangci-lint documentation
- Go Code Review Comments
- Michael Nygard, "Documenting Architecture Decisions" (blog post, 2011) — the original ADR format.
- Rouan Wilsenach, "Ship / Show / Ask" (martinfowler.com, 2021).
- OWASP Code Review Guide — security-focused review techniques.
- PCI Security Standards Council, PCI DSS — requirements on protecting stored and logged cardholder data.
Related
- Clean Code Principles — what good code looks like to a reviewer.
- Code Smells & Refactoring — smells to flag and how to split PRs.
- Testing Strategy — judging whether tests are adequate.
- Documenting Architecture: C4, ADRs, arc42 — ADRs linked from PRs.
- The Role of a Solution/System Architect — influence without gatekeeping.
- Security for Architects — the security lens in reviews.
- Compliance: PCI DSS, KYC/AML, Data Protection — why some review rules are non-negotiable.
- Locking & Concurrency Control — fixing check-then-act races.
- Behavioral Stories (STAR) for Architects — review stories for behavioral rounds.
Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).