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

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.
- 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.
- 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.
- 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 happens | What the system does | Covered by |
|---|---|---|
| Two debits race and together exceed the balance | One conditional update matches. The other matches nothing and fails as insufficient | A test on an in-memory replica set runs two concurrent debits and asserts that exactly one succeeds |
| The transaction aborts after the balance update | Balance and ledger both roll back | A test joins the kernel to a caller’s session, aborts it, and asserts both are unchanged |
| The same keyed movement arrives again | The earlier result is returned and nothing is written | A test fires five concurrent calls with one key and asserts the balance moved once |
| The amount is zero or not a safe integer | Rejected before any read or write | A guard at the top of the kernel |
| A debit for a user that does not exist | The conditional update matches nothing and the call fails | Kernel unit tests on the conditional update, with a mocked database |
| A zero balance is read through a legacy fallback | The resolver returns zero | A 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.
