Quick revision
The short answer
A PN-Counter keeps two maps from replica id to a running total: p counts increments and n counts decrements, and each replica only ever raises its own slot. The value is the sum of p minus the sum of n, and merge takes the maximum of each slot, because every slot only grows, so the larger number is simply the newer one. Since max gives the same answer however often and in whatever order we apply it, a merge message delivered twice changes nothing.
What to remember
In this answer, we built a PN-Counter from two grow-only maps keyed by replica id. Each replica only increments its own slots, value() is the sum of p minus the sum of n, and merge takes the per-slot maximum because each slot only grows, so the larger number is the newer total. Max is idempotent, commutative and associative, so duplicated or reordered messages do no harm. We also saw the practical rules: atomic per-slot updates, stable unique replica ids, and reloading a replica's own slot after a restart so it never moves backwards.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
A PN-Counter keeps two maps from replica id to a running total: p counts increments and n counts decrements, and each replica only ever raises its own slot. The value is the sum of p minus the sum of n, and merge takes the maximum of each slot, because every slot only grows, so the larger number is simply the newer one. Since max gives the same answer however often and in whatever order we apply it, a merge message delivered twice changes nothing.
Why this question is asked
A like counter that lives in three regions is a classic place where locking is too slow and last write wins loses updates. Conflict-free replicated data types, CRDTs for short, solve it by choosing a state shape whose merge can never conflict. Interviewers ask for the PN-Counter because it is small enough to write on a whiteboard, yet it shows whether we understand why merge must be idempotent, commutative and associative. In this answer, we will recap the grow-only counter it is built from, write the PN-Counter in Java, walk through a merge between regions, see what a duplicated message does, and finish with the practical details: thread safety, replica ids and restarts.
1A Quick Recap: Why a Plain Counter Fails
Suppose each region simply stores one number, the like count, and sends it to the others. Region US has 10 likes and adds 2, so it sends 12. Region EU has 10 and adds 1, so it sends 11. When US receives 11, should it keep 12, take 11, or add something? It cannot tell which likes the 11 already includes, so any choice loses or double counts.
The trick of a CRDT, a conflict-free replicated data type, is to store enough structure that the merge is obvious. A G-Counter (grow-only counter) gives every replica its own slot. Replica US only increments the US slot, EU only the EU slot, and the value is the sum of all slots. A PN-Counter is two G-Counters side by side: P for increments (the positive side) and N for decrements (the negative side). We need two because a slot that went down would break the rule that makes merge work, as we will see.
2Writing the PN-Counter in Java
The state is two maps from replica id to long. Increment adds 1 to this replica's entry in p, decrement adds 1 to this replica's entry in n, and value() subtracts the two sums. For merge, we pass a snapshot of the other replica's state, which in a real system arrives as a message.
Notice that increment and decrement only touch the slot for replicaId. That is the whole discipline of the type: every slot has exactly one writer, so no two replicas ever race on the same number. ConcurrentHashMap.merge with Long::sum makes a local increment atomic, and merge with Math::max makes the remote merge atomic per slot, so several threads in one region can use the same counter safely.
3Following a Merge Between Regions
Let us run two regions through a few operations and a merge, including the case the question asks about, a message that arrives twice.
8 messages in order. Play them, or step through them one at a time.
Because max is idempotent, a duplicated message is harmless.
Notice that the second merge changed nothing. For the eu slot, US already holds 1, and max(1, 1) is 1. That is idempotence: applying the same input again gives the same result. Max is also commutative (max(a, b) equals max(b, a)) and associative (the grouping does not matter), so the regions can receive each other's states in any order, through any path, as many times as the network likes, and they still end at the same value once they have seen the same updates.
4Why the Maximum Is the Right Merge
Each slot is a running total that only its own replica changes, and it only ever grows. So if US has eu=3 and the incoming message says eu=5, the 5 must be a later reading of the same total, which already contains the 3 likes we knew about. Taking the maximum keeps the newest reading and throws nothing away. If the message says eu=2, it is an old, delayed reading, and max correctly ignores it.
This is also why decrements need their own map. If a slot could go down, a smaller number might be newer, and max would pick the wrong one. Keeping n as a separate grow-only total means both maps obey the same rule, and the subtraction happens only when we read the value.
Adding the incoming values instead would be wrong, because the message carries totals, not deltas. Merging eu=1 twice by addition would count EU's like twice, and every retry, every gossip path and every message that arrives through two routes would inflate the counter. Max lets us use an unreliable, at-least-once channel without any deduplication.
5Replica Ids, Restarts and Thread Safety
Three practical details decide whether this works in production. First, each replica needs a stable, unique id. If two processes accidentally share the id us, they both write the us slot, and max throws away one of their increments. If a replica gets a new random id on every start, the maps grow with a dead slot per restart, which is harmless for correctness but wastes space forever.
Second, a restarted replica must reload its own slot before it increments. If US crashes, forgets that it had us=500, starts again at 0 and increments to 1, then every other region keeps 500 for that slot and US's next 499 likes vanish, because max(500, 1) is 500. That is why the constructor above merges a saved state first; in practice we persist the state, or fetch it back from a peer, before accepting writes.
Third, thread safety within a replica. ConcurrentHashMap gives atomic per-slot updates, but value() reads two maps one after the other, so a concurrent increment can make one read slightly stale. For a like counter that is fine. If we need a perfectly consistent snapshot, we make increment, decrement, merge and value synchronized on the object, which is simple and cheap for this size of state.
6Follow-up questions
Why would adding the other replica's values instead of taking the maximum be wrong?
Because the state we receive holds cumulative totals, not changes. If EU sends eu=5 and later eu=6, adding them would give 11, when EU has only ever counted 6. Duplicates and messages that arrive through two different peers would also be added again. Max treats each slot as a reading of a growing number and keeps the latest reading, which is correct no matter how many times or in what order we receive it.
Can a PN-Counter guarantee the value never goes below zero?
No. Each region decrements locally without asking the others, so two regions can both remove the last like and the merged value becomes -1. If a bound must hold, we need coordination, for example splitting the allowed amount between regions as escrow, or routing decrements through one owner. For likes, we usually just display max(value, 0).
How big does the state get?
It has one entry per replica in each map, so with three regions it is six longs. It stays tiny as long as replica ids are regions or stable nodes, not users or requests. That is why the id must be stable rather than random per process start.
7Conclusion
In this answer, we built a PN-Counter from two grow-only maps keyed by replica id. Each replica only increments its own slots, value() is the sum of p minus the sum of n, and merge takes the per-slot maximum because each slot only grows, so the larger number is the newer total. Max is idempotent, commutative and associative, so duplicated or reordered messages do no harm. We also saw the practical rules: atomic per-slot updates, stable unique replica ids, and reloading a replica's own slot after a restart so it never moves backwards.
Open with
I would model it as two grow-only counters. The state is two maps from replica id to long, p for increments and n for decrements. increment adds one to p for my own replica id, decrement adds one to n for my own id, and value is the sum of p minus the sum of n.
Then, if they want more
Merge goes through every replica id in the incoming state and sets each slot to the maximum of mine and theirs, separately for p and n. The maximum is correct because every slot is a running total that only its owner changes and that only grows, so the larger value is always the newer one and already includes the smaller.
That is also why decrements need their own map: a slot that could go down would break that rule. If a merge message is delivered twice, nothing changes, because max is idempotent, and since it is also commutative and associative, order and the path a message takes do not matter either.
Adding instead of taking the maximum would double count every retry. In Java I would use ConcurrentHashMap.merge with Long::sum for local updates and Math::max for merges, or synchronized methods if I need a consistent read.
Finally, each replica needs a stable unique id, and a restarted replica has to reload its own slot before incrementing, otherwise it starts from zero and its new increments are hidden by the old maximum.
About this answer
- Last updated
- 13 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Implement a PN-Counter in Java with increment, decrement, value and merge, and explain...": https://scrivio-interview-library.netlify.app/architecture/partitioning-and-replication/08ff34eb55/