Skip to content
notes.vinhnq.com

Search

Git, DevOps & ToolingSenior20 min read

Code review: resolving disagreements and two worked reviews of real code

Review 11 cards
On this page

Code review series: 1. Goals, process and writing comments · 2. Resolving disagreements and worked reviews

Part 1 covered goals, a checklist, the process and labelled comments (TODO blocks the merge; NIT, OPTIONAL and FYI don’t). This post answers two harder questions: what to do when reviewer and author disagree, and what a real review looks like. The two worked reviews use code from the course (a homestay booking flow in Spring Boot 3, a Redis distributed lock); for recording decisions see ADRs and quality requirements.

At a glance:

flowchart TD
  A[Listen and restate] --> B[Write pros and cons]
  B --> C[Establish context]
  C --> D["Measure / PoC"]
  D --> E["Take to team, escalate"]
  E --> F["Disagree and commit + ADR"]
  R["2 rounds on one point"] -->|talk 15 minutes| G[Record outcome in MR]
  L["Little: threads = rate × wait"] --> TO["Business timeout per SLA"]
  TO --> FO{"Fail-open or fail-closed?"}

1. Resolving disagreements

Key idea: disagreement is normal; you need a process that moves from opinions to facts, then to a decision the whole team follows. The steps are the course’s, with concrete practices added.

  1. Listen to both sides. Each side summarises the other’s argument until the other says “yes, that’s my point”.
  2. Analyse pros and cons of each option, in writing, not just out loud.
  3. Establish the context: which qualities is the team prioritising right now (deadline, reliability, cost, maintainability)? The same choice can be right in one project and wrong in another.
  4. Pick the option that fits the context, not the “most elegant” one.
  5. Build a PoC or measure when the argument hinges on an assumption you can test (performance, complexity). A PoC (proof of concept) is a small prototype that tests an assumption.
  6. Take it to the team, then escalate if needed: the tech lead or solution architect, then the head of engineering.
  7. Disagree and commit: once decided, the person who disagreed still executes it fully, and the decision is recorded as an ADR (Architecture Decision Record, a short document stating a decision and why) with its reasons and the conditions for revisiting it.

A pragmatic rule: after two rounds of back-and-forth on the same point, switch to a 15-minute conversation, then write the conclusion back on the MR for future readers.

Case study: waiting up to 5 minutes for a fraud check

Key idea: a synchronous endpoint that waits up to 5 minutes drains the whole service’s threads at under one request per second. Measure with Little’s law instead of arguing, then split out a 2–3 second business timeout that fails closed.

A PR in an e-wallet service adds a synchronous payment endpoint: the service sends a command over Kafka to the fraud-detection service, then waits for the result by polling Redis repeatedly (sleeping between polls, with growing intervals) until a result arrives or time runs out. The maximum wait comes from the Redis timeout setting, currently 300,000 ms.

  • Reviewer (TODO): one request can hold a Tomcat thread for up to 5 minutes.
  • Author: the fraud service is sometimes slow, and the business needs an answer before replying to the customer.

Walking through the steps:

  • Context: this endpoint is on the user’s payment path, with a p99 target under 2 seconds; the current priority is “never approve a fraudulent transaction” over “always answer fast”.
  • Measure instead of arguing: Little’s law says work in progress = arrival rate × time in the system; here, busy threads = request rate × time each request holds a thread. Tomcat has 200 worker threads by default; if the fraud service is slow and each request waits 5 seconds, just 40 requests per second exhausts all 200 threads, and every other endpoint of the service (health checks included) starts timing out. With a 5-minute wait, less than one request per second is enough. A short load test on staging showed exactly that.
  • Options: (a) a separate business timeout of 2–3 seconds, returning PENDING_REVIEW on expiry (fail-closed: don’t approve when unsure); (b) make the API asynchronous: return 202 Accepted with an id, and the client polls for status or receives a webhook; (c) use Spring’s ReplyingKafkaTemplate instead of hand-rolled Redis polling; (d) call the fraud service over plain HTTP if it truly must be synchronous.
  • Decision: (a) in this PR, (b) as the follow-up; record an ADR “Fraud-check timeout and behaviour on expiry” with the numbers, the reason for fail-closed, and the condition for revisiting it (e.g. when the fraud service’s p99 drops below 300 ms). The full ADR is in Exercise 2.

2. Worked review 1: the v2 booking flow

Key idea: the six merge-blocking issues (TODO) sit where the code seems to work: dependencies never injected, retries creating duplicate bookings, side effects before the commit, a checked exception that still commits, unordered row locks, and “today” in the JVM’s time zone.

Code from the sample homestay booking project (Spring Boot 3, PostgreSQL), the version that uses Template Method (the pattern itself is analysed in Template Method and composition). I only quote the lines the comments need.

// BookingV2Controller
@RestController
@RequiredArgsConstructor
public class BookingV2Controller {
    private BookingFactory bookingFactory;
// BookingFactory
@Service
@RequiredArgsConstructor
public class BookingFactory {   // Abstract Factory
    private final VillaBookingService villaBookingService;
    private HomestayService homestayService;
    private BaseBookingService baseBookingService;
    private ApartmentBookingService apartmentBookingService;
// BaseBookingService
private BookingRepository bookingRepository;
private HomestayAvailabilityRepository availabilityRepository;
// ...
@SneakyThrows
@Transactional                       // jakarta.transaction.Transactional
public BookingResponse execute(BookingRequest request) {
    // validate, lock nights, price, save
    sendNotifications(booking);
    postProcess(booking);            // ApartmentBookingService: produce event to Kafka
// validateRequest
final var currentDate = LocalDate.now();
if (checkinDate.isBefore(currentDate) || checkinDate.isAfter(checkoutDate)) { ... }
// HomestayAvailabilityRepository
@Query("""
    SELECT new HomestayAvailability(ha.homestayId, ha.date, ha.price, ha.status)
    FROM HomestayAvailability ha
    WHERE ha.homestayId = :homestayId AND ha.status = :status
    AND ha.date BETWEEN :checkinDate AND :checkoutDate
    """)
@Lock(LockModeType.PESSIMISTIC_WRITE)
List<HomestayAvailability> findAndLockHomestayAvailability(...);

Plus: the booking table has a request_id text not null column with no UNIQUE constraint; DiscountService returns the discount as a negative amount (subtotal × -0.05); PricingService has two identical calculate overloads, one taking a homestay it never uses.

The merge-blocking comments, in order of severity:

  1. TODO (BookingV2Controller, BookingFactory, BaseBookingService): the dependency fields aren’t final, so @RequiredArgsConstructor leaves them out of the constructor (I checked with Lombok 1.18.42: a class with no final fields gets an empty constructor). Spring injects nothing, the app still starts, and the first request to /api/v2/bookings hits an NPE (NullPointerException) at bookingFactory.build. Suggest private final for every dependency, a @SpringBootTest that calls this endpoint, and the ArchUnit rule from part 1, section 6.
  2. TODO (schema, booking.request_id): without UNIQUE, a client retry (flaky network, a double click) creates two bookings. Suggest UNIQUE (request_id) (build the index CONCURRENTLY on a live table) and return the existing booking on a duplicate. Details in Idempotency in distributed systems.
  3. TODO (execute, postProcess): the email and the Kafka event are sent inside the transaction. If the commit then fails, the guest has an email for a booking that doesn’t exist; move sending after the commit and a crash in between loses the event. Suggest an outbox for Kafka and @TransactionalEventListener(AFTER_COMMIT) for the email (see Observer and Spring events).
  4. TODO (@SneakyThrows + jakarta.transaction.Transactional): by default only unchecked exceptions roll back; a checked exception sneaked out via @SneakyThrows makes the transaction commit even though the method failed. Suggest dropping @SneakyThrows, or rollbackOn = Exception.class.
  5. TODO (the night-locking query): no ORDER BY ha.date. Two bookings with partially overlapping ranges can lock rows in different orders and deadlock; Postgres aborts one with deadlock detected and the user sees a 500. Add ORDER BY so every transaction locks in the same order (see Transactions, isolation levels and locking).
  6. TODO (validateRequest): LocalDate.now() uses the JVM’s default time zone. With servers on UTC, between midnight and 7 a.m. Vietnam time the server’s “today” is still yesterday, so the system accepts check-ins on a date that has already passed. Suggest injecting a Clock and computing today in the homestay’s time zone.
Non-blocking comments: QUESTION, OPTIONAL, NIT, FYI, PRAISE
  • QUESTION (the night-locking query): SELECT new HomestayAvailability(...) is a constructor expression (JPQL building new objects from columns), so the results are new objects, not entities managed by the persistence context. That means saveAll(aDays) will merge each row (an extra SELECT per night), and I’m not sure Hibernate applies FOR UPDATE to this kind of query at all. Have you checked the SQL log? If the constructor expression isn’t needed, SELECT ha FROM HomestayAvailability ha ... ORDER BY ha.date gives you both the lock and dirty checking (Hibernate detects changed fields and writes them back).
  • OPTIONAL (BookingFactory.build and validateHomestay): the homestay is loaded twice per request. You could pass the loaded homestay into the service.
  • NIT (PricingService): two identical calculate overloads, and the one taking homestay ignores it. Delete one.
  • NIT (DiscountService): a negative discount added to the subtotal is easy for the next person to flip; the result isn’t rounded either (100.00 × -0.05 = -5.0000). Suggest a non-negative discount and setScale per currency.
  • FYI (BookingFactory): the comment says “Abstract Factory” but the class just picks a bean by type, i.e. a simple factory. BookingServiceSelector would be less misleading; the default branch also sends any new listing type down the default path silently.
  • PRAISE: one availability row per night plus row locks is the right design for this problem (overlap checks become row counts, prices per night), and logging the request_id at every step makes tracing easy.
Why side effects must leave the transaction
After the review: runnable Java code and test results

After applying the comments, the core looks like this (plain Java, with the database simulated by maps so it runs with java ReviewedBooking.java):

static final class BookingService {
    private static final int MAX_NIGHTS = 365;
    private static final BigDecimal LONG_STAY_RATE = new BigDecimal("0.05");

    private final FakeDb db;        // final: constructor injection, Lombok would include it
    private final Clock clock;      // injected so tests control "today"

    BookingService(FakeDb db, Clock clock) { this.db = db; this.clock = clock; }

    /** In Spring: @Transactional(rollbackFor = Exception.class) on the public method. */
    synchronized Booking book(BookingRequest r) {
        Booking existing = db.bookingsByRequestId.get(r.requestId());
        if (existing != null) return existing;                      // retry of the same request

        Homestay h = db.homestays.get(r.homestayId());
        if (h == null) throw new BusinessException("HOMESTAY_NOT_FOUND");
        LocalDate todayAtHomestay = LocalDate.now(clock.withZone(h.zone()));
        if (r.checkin().isBefore(todayAtHomestay) || !r.checkin().isBefore(r.checkout()))
            throw new BusinessException("DATES_INVALID");
        if (r.guests() <= 0 || r.guests() > h.maxGuests()) throw new BusinessException("GUESTS_INVALID");
        long nights = Duration.between(r.checkin().atStartOfDay(), r.checkout().atStartOfDay()).toDays();
        if (nights > MAX_NIGHTS) throw new BusinessException("NIGHTS_INVALID");

        // SELECT ... FOR UPDATE ... ORDER BY date: a sorted range, so two bookings lock in the same order
        SortedMap<LocalDate, BigDecimal> range = db.freeNights.subMap(r.checkin(), r.checkout());
        if (range.size() < nights) throw new BusinessException("HOMESTAY_BUSY");

        BigDecimal subtotal = range.values().stream().reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal discount = nights >= 3
                ? subtotal.multiply(LONG_STAY_RATE).setScale(2, RoundingMode.HALF_EVEN)
                : BigDecimal.ZERO.setScale(2);
        var booking = new Booking(db.nextId++, r.requestId(), h.id(), r.checkin(), r.checkout(),
                subtotal, discount, subtotal.subtract(discount));

        new ArrayList<>(range.keySet()).forEach(db.freeNights::remove);        // mark nights BOOKED
        if (db.bookingsByRequestId.putIfAbsent(r.requestId(), booking) != null) // UNIQUE(request_id)
            throw new IllegalStateException("duplicate request_id");
        db.outbox.add(new OutboxEvent("BookingCreated", booking.id()));         // same transaction
        return booking;                                                        // email/Kafka: relay reads outbox
    }
}

The checks that run with it, with the clock fixed at 2026-11-30T18:00Z (already 1 a.m. on 1 December in Vietnam):

PASS subtotal of 3 nights = 99.99
PASS 5% long-stay discount rounded to cents = 5.00
PASS total = 94.99
PASS same request_id returns the first booking
PASS retry does not emit a second event
PASS overlapping booking rejected with HOMESTAY_BUSY
PASS check-in 2026-11-30 rejected: it is already Dec 1 in Vietnam

The synchronized only simulates a transaction in a single-process demo. In the real system, correctness comes from the database’s row locks and the UNIQUE constraint, not from a JVM lock (several instances run in parallel).

3. Worked review 2: a Redis distributed lock

Key idea: every TODO states a concrete consequence (“a 30-second lock becomes an 8-hour one”) and the fix, so the author doesn’t have to guess what the reviewer wants.

The same codebase has a Redis-based distributed lock service. The full analysis and rewrite are in Reviewing a Redis distributed lock; here is just how I’d word the comments:

Label Comment
TODO The lock value is the constant 1 and unlock is an unconditional DEL: a client whose lock expired can delete another client’s lock. Use a random token per acquisition and a Lua script that compares the token before deleting.
TODO The TTL is multiplied by 1000 twice (once at init, once in lock), turning a 30-second lock into an 8-hour one. Carry the unit in the type (Duration) instead of multiplying by hand.
TODO The property names in YAML and in code don’t match, so the app fails to start when the property is missing. Use @ConfigurationProperties with validation.
TODO Multiple keys are acquired in parallel with no ordering: two requests with overlapping key sets can each hold part and retry forever (livelock: both keep running but neither makes progress). Sort the keys and acquire sequentially.
QUESTION unlock runs asynchronously on an unbounded newCachedThreadPool, so the caller returns before the lock is released. Is that intended?
FYI A lock on a single Redis node isn’t safe across failover (asynchronous replication). If the lock protects data correctness, you need fencing tokens (an increasing number the storage uses to reject a stale lock holder) or the database’s own locks.

Exercises

Exercise 1: Review three solutions to grouping anagrams

Task (the session’s homework, paraphrased): given an array of lowercase strings (up to 10^4 strings, each up to 100 characters), group the strings that are anagrams of each other, in any order. For example ["eat","tea","tan","ate","nat","bat"] gives [eat, tea, ate], [tan, nat], [bat]; [""] gives [[""]]. Three people submitted three solutions; review them.

// Solution A: compare every pair
static List<List<String>> pairwise(String[] words) {
    List<List<String>> groups = new ArrayList<>();
    boolean[] used = new boolean[words.length];
    for (int i = 0; i < words.length; i++) {
        if (used[i]) continue;
        List<String> g = new ArrayList<>(List.of(words[i]));
        for (int j = i + 1; j < words.length; j++) {
            if (!used[j] && isAnagram(words[i], words[j])) { g.add(words[j]); used[j] = true; }
        }
        groups.add(g);
    }
    return groups;
}

// Solution B: key = sorted characters
static List<List<String>> bySortedKey(String[] words) {
    Map<String, List<String>> groups = new HashMap<>();
    for (String w : words) {
        char[] cs = w.toCharArray();
        Arrays.sort(cs);
        groups.computeIfAbsent(new String(cs), k -> new ArrayList<>()).add(w);
    }
    return new ArrayList<>(groups.values());
}

// Solution C: key = sum of character codes
static List<List<String>> bySumKey(String[] words) {
    Map<Integer, List<String>> groups = new HashMap<>();
    for (String w : words) groups.computeIfAbsent(w.chars().sum(), k -> new ArrayList<>()).add(w);
    return new ArrayList<>(groups.values());
}
Answer to Exercise 1: results and a comment on each solution

I ran all three (plus a fourth that uses a 26-letter count array as the key) on the example and on 10,000 random strings of 1–8 characters (7,630 groups):

[[eat, tea, ate], [bat], [tan, nat]]
[[]] [[a]]
sum-key bug on [ad, bc]: [[ad, bc]]
groups: 7630
count key agrees: true
pairwise agrees:  true
round 2: pairwise 219 ms, sorted 1 ms, counts 1 ms

Comments:

  • A — PRAISE correct and readable, and isAnagram uses a count array, O(k). TODO it’s O(n²·k): with n = 10^4 that’s about 5×10^7 comparisons. I measured 219 ms with short strings, but 100-character strings will be much slower, and it grows quadratically with the input. Suggest grouping by key in a HashMap to get O(n·k log k) or O(n·k).
  • B — PRAISE O(n·k log k), short, and correct for any characters (not just a–z). OPTIONAL with small k (≤ 100) this is already the solution to pick; a 26-letter count key only pays off for large k.
  • C — TODO wrong: two strings with different letters can have the same sum ("ad" and "bc" are both 197), so they get grouped together. A hash (the sum) is only a necessary condition; a map key has to be a canonical form (one value that uniquely identifies the group) that uniquely identifies the group, like the sorted string or the count array. Add a test with ["ad","bc"].

Exercise 2: Record the decision after the argument

Task: write a short ADR for the case study in section 1.

Answer to Exercise 2: ADR-017
# ADR-017: Fraud-check timeout on the synchronous payment path

Status: Accepted (2026-11-18)

## Context
POST /payments/sync waits for the fraud service's result over Kafka. The wait currently comes from
spring.redis.timeout (300 s). The endpoint's p99 target is 2 s; Tomcat has 200 worker threads.

## Decision
- A separate business timeout: payment.fraud-check.timeout = 2s.
- On expiry: return PENDING_REVIEW (fail-closed); never approve the transaction.
- Late results are processed asynchronously and update the transaction.

## Options considered
- Keep the 300 s wait: threads run out at about 1 request/s when the fraud service is slow.
- Fail-open on expiry: risk of approving fraud, not acceptable.
- Asynchronous API (202 + webhook): the right direction, needs client changes, planned for next quarter.

## Consequences
- Some transactions move to PENDING_REVIEW when the fraud service is slow; we need a dashboard for that rate.
- Revisit when the fraud service's p99 is under 300 ms or when the asynchronous API ships.

Remember

  • Walk through the steps from disagreement to decision, and know when to move from comments to a conversation.
  • Use Little’s law to work out at how many requests per second a slow endpoint drains the thread pool.
  • Explain why a business timeout must be separate from an infrastructure timeout, and how to choose fail open or fail closed.
  • Spot the Spring traps in the worked review: non-final fields, @SneakyThrows with @Transactional, side effects before the commit, LocalDate.now().
  • Write a TODO comment with a concrete consequence and the fix.

Interview questions

Junior

What does disagree and commit mean?

Once a decision has been made through a proper process, the people who disagreed still execute it fully instead of half-heartedly or continuing the argument.

A “proper process” means all sides were heard and the options weighed. The disagreement is recorded (usually in an ADR) along with the conditions for revisiting it, so if an assumption turns out wrong there’s a basis for reopening the decision.

Mid

You find a serious bug outside the scope of the PR you’re reviewing. What do you do?

Leave an FYI on the PR so the author knows, but don’t require the fix in that PR (unless the PR makes it worse).

Open a separate prioritised issue, or raise it immediately if it’s causing an incident. Expanding a PR’s scope makes the review harder and delays a change that needs to land.

You’re reviewing code that compares a check-in date with LocalDate.now(). What do you comment?

LocalDate.now() uses the JVM’s time zone, so I’d ask for an injected Clock and computing the date in the business location’s zone.

The JVM usually runs on UTC in a container, so between midnight and 7 a.m. Vietnam time the server’s “today” is still yesterday. Fix it with LocalDate.now(clock.withZone(zone)), plus tests with a fixed clock around midnight.

An anagram-grouping solution uses the sum of character codes as the key. How do you review it?

It’s wrong: two strings with different letters can share a sum ("ad" and "bc" are both 197) and get grouped together.

A sum is just a hash, a necessary condition. The map key has to be a canonical form that uniquely identifies the group, like the sorted string (O(k log k)) or a 26-letter count array (O(k)). Add a test with that pair so the bug can’t come back.

Senior

You and the author disagree about a design in a PR. How do you handle it?

Make sure we understand each other, move the argument to context and evidence, then decide, disagree and commit, and record an ADR.

  • Summarise each other’s argument until both agree it’s been understood; write down the pros and cons of each option.
  • Establish the context and which qualities are being prioritised; if an assumption is measurable, build a PoC or measure.
  • After two rounds of comments, talk in person. Still no agreement: take it to the group or the tech lead.
  • Once decided: disagree and commit, and record an ADR with conditions for revisiting it.
How do you write a comment about a serious mistake by a new colleague so it actually helps?

Label it TODO, state the concrete consequence, the cause and the fix; write about the code, not the person.

Concrete consequences look like “the first request will NPE” or “the customer gets charged twice”. Offer a fix or a code suggestion, link to docs, and mention what’s good in the PR too. If several issues share a root cause (say, misunderstanding @RequiredArgsConstructor), a 10-minute conversation beats 10 comments.

A review reveals a synchronous endpoint that waits up to 5 minutes for a Kafka reply. How do you argue it?

With Little’s law: busy threads = request rate × wait time, so a 5-minute wait exhausts the threads at under one request per second.

Tomcat’s 200 worker threads with each request waiting 5 seconds only sustain 40 requests per second; with a 5-minute wait the whole service stops answering. I’d ask for a separate business timeout from the SLA, an explicit behaviour on expiry (fail-closed for financial transactions), and an asynchronous API in the longer term.

Useful phrases for interviews

  • “Let’s take this offline; after two rounds of comments a quick call is faster.”
  • “Before we argue, let me make sure I can state your position in my own words.”
  • “Given our current priority on reliability, I’d go with the fail-closed option.”
  • “By Little’s law, a five-second wait at forty requests per second uses all two hundred Tomcat threads.”
  • “I disagreed, but once the team decided, I committed to it and we recorded the reasoning in an ADR.”
  • “Side effects like emails and events belong after the commit, or in an outbox.”
  • “Today has to be computed in the business’s time zone, so we inject a Clock.”

Notes based on the Advanced Backend course (Ronin Engineer), rewritten in my own words.