A point in CASHPOCKET was bought by an advertiser with a card and can leave as a bank transfer to a tester. The code that moves points is therefore the part of the system with the least room for error. All of it goes through one function, which this page calls the kernel.

The problem

Three things can go wrong when a balance changes.

  • Two requests spend the same points. A tester with 10,000 points opens the shop on a phone and the withdrawal page in a browser and presses both buttons. If each request reads the balance, sees enough, and then writes, both succeed and the account has spent 20,000.
  • The process dies between two writes. If the balance is reduced and the history row is never written, the system holds a number it cannot explain. If the row is written and the balance is not, the tester has been charged on paper only.
  • The same operation arrives twice. A payment confirmation is retried, or a job runs again. That case has its own page: Idempotency keys.

Application-level locking does not solve the first two on a server that runs as two processes. The database has to be the one that says no.

The kernel

A flow of four boxes in a row. A point movement, a credit or debit with a reason and, where it can repeat, a key, goes to a key lookup that asks whether a row with this key is already in the ledger. If it is new, the flow enters a dashed region labelled one MongoDB transaction containing a balance update, conditional so that a debit needs the balance to be at least the amount, followed by a ledger row holding delta, reason, reference and the balance before and after. From the key lookup a dashed arrow labelled found leads down to a box named repeat: return the first result, balance untouched. From the balance update a red arrow labelled no match leads down to a box named not enough: nothing is written and the caller gets an error. Two notes below: two concurrent debits that together exceed the balance each state the balance they need, the database applies one and the other finds no matching document; and credits carry an expiry date 180 days after they are earned, while the ledger keeps the balance before and after each row so an audit can compare the stored balance with the history.
Figure 1. The point kernel. A movement is checked against earlier rows by key, then applied as a conditional balance update and a ledger insert inside one transaction. A repeat returns the first result, and a debit the balance cannot cover writes nothing.

The kernel takes a user, a signed amount, a reason, a reference to the thing the movement belongs to, and optionally a key and a database session. It does three things in order.

  1. If a key was given, it looks for a ledger row with that key. A hit means this operation has already happened, and the kernel returns the earlier result without touching anything.
  2. It updates the balance on the user document with a condition. A credit always matches. A debit matches only if the balance is at least the amount.
  3. It inserts the ledger row, with the balance before and after taken from the document the update returned.

Steps 2 and 3 run in one transaction. The pseudo-code below was written for this page.

movePoints(user, delta, reason, ref, key?, session?):
    reject unless delta is a non-zero safe integer

    if key and the ledger has a row with this key:
        return { duplicate: true, balance: that row's balanceAfter }

    in a transaction (the caller's session, or a new one):
        doc = users.findOneAndUpdate(
                where  _id = user
                  and  (delta > 0  or  balance >= -delta),
                set    balance = balance + delta )
        if no document matched:
            fail with "insufficient balance" or "no such user"

        ledger.insertOne({
            user, delta, reason, ref, key,
            balanceBefore: doc.balance - delta,
            balanceAfter:  doc.balance,
            expiresAt:     delta > 0 ? now + 180 days : none })

    return { duplicate: false, balance: doc.balance }

The condition in step 2 is the whole answer to the first problem. Each debit states the balance it needs inside the update itself. When two debits race, MongoDB applies them one after the other. The second one is evaluated against the balance the first one left, finds that the condition no longer holds, and matches nothing. No lock is taken in the application, and there is no moment where a stale read can be acted on.

The transaction is the answer to the second problem. MongoDB commits the balance change and the ledger row together or not at all.

Why the balance is stored

An alternative design keeps no balance and sums the ledger whenever one is needed. It has one attractive property: there is a single source of truth by construction. The kernel keeps a stored balance instead, and its header names that field the single source of truth. Two properties come with that choice.

A sum cannot refuse an overdraft atomically. Reading the sum and then inserting a debit row are two operations, and two requests can interleave between them. Closing that gap needs a lock or a serialisable transaction around every spend. A stored number with a conditional update needs neither.

A sum also costs more with every row a user accumulates, while a stored number is one field read.

The price of storing the balance is that two things now have to agree. The transaction makes them agree at write time, and the balanceBefore and balanceAfter fields make the agreement checkable later. A read-only audit script walks each user’s rows, compares the stored balance with the sum of deltas, and reports any row whose balanceBefore does not equal the previous row’s balanceAfter.

Joining a caller’s transaction

Many operations need a point movement and something else to succeed or fail together. A withdrawal is a debit and a request row. A shop purchase is a stock decrement, a debit and a purchase row. The kernel accepts the caller’s session for this. When it gets one, it does not open its own transaction: its two writes join the caller’s, and the caller’s commit decides all of them.

One detail follows from that. If the ledger insert hits the unique index on the key while the kernel owns the transaction, the kernel rolls back and answers as a repeat. If it happens inside a caller’s session, the kernel cannot quietly swallow the error, because the caller’s other writes are part of the same transaction. It rethrows, and the caller’s transaction aborts as a whole.

Reading a balance

The first version of the product stored the balance in a field with a different name. When the current field was introduced, the old one was kept as a mirror, and some read paths used an expression that fell back to the old field when the new one was falsy.

Zero is falsy. In August 2026 accounts that had spent their whole balance started showing the stale value from the legacy field again. The fix was to put every read behind one resolver with an explicit rule: the current field wins whenever it is a number, zero included, and the legacy field is used only when the current one does not exist. The kernel’s conditional update uses the same rule on the database side.

Expiry

Every credit row gets an expiry date 180 days after it was earned. A batch route, protected by its own key, collects credits past their date, deducts the total per user through the kernel with a dedicated reason, flags the source rows as expired and writes a notification. If the deduction would exceed the balance, the kernel refuses it like any other debit, the user is logged as an error, and the rows stay unflagged.

Failure modes

What happensWhat the system doesCovered by
Two debits race and together exceed the balanceOne conditional update matches. The other matches nothing and fails as insufficientA test on an in-memory replica set runs two concurrent debits and asserts that exactly one succeeds
The transaction aborts after the balance updateBalance and ledger both roll backA test joins the kernel to a caller’s session, aborts it, and asserts both are unchanged
The same keyed movement arrives againThe earlier result is returned and nothing is writtenA test fires five concurrent calls with one key and asserts the balance moved once
The amount is zero or not a safe integerRejected before any read or writeA guard at the top of the kernel
A debit for a user that does not existThe conditional update matches nothing and the call failsKernel unit tests on the conditional update, with a mocked database
A zero balance is read through a legacy fallbackThe resolver returns zeroA unit test on the balance resolver

Limits

  • Rows are not strictly immutable. The expiry batch flags the rows it has expired, and one backfill filled in a status and an expiry date on rows that predate those fields. Amounts are corrected by adding an adjustment row through the kernel.
  • The promise holds for calls that go through the kernel. The repository’s conventions route every point change there, and the older history collections are no longer the record.
  • The stored balance is the truth and the ledger is its explanation. If they ever disagree, the audit reports it and a person decides. The repair script proposes a correction, runs dry by default, and refuses to apply beyond a cap on accounts and total amount.
  • The index behind keyed movements is created by a script, not by the schema. A new environment needs that script run before the code that depends on it.