Skip to content
All posts
marketplacecommissionmysqlledgerconcurrency

Marketplace Commission Tiers and a Ledger That Stays Correct

November 12, 2026 11 min read· Mahmoud Makhlouf
اقرأ هذا المقال بالعربية

On a B2B elevator-parts marketplace, a single elevator machine or controller can be a 300,000 EGP line on one order. Under our first commission rule, the platform earned 1,000 EGP on that line. Under the most common alternative, it would have asked for 15,000 EGP, which gives the buyer every reason to call the supplier directly next time.

Short answer: charge commission in brackets, the way income tax works. Each rate applies only to the slice of the price inside its band, so commission keeps growing with order size while the effective rate falls. Earn it when delivery is confirmed, not at checkout. Then record it in a ledger that serializes writes per seller, or concurrent deliveries will quietly corrupt the running balance.

The business problem: one rate cannot fit a 2,000 EGP part and a 500,000 EGP part

Most marketplaces start with one number: "we take 5%." That works when baskets are similar in size. B2B trade is different. On MONTRA, our own B2B marketplace for elevator spare parts in Egypt, the same supplier sells door contacts that cost a few hundred pounds and traction machines that cost hundreds of thousands.

A flat rate fails at both ends:

  • On large tickets it is too expensive. 5% on a 300,000 EGP part is 15,000 EGP. At that size the buyer and the supplier have every reason to finish the deal off the platform, and the platform loses the order entirely.
  • A cap fixes that, then breaks your revenue. Our first scheme was 3% with a 1,000 EGP ceiling. It looked reasonable in a spreadsheet. But the cap is reached at about 33,300 EGP, and above that every extra pound earns nothing. On a 500,000 EGP line, 1,000 EGP is 0.2%. The biggest, most valuable orders on the platform were the ones that paid least, and nothing in the dashboard flagged it, because every individual number looked "correct".

Your options, side by side

Here are the three common shapes, applied to the same item prices. The bracket column uses the bands we run on MONTRA: 5% up to 25,000 EGP, 3% from 25,000 to 100,000 EGP, and 1.5% above 100,000 EGP.

Item price (EGP)Flat 5%3% capped at 1,000Brackets 5 / 3 / 1.5%
10,000500 (5%)300 (3%)500 (5%)
100,0005,000 (5%)1,000 (1%)3,500 (3.5%)
300,00015,000 (5%)1,000 (0.33%)6,500 (2.17%)
500,00025,000 (5%)1,000 (0.2%)9,500 (1.9%)

The 300,000 EGP case works out like this: the first 25,000 at 5% is 1,250; the next 75,000 at 3% is 2,250; the remaining 200,000 at 1.5% is 3,000. Total 6,500 EGP.

What each option means for the business:

  • Flat percentage. Simplest to explain. Fine for B2C baskets of similar size. Pushes large B2B deals off the platform.
  • Percentage with a cap. Protects big buyers, but revenue flattens above the cap point. If most of your value sits in big tickets, you are subsidizing your best customers.
  • Brackets (marginal bands). Commission always rises with the order, so the platform never earns less on a bigger deal. The effective rate falls, so large buyers still get a fair price. Everyone already understands tax brackets, which makes it easy to explain to sellers.

Brackets also have no cliffs. Crossing 25,000 EGP does not reprice the whole item at 3%; only the pounds above 25,000 get the lower rate, so nobody gains by splitting or merging orders to land in a cheaper band.

How we built it in MONTRA

On MONTRA the supplier lists their own price. The platform's commission is calculated on that supplier price, line by line, and added on top to form the price the buyer sees (with a minimum-margin floor so the platform never sells at cost). The supplier's number is never touched.

Three business rules shaped the rest of the design:

  1. Bands are a setting, not code. The bands live in a system setting as a small JSON array. Admins can change them without a deploy, and the admin panel shows example commissions for sample prices. The validator rejects bands that are out of order, a rate outside 0 to 1, or a last band that is not open-ended. If the setting does not exist yet, the engine creates it with the recommended defaults.
  2. Commission is earned on delivery, not at checkout. An order can be cancelled, partly fail delivery or change before the goods arrive. We accrue commission only when the sub-order is delivered, which on MONTRA is anchored to a delivery note.
  3. One balance per supplier, in both directions. Sometimes the supplier collects cash on delivery, including the platform's cut, so the supplier owes the platform. Sometimes the platform holds money for the order (a deposit or a prepayment), so the platform owes the supplier. Both go into one signed running balance.

Delivery notes are the trigger

Each sub-order (one supplier's part of a customer's order) gets exactly one delivery note, enforced by a unique constraint in the database. The note lists items and quantities and carries no prices, so it can be handed to a site engineer or a building manager without exposing margins.

A note can be confirmed four ways: the supplier confirms, the customer acknowledges receipt, an admin overrides, or it auto-confirms after a 48-hour timeout. Confirmation is what accrues the commission.

For money the platform is holding, we wait longer. A supplier can mark their own delivery done, but held money is not paid out to them until the customer acknowledges the note, an admin confirms it, or a configured hold period passes.

delivery note for one sub-order: item names and quantities, no prices, confirmation status and who confirmed itdelivery note for one sub-order: item names and quantities, no prices, confirmation status and who confirmed it

Monthly invoices and credit limits

Accrued commission rolls into a monthly commission invoice per supplier, generated on the first of each month (Cairo time). A daily job checks overdue invoices. Suppliers can carry a credit limit; when the outstanding balance reaches it, they stop receiving new order assignments until it comes back down, and both the supplier and the admins are notified.

Our first version handled cash-on-delivery differently: when a supplier confirmed cash, the system wrote two payment records, one for client to platform and one for platform to supplier. It described the money flow, but it could not express "the supplier already holds our share". We replaced it with the signed ledger, where held money is booked first and dues second, so the running balance never shows a "you owe us" step that never happened.

supplier balance page: running balance, accrued commission entries, held-deposit entries and the current monthly invoicesupplier balance page: running balance, accrued commission entries, held-deposit entries and the current monthly invoice

Under the hood: the bracket function

The calculation is small. Each band charges only its own slice:

function bandedCommission(price: number, bands: Band[]): number {
  if (!Number.isFinite(price) || price <= 0) return 0;
  let commission = 0;
  let floor = 0;
  for (const band of bands) {
    const ceiling = band.upTo ?? Infinity;   // last band is open-ended
    const sliceEnd = Math.min(price, ceiling);
    if (sliceEnd > floor) commission += (sliceEnd - floor) * band.rate;
    if (price <= ceiling) break;
    floor = ceiling;
  }
  return commission;
}
// bandedCommission(300_000, defaults) === 6_500

The interesting engineering was never the formula. It was keeping the ledger right.

Under the hood: the ledger race we hit on MySQL

The commission ledger is append-only. Every entry stores balanceBefore and balanceAfter, and each new entry builds on the previous entry's balanceAfter. That chain is what makes the ledger auditable: you can replay it from zero and every step must add up. A daily job does exactly that for every supplier and alerts admins if any step is off.

The problem appears when two writes for the same supplier happen at once. Two deliveries confirmed in the same second, or a delivery and a reversal, or an invoice payment and a waiver:

T1 (delivery A)                     T2 (delivery B)
read latest entry -> balance 4,000
                                    read latest entry -> balance 4,000
insert: 4,000 -> 4,500
                                    insert: 4,000 -> 4,700
commit                              commit

Chain now: 4,000 -> 4,500, then 4,000 -> 4,700   (forked)
Stored balance: 5,200                              (still right)

The supplier's stored balance used an atomic increment, so the total stayed correct. The chain did not: two entries claimed the same starting point. Right totals over a wrong history is the worst kind of money bug: nothing breaks until someone audits.

Fix 1: serialize per supplier

Every code path that writes to a supplier's ledger now locks that supplier's row first:

export async function lockTraderLedger(tx, traderId: string) {
  await tx.$queryRaw`
    SELECT id FROM trader_profiles WHERE id = ${traderId} FOR UPDATE`;
}

The second transaction now waits for the first to commit. We also fixed a lock order (sub-order row, then supplier row, then commission records) so different writers cannot deadlock each other.

Fix 2: the lock was not enough on its own

After adding the lock we could still fork the chain. The cause is how InnoDB reads under its default isolation level, REPEATABLE READ. MySQL's documentation is explicit: all consistent (plain) reads in a transaction read the snapshot established by the first such read. Changes committed by other transactions after that point are invisible to plain SELECTs.

Our accrual reads the sub-order before it reaches the supplier lock. That first read fixes the snapshot. The transaction then waits on the lock while the other transaction appends its entry and commits. When it finally gets the lock and does a plain "read latest entry", it reads from its old snapshot and gets the same stale entry. The lock serialized the writers, but the second one was still looking at the past.

The fix is to read the latest entry with a locking read. MySQL's manual states that SELECT ... FOR UPDATE reads the latest available data and sets exclusive locks on the rows it reads:

const rows = await tx.$queryRaw`
  SELECT balanceAfter, createdAt FROM commission_ledger_entries
  WHERE traderId = ${traderId}
  ORDER BY createdAt DESC, id DESC
  LIMIT 1
  FOR UPDATE`;

We applied the same rule to the "already accrued?" flag on the sub-order, which is also read with FOR UPDATE, so a delivery confirmation and a retry cannot both accrue.

The smaller edges

  • Equal timestamps. Two entries in the same millisecond have no defined order when read back by createdAt. Each new entry gets a timestamp strictly after the previous one.
  • Paying an invoice. Marking an invoice paid decrements the balance by the invoice amount. It never overwrites the balance with a value computed earlier, because a new commission may have accrued between issuing the invoice and paying it. A regression test covers exactly that case.
  • Crashes between steps. The delivery status commits first and the accrual runs in its own transaction. If the process dies in between, a reconciliation job every 30 minutes finds delivered sub-orders with no accrual and re-runs it. Because accrual is idempotent (row lock plus the flag re-check), running it twice is safe.

For the general patterns behind this (idempotency keys, append-only ledgers, serialization), see our guide on handling money correctly with idempotency and ledgers.

admin commission ledger for one supplier: entries with balance before/after, entry types, and the integrity check statusadmin commission ledger for one supplier: entries with balance before/after, entry types, and the integrity check status

Checklist: if you are designing marketplace commission

  1. Model commission against your real order-size distribution. Put your 10 largest orders through each scheme before you pick one.
  2. If you use a cap, compute the order size where it kicks in and how much revenue sits above it.
  3. Prefer marginal brackets for B2B. Make sure only the slice above a threshold gets the lower rate, with no whole-order repricing.
  4. Store bands as validated configuration, with a known, safe fallback if someone saves a broken value.
  5. Decide what event earns commission (delivery, acceptance, end of a return window) and make it a recorded document, not a status flag someone can flip.
  6. Use one signed balance per seller for both directions of money, and book held money before dues.
  7. Make every ledger writer lock the seller row before reading the previous entry, and use a locking read for that entry if you run MySQL under REPEATABLE READ.
  8. Replay the ledger chain on a schedule and alert on any mismatch.

Frequently asked questions

What is a tiered commission structure for a marketplace?

It is a commission where different rates apply to different slices of the price, like income-tax brackets. For example, 5% on the first 25,000, 3% on the next 75,000 and 1.5% on the rest. The commission always grows with the order, while the effective percentage goes down.

Is a commission cap a good idea?

A cap protects large buyers, but above the cap point the platform earns nothing extra. If big orders carry most of your volume, a cap can leave you earning a fraction of a percent on your best deals. Brackets give big buyers a lower effective rate without flattening revenue.

When should a marketplace record commission as earned?

When the goods are delivered and the delivery is confirmed, not at checkout. Before delivery, the order can still be cancelled or fail. Tying accrual to a delivery note gives you a document to point to if a seller disputes a charge.

Why does SELECT FOR UPDATE matter for a ledger in MySQL?

Under InnoDB's default REPEATABLE READ isolation, plain reads use a snapshot taken at the transaction's first read. A transaction that waited for a lock can still read a stale "last entry" from that snapshot. A locking read returns the latest committed row, so each new entry builds on the true previous balance.

Does a row lock slow the marketplace down?

The lock is per seller and held only for the few statements that append to that seller's ledger. Writes for different sellers run in parallel. Only simultaneous money events for the same seller wait for each other, and those are exactly the ones that must not overlap.

Next step

If you run or are planning a marketplace, start by putting your largest real orders through each commission shape in a spreadsheet. The numbers usually make the decision. If you also want the ledger, delivery evidence and invoicing built properly from day one, send us a short project brief and we will tell you what it involves for your case. For the wider picture, see the MONTRA case study and our marketplace MVP checklist for spare parts.

// Let's build

Have a product in mind? Get a clear plan and a free 15-minute intro call.

Tell us what you're building. We'll come back with an approach, a rough timeline, and a ballpark — usually within 24 hours.

Book a free discovery call WhatsApp