Skip to content

Retries & Version Checks

The Course
•
20 min study

A caller may repeat a request because it did not see the first response. Idempotent handling gives that repeat the same state effect as one request. This lesson separates a safe replay from a conflicting request that reuses an identifier with different content.

Understand the contract

Use the request's stable ID as the lookup key and compare the complete normalized value. If the key is absent, insert. If the stored value equals the incoming value, report replay and make no change. If the ID matches but the content differs, reject. Silently keeping either value would hide a conflict.

This is an in-memory single-process example. It does not promise exactly-once network delivery, storage after a restart, or concurrent safety. A real service needs durable deduplication and a defined retention window. Here the useful design principle is testable without networking: retries must not add another contribution to a total.

Version checks solve a related but different problem. A client reads version 4, makes an edit, then submits expectedVersion=4. If another accepted update has moved the state to version 5, the old edit should be rejected rather than silently overwriting newer work. A real concurrent store must make the version check and update one atomic operation; two separate statements without synchronization are not enough.

Before running, write the output you expect and explain which rule produces each line. Each editor is an independent program.

Predict, then run Java
import java.util.Map;
import java.util.LinkedHashMap;

public class Main {
    public static void main(String[] args) {
        Map<String, Request> saved = new LinkedHashMap<>();
        System.out.println(save(saved, new Request("A", 10)));
        System.out.println(save(saved, new Request("A", 10)));
        System.out.println(saved.size());
    }

    static String save(Map<String, Request> saved, Request request) {
        Request old = saved.get(request.id());
        if (old != null) {
            if (!old.equals(request)) {
                throw new IllegalArgumentException("id conflict");
            }
            return "Replay";
        }
        saved.put(request.id(), request);
        return "Inserted";
    }
}

record Request(String id, int amount) {}
Check your prediction
Text
Inserted
Replay
1

Trace a different case

This sequential model makes the stale-version rule visible without threads. Revision is a record containing a version and text. A successful edit returns a new revision; a stale edit throws before returning one. The old read still describes version 4 even after current changes. The example deliberately uses tiny versions so integer overflow is outside its contract.

Compare the boundary case Java
public class Main {
    public static void main(String[] args) {
        Revision current = new Revision(4, "Old");
        Revision earlierRead = current;
        current = edit(current, 4, "New");
        try {
            current = edit(current, earlierRead.version(), "Stale edit");
        } catch (IllegalArgumentException expected) {
            System.out.println("Stale rejected");
        }
        System.out.println(current.text());
    }

    static Revision edit(Revision current, int expectedVersion, String text) {
        if (current.version() != expectedVersion) {
            throw new IllegalArgumentException("stale version");
        }
        return new Revision(current.version() + 1, text);
    }
}

record Revision(int version, String text) {}
Check your prediction
Text
Stale rejected
New

Compare the whole request after matching its identity

The ID locates a prior request; equality decides whether the incoming content repeats it. Matching only the amount could confuse two different requests, while matching only the ID could conceal a changed category or payload. Normalize values before this comparison so equivalent accepted spellings behave consistently.

Trace three outcomes: absent ID inserts, equal existing request replays without a second contribution, changed existing request rejects. An empty batch and a replay-only batch can both make no state change for different reasons; result counts can explain the distinction.

A version check addresses another question: whether an edit was based on the current state. It does not automatically identify a replay. Keep those contracts separate, and remember that a real concurrent version comparison and write must be coordinated by the storage implementation.

Build it yourself

Exercise

Retries & Version Checks: practice

The replay rule was practised in the first example. This exercise is the other half: a version-checked update. Write a Note class that owns its state:

  • a new Note holds its text at version 1;
  • version() and text() read the state;
  • edit(int expectedVersion, String newText) replaces the text and adds one to the version, but only if expectedVersion equals the current version and the new text is not blank. Otherwise it throws IllegalArgumentException and changes nothing.

Make main print exactly:

Text
2 Plan
Stale rejected: 2 Plan
Blank rejected: 2 Plan
3 Final

The stale edit uses the version read before the first edit; the blank edit uses the current version.

Your workspace Java
public class Main {
    public static void main(String[] args) {
        // Create a Note("Draft") and keep the version you read from it.
        // Edit to "Plan" with that version, then retry with the same old version.
        // Try a blank edit with the current version, then edit to "Final".
        System.out.println("Your workspace");
    }
}

class Note {
    // Private version and text, a constructor, two readers and edit().
}
Hint 1: the idea

The caller says which version its edit was based on. If that is no longer the current version, someone else's change came first, and applying the edit would silently erase it. Every check must happen before either field changes.

Hint 2: a first step

In edit, write the two if ... throw checks first: version, then text. Only after both, assign the text and increment the version. Keep the old version in a local variable in main so you can send it again for the stale edit.

Show one solution
Java
public class Main {
    public static void main(String[] args) {
        Note note = new Note("Draft");
        int read = note.version();
        note.edit(read, "Plan");
        System.out.println(note.version() + " " + note.text());

        try {
            note.edit(read, "Old idea");
        } catch (IllegalArgumentException expected) {
            System.out.println("Stale rejected: " + note.version() + " " + note.text());
        }
        try {
            note.edit(note.version(), " ");
        } catch (IllegalArgumentException expected) {
            System.out.println("Blank rejected: " + note.version() + " " + note.text());
        }
        note.edit(note.version(), "Final");
        System.out.println(note.version() + " " + note.text());
    }
}

class Note {
    private int version = 1;
    private String text;

    Note(String text) {
        this.text = text;
    }

    int version() {
        return version;
    }

    String text() {
        return text;
    }

    void edit(int expectedVersion, String newText) {
        if (expectedVersion != version) {
            throw new IllegalArgumentException("stale version " + expectedVersion);
        }
        if (newText == null || newText.isBlank()) {
            throw new IllegalArgumentException("text required");
        }
        text = newText;
        version++;
    }
}

Expected output:

Text
2 Plan
Stale rejected: 2 Plan
Blank rejected: 2 Plan
3 Final

Both checks come before the two assignments, so a rejected edit leaves version and text exactly as they were; the second and third lines prove it. The version goes up only on success, which is what makes the old read value stale. Notice that a network retry of the first edit would also be rejected as stale: version checks stop lost updates, and replay detection needs the request-ID rule from the first example. In a concurrent store, the check and the write would have to be one atomic step.

Change it and test again

Move version++ above the two checks in edit and run main again: which printed line changes first, and why? Restore it. Then combine the two rules: give each edit a request ID as well, and decide what a retry of an edit that already succeeded should return. Should it be a replay or a stale rejection? Write down the contract before changing code.

Explain before moving on

What is the difference between a replay, a conflict and a stale version? Explain why these deterministic tests establish decision rules but do not prove thread safety. Concurrent Java and database transactions require separate execution environments and tests.

Was this article helpful?

Your response is saved on this device.