A balance looks like the simplest thing in your database. It's one number: add to it when money comes in, and subtract when it's spent.
Then a refund runs twice, two purchases spend the same credit, or someone asks why their balance is $12 short. If that number is all you kept, you can't explain how it got there.
We learned this on PlayerBay, the marketplace we built and run. Early on, a refund meant to return a buyer's store credit returned a hundredth of it, because dollars and credit had been mixed up in one calculation. We put it right, and it changed how PlayerBay handles money for good. This guide covers the pattern we use now, with a smaller version you can adapt.
Why a balance field isn't enough
This refund code looks reasonable:
const order = await orders.findOne({ _id: orderId })
if (order.refunded) return
await accounts.updateOne(
{ _id: order.buyerId },
{ $inc: { balance: order.totalCents } }
)
await orders.updateOne({ _id: orderId }, { $set: { refunded: true } })
$inc is atomic, so two updates won't overwrite each other. But the refund as a whole still isn't safe:
- Two requests can race. Both see
refunded: false, and both add the money. - The server can crash between the writes. The buyer has the money, but the order doesn't say so. The next retry pays them again.
- There's no history. The balance shows the total, not which refund, purchase or correction changed it.
A ledger fixes all three. Each movement gets its own entry, and the balance becomes a running total you can check against those entries.
Step 1: Choose one unit and use whole numbers
Store amounts as whole numbers in the currency's smallest unit. For US dollars, $25.00 is 2500 cents. JavaScript can't represent every decimal exactly, so 0.1 + 0.2 gives 0.30000000000000004.
Whole numbers won't save you from mixing up units, though. Say your store credit uses 100 units per dollar. If a $25 refund adds 25 instead of 2500, the buyer gets 25 cents. Both are valid whole numbers, so checking for a whole number won't catch it.
- Put the unit in the name.
refundCentsis much harder to misuse thanrefund. - Convert once, at the edge. Do it where the amount enters your system, so everything after that uses one unit.
- Test real amounts. Check that a $25.00 refund adds exactly
2500units, not just that the balance went up.
The example below uses one currency. If you have several, store the currency with every account and entry, and never add different currencies together.
Step 2: Give every movement a key
An idempotency key identifies one movement of money. If the same movement is tried again, it uses the same key, and the ledger knows it's already done.
Build the key from the business reason, not from the request:
| Movement | Example key |
|---|---|
| Wallet top-up | topup:<paymentId> |
| Store credit spent on an order | order-balance:<orderId> |
| Full refund of an order | refund:<orderId>:full |
| Refund from a dispute | refund:<orderId>:dispute-<disputeId> |
A new random ID for each attempt defeats the purpose, because every retry looks like a new movement. If nothing in your data identifies the action, such as a manual credit from staff, create an ID when the form opens and reuse it for every retry of that submission.
Share a key when only one action should win
An order might be refunded because delivery was late, the seller cancelled or staff stepped in. If each route has its own key, two of them can refund the same order.
On PlayerBay, the routes that refund an order in full share one key. If two run at once, only one can add the credit. Dispute refunds have their own key for each dispute, because they're a separate decision.
Let the database enforce it
Create a unique index on the key before your code moves any money:
await db
.collection("ledger_entries")
.createIndex({ key: 1 }, { unique: true })
Checking for a key in your code isn't enough, because two requests can check at the same moment. The index is what guarantees there's only one entry per key. It matters so much that PlayerBay's ledger won't move any money if the index is missing.
If you're adding keys to a collection with older entries that don't have them, use a partial index so the rule only covers entries with a key:
await db.collection("ledger_entries").createIndex(
{ key: 1 },
{
unique: true,
partialFilterExpression: { key: { $type: "string" } },
}
)
Use one version or the other. With the partial index, entries without a key aren't protected, so your code must require a key for every new one.
Step 3: Save the entry and balance together
The ledger entry and the balance update must both succeed or both fail. That calls for a transaction, and MongoDB only supports those on replica sets and sharded clusters, not standalone servers.
This is the whole function, using the official Node.js driver:
import { MongoServerError, type MongoClient } from "mongodb"
type Account = { _id: string; balance: number }
type Movement = {
accountId: string
amount: number // cents: positive adds, negative takes away
key: string
reason: string
}
type Entry = Movement & { createdAt: Date }
type Result = "applied" | "duplicate" | "insufficient_funds"
class InsufficientFunds extends Error {}
const assertSameMovement = (entry: Entry, movement: Movement) => {
if (
entry.accountId !== movement.accountId ||
entry.amount !== movement.amount
)
throw new Error(`Key ${movement.key} was used for a different movement`)
}
export const moveBalance = async (
client: MongoClient,
movement: Movement
): Promise<Result> => {
const { accountId, amount, key } = movement
if (!Number.isSafeInteger(amount) || amount === 0)
throw new Error("Amount must be a non-zero whole number of cents")
const entries = client.db().collection<Entry>("ledger_entries")
const accounts = client.db().collection<Account>("accounts")
const session = client.startSession()
try {
return await session.withTransaction(async (): Promise<Result> => {
const existing = await entries.findOne({ key }, { session })
if (existing) {
assertSameMovement(existing, movement)
return "duplicate"
}
await entries.insertOne(
{ ...movement, createdAt: new Date() },
{ session }
)
const updated = await accounts.updateOne(
amount < 0
? { _id: accountId, balance: { $gte: -amount } }
: { _id: accountId },
{ $inc: { balance: amount } },
{ session, upsert: amount > 0 }
)
if (updated.matchedCount + updated.upsertedCount === 0)
throw new InsufficientFunds()
return "applied"
})
} catch (error) {
if (error instanceof InsufficientFunds) return "insufficient_funds"
if (error instanceof MongoServerError && error.code === 11000) {
const existing = await entries.findOne({ key })
if (existing) {
assertSameMovement(existing, movement)
return "duplicate"
}
}
throw error
} finally {
await session.endSession()
}
}
We ran this code with version 6.21 of the driver on a one-member test replica set. A few details matter:
- A duplicate is a normal result. The first check handles most repeats. If two requests race past it, the unique index still allows only one entry. After a duplicate key error, the code looks up the saved entry once the transaction has ended. MongoDB aborts a transaction when an operation inside it fails, so don't hide the error and carry on.
- The same key must mean the same movement. If a key comes back with a different account or amount, the function throws an error. That's a bug to investigate, not a harmless retry.
- Every operation uses the session. Without
{ session }, an operation runs outside the transaction. The same applies in Mongoose, unless you've turned on itstransactionAsyncLocalStorageoption. - Operations run one at a time. The Node.js driver doesn't support parallel operations in a transaction, so don't use
Promise.allinside it.
Leave the transaction's write concern at majority. MongoDB warns that a transaction committed with w: 1 can be rolled back if the primary server fails over. Keep transactions short too: by default, they must finish in under a minute.
Step 4: Stop people from overspending
Checking the balance first and subtracting later leaves a gap. Two purchases can both see $10 and both try to spend it.
The function puts the check in the update itself:
await accounts.updateOne(
{ _id: accountId, balance: { $gte: -amount } },
{ $inc: { balance: amount } },
{ session }
)
For a debit, amount is negative, so -amount is the sum the account needs. If there isn't enough, nothing matches. The function then throws an error, and the transaction also undoes the ledger entry. No money moves, and no record claims it did.
The result is insufficient_funds if the account doesn't exist, too. Only a credit can create an account.
Step 5: Allow only one way to change a balance
A safe function only helps if everyone uses it. One quick $inc in an admin tool skips the key, the entry and the balance check.
On PlayerBay, all wallet balance changes go through the ledger. A test scans the code and fails the build if it finds a direct balance update anywhere else. We also deleted the old functions that used to change balances, so nobody can use them by mistake.
A code scan can't catch everything, such as someone editing the database by hand. Limit who has write access to production, and use the daily check in step 6 to spot anything that gets through.
To fix a mistake, add a new entry that reverses it. Don't edit or delete the original, or you'll lose the history you built the ledger to keep.
This is an example of keeping one clear owner for your data, which we cover in our guide to modular monoliths.
Step 6: Compare balances with the ledger every day
If every change went through the ledger, each balance equals the sum of its entries. This query finds the ones that don't match:
const mismatches = await db
.collection("accounts")
.aggregate([
{
$project: {
accountId: "$_id",
balance: 1,
recorded: { $literal: 0 },
},
},
{
$unionWith: {
coll: "ledger_entries",
pipeline: [
{
$project: {
accountId: 1,
balance: { $literal: 0 },
recorded: "$amount",
},
},
],
},
},
{
$group: {
_id: "$accountId",
balance: { $sum: "$balance" },
recorded: { $sum: "$recorded" },
},
},
{ $match: { $expr: { $ne: ["$balance", "$recorded"] } } },
])
.toArray()
It combines both collections, so it also finds entries whose account is missing. Starting with accounts and looking up their entries would miss those.
Money can move while the query runs, so check any mismatch again before treating it as real. This version also reads every entry, so a large ledger will need a faster approach, such as saved daily totals.
PlayerBay runs read-only money checks every day and alerts staff if they find a problem. They never change a balance. A mismatch means something went wrong, and an automatic fix could hide the cause.
If you're adding a ledger to existing balances, do it while balance changes are paused. Record one opening entry per account for whatever its history doesn't explain, without changing the balance. Investigate any difference first, and don't use opening entries to hide new mistakes.
Test what happens when things go wrong
Use a real MongoDB replica set for these tests, because a mock can't show you how transactions, indexes and competing writes behave. mongodb-memory-server can start a temporary one with MongoMemoryReplSet.
We ran these checks on the code in this guide:
| Test | Result |
|---|---|
| Send the same $25 credit 8 times at once, and repeat for 20 new accounts | Each account gets $25 and one entry |
| Try 10 debits of $1 at once from a $3 balance | 3 succeed, 7 are rejected and the balance is $0 |
| Debit an account that doesn't exist | Rejected, and no account is created |
| Reuse a key with a different amount | Throws an error |
| Use a fraction of a cent | Throws an error |
| Change a balance directly, and add an entry with no account | The daily check finds both |
These tests cover the logic, not a server failing over or how the code performs under your traffic. Test those on a setup like your production one.
What this ledger doesn't do
This is a single-entry ledger. It records what happened to each account, but not where the money came from or went. That can be enough for simple store credit.
With double-entry accounting, every movement has at least two sides that must balance. A top-up, for example, increases both the cash you hold and the credit you owe customers. Consider it if you move money between accounts, track fees and payouts, or need your records to match your bank and your accounts.
Your database also can't include a payment provider in its transaction. A card refund and a store credit update are separate steps, so use the provider's own idempotency keys and regularly compare its records with yours. Our Stripe webhooks guide covers that side.
Holding money for customers can also bring legal, tax and accounting rules. Get professional advice before you launch. A well-built ledger doesn't replace it.
Is MongoDB good for storing financial transactions?
It can be. MongoDB supports transactions across multiple documents on replica sets and sharded clusters, along with unique indexes and conditional updates. You still have to design the ledger carefully, because MongoDB won't make your entries balance for you. If you need database rules across many related records, a relational database may suit you better.
Should I store a balance or calculate it from transactions?
For most apps, do both. Keep the entries as the history and a stored balance for quick reads and safe debits. Update them in the same transaction, and compare them regularly.
How do I prevent duplicate refunds?
Give each refund a key based on its business reason, enforce it with a unique index, and save the entry and balance change in one transaction. If several routes can refund the same order in full, give them the same key. Also limit the total refunded to what the buyer paid.
Do MongoDB transactions need a replica set?
Yes, or a sharded cluster. Standalone MongoDB servers don't support transactions. For automated tests, you can run a temporary replica set with a single member.
Should I store money as a decimal or an integer in MongoDB?
Whole numbers in the smallest unit, such as cents, are a simple choice for most balances. In JavaScript, make sure amounts and totals stay within the safe integer range. MongoDB also has a Decimal128 type for exact decimals, which helps when you need fractions of the smallest unit.


