Foundationপ্রথম নীতি থেকে
LEVEL 9 · Distributed Systems

PN Counter

পিএন-কাউন্টার

Positive-Negative counter — দুই G-Counter-এর বিয়োগ; increment-decrement দুটোই conflict-free।

also: positive-negative-counter, g-counter-pair

class PNCounter:
    P: dict[str, int]      # node → মোট increment
    N: dict[str, int]      # node → মোট decrement

    def value(self) -> int:
        return sum(self.P.values()) - sum(self.N.values())

    def merge(self, other):            # element-wise max — semilattice join
        for k in set(self.P) | set(other.P):
            self.P[k] = max(self.P.get(k, 0), other.P.get(k, 0))
        ...
  • G-Counter একা কমতে শেখে না — max-join-এ পুরনো value ফিরে আসে; negative পাশ আলাদা counter-এ রাখাই কৌশল
  • Per-node slot-এর কারণে size O(nodes); churn-heavy cluster-এ compaction strategy ভাবতে হয়
  • Use case: globally aggregated stats (views/likes/errors) যেখানে কেন্দ্রীয় counter single-point contention