All notes

A delivery app where every order nets to zero: building Jaylak's money ledger

· 6 min read

Cash on delivery, prepaid transfers, wallet coins and promo codes all flow through one rule: every order's ledger entries must sum to zero, or the transaction rolls back.

Jaylak is a food, pharmacy and grocery delivery platform in Ashmoun, Menoufia. Most customers pay cash at the door. Some pay by bank transfer before the driver leaves. Some pay part of the total with wallet coins. Some orders use a promo code, and the merchant pays for part of that discount. Some merchants deliver with their own driver, and some customers pick up at the counter.

Every one of those cases moves money between four parties: the merchant, the driver, the customer and the platform. If I had put a balance column on each of them and updated it in the API, I would have to trust that every code path added and subtracted correctly forever. I did not want to trust that.

So Jaylak has a double-entry ledger, and one rule that nothing is allowed to break.

The rule: every order nets to zero

When an order is delivered, the API writes one row per money movement into ledger_entries:

party direction reason
merchant credit order_items
merchant debit commission
driver debit cash_collected
driver credit delivery_fee
platform credit platform_earnings

credit means the platform owes that party. debit means the party owes the platform. On a normal cash order the driver owes the cash they collected, the merchant is owed the items minus commission, the driver is owed their delivery earnings, and the platform keeps the rest.

Add the credits, subtract the debits, and the result must be exactly zero. The service checks that right after the insert, inside the same database transaction:

async function insertBalanced(tx, orderId, entries) {
  const posted = await tx`insert into ledger_entries ${tx(entries)} returning direction, amount`;
  const net = posted.reduce(
    (sum, row) => sum + (row.direction === 'credit' ? 1 : -1) * piastres(row.amount),
    0,
  );
  if (net !== 0) throw new Error(`Ledger for order ${orderId} does not balance: ${net} piastres`);
}

If the numbers do not balance, the error rolls back the whole delivery. The order stays undelivered and nobody's balance moves. A bug shows up as a loud failure on one order, not as a quiet drift in hundreds of balances that someone finds at the end of the month.

Money is an integer

The first bug in most money code is 0.1 + 0.2. Jaylak never does arithmetic on floats. Every amount is converted to piastres (1 EGP = 100 piastres) and every percentage to hundredths of a percent, as plain integers:

// "125.50" -> 12550. Throws on anything that is not a decimal with at most two places.
export const piastres = (value: number | string): Piastres => parseHundredths(value, 'money');

Percentages round half away from zero, the same way PostgreSQL's round() does, so the API and the database never disagree by one piastre about a commission.

One rule, many payment shapes

The real value of the zero-sum rule shows up when the business adds a new way to pay. Each new case is just a different set of rows that still has to sum to zero:

  • Prepaid transfer to the merchant. Nobody collects cash at the door. The merchant holds the whole total and hands the driver the delivery fee at pickup, so the merchant owes the platform the total minus that fee, and the driver owes the fee.
  • Wallet coins. The part paid from the wallet is a customer debit (wallet_spend). Whoever collects (driver, merchant or transfer) collects only the rest. Every other row is unchanged.
  • Pickup or the shop's own driver. No Jaylak driver is involved. The merchant holds the whole total and owes the platform its commission and fees.
  • Promo codes. The merchant's share of the discount is its own promo_discount debit, so the platform does not quietly absorb it.

When wallet coins came later, the cash and transfer rows stayed exactly as they were. Wallet coins added one row type, and the balance check proves on every delivery that the other cases still add up.

Freeze the numbers on the order

A ledger is only as good as the amounts it reads. If a merchant changes their commission rate on Tuesday, an order placed on Monday must still settle at Monday's rate. Jaylak copies every amount onto the order when it is placed (items total, delivery fee, commission, the merchant's share of the discount, driver earnings, wallet amount), and the ledger only reads those frozen copies.

Never post the same money twice

Drivers lose signal. Phones retry. A driver tapping "Delivered" on a weak connection can send the request twice, and the second one must not pay anyone twice.

Every endpoint that creates money or order state requires an Idempotency-Key header: a fresh UUID per user action, reused on every retry of that action. The key is inserted in the same transaction as the write it protects:

insert into idempotency_keys (key, user_id, route, request_hash)
values ($1, $2, $3, $4)
on conflict (user_id, route, key) do nothing
returning key;
  • No row returned means another request already claimed this key. The API returns the stored response instead of running the write again.
  • Two requests that arrive at the same moment both try to insert. One wins and the other waits on the uncommitted row, then replays the winner's response.
  • If the write fails, the key rolls back with it, so a failed request never burns its key.
  • The key is stored with a SHA-256 hash of the request body. The same key with a different body is rejected, so a client bug cannot reuse one key for two different payouts.

Corrections are new rows, not edits

Ledger rows are never edited or deleted. A wrong charge is fixed with an adjustment: a new entry tied to the same order and party. Only the owner can post one, and every adjustment is written to the audit log. The history shows what happened and what fixed it.

The only field that changes later is settlement_id. When a merchant or driver is paid out, their unsettled entries for that period are attached to one settlement with a gross, a deduction and a net. The index on (party, party_id) where settlement_id is null makes "what do we still owe this merchant?" a cheap query.

What I would tell you before you build one

  1. Write the zero-sum check before the second payment method. It costs a few lines and it catches the bugs you have not written yet.
  2. Keep money in integers from the first request. Converting a live system later is painful.
  3. Freeze prices on the order. A ledger that reads current prices settles yesterday's orders at today's rates.
  4. Make retries safe in the database, not in the client. The idempotency key has to live in the same transaction as the write, or a crash between the two brings back the double payment.
  5. Append, never edit. The day a merchant disputes a payout, the full history is the only thing that ends the argument.

None of this is clever. It is a set of boring rules, and the database enforces each one, so every order in Jaylak's history adds up to zero.