Skip to content
Mohamed Naser
ع

Islamic Finance for Engineers: Murabaha as a State Machine

By Mohamed Naser Technical Lead, Lynk

Before the story of scaling from ten orders to five thousand, here is the machine itself: a commodity Murabaha as a state machine, where every transition is legally load-bearing and stock has to exist as individually coded units.

Islamic Finance for Engineers: Murabaha as a State Machine
  • murabaha state machine
  • commodity murabaha
  • murabaha process
  • islamic finance
  • sharia compliant financing
  • murabaha platform
  • islamic banking technology
  • tawarruq
  • SPV
  • time deposit
  • special purpose entity
  • fintech saudi arabia
  • system design

LYNK Engineering · Murabaha Platform · Part 1 of 3

About these numbers. Every figure in this series comes from LYNK's pre-production stress-test program — synthetic orders against test data — not from customer traffic, and no customer data appears anywhere in it. Screenshots are of test environments. Published with LYNK's knowledge; the opinions, and any errors, are my own.

What LYNK is, and what we do

LYNK is a Saudi fintech platform that provides the infrastructure for commodity Murabaha financing.regulator ↓ When a bank or finance company wants to extend Sharia-compliant financing to a customer — a personal loan, an SME facility, a credit card settlement — the funds cannot simply be lent at interest. Instead, the financing must be structured as a real trade: the institution buys a genuine commodity, sells it to the customer at cost plus an agreed profit (the Murabaha), and the customer sells it on for liquidity.standard ↓ LYNK is the marketplace and execution engine that makes that entire trade real, digital, and fast.

In practice, we operate three things:

  • A commodity marketplace. LYNK runs a local commodity market where approved suppliers list real inventory — steel, gasoline, and other qualifying goods — tracked down to the individual unit, with live availability and pricing. For institutions that prefer international commodities, LYNK also integrates directly with Bursa Malaysia's Suq Al-Sila' (BSAS) commodity trading platform.
  • An execution engine. Financial institutions create Murabaha orders through the LYNK portal or entirely through our API from their own loan-origination systems. Orders can run in manual mode, where an officer confirms each step, or in AUTO mode, where the whole cycle — purchase, ownership transfer, sale, completion — executes without human intervention.
  • The record of the trade. Every step produces its legal evidence: purchase confirmations, wakala (agency) agreements, ownership certificates, and sell confirmations.

One machine, many financial products

The same Murabaha machinery serves very different financial products. What changes between them is who the parties are and what the financing is for — never the legal sequence of the trade itself:

ProductLenderBorrowerWhat it serves
Normal lending The financial institution The institution's customer Classic Murabaha: personal finance, SME facilities, credit-card settlement
SPV (Special Purpose Vehicle) An SPV — a separate legal entity the institution creates to isolate financial risk The financial institution itself Structured finance: large or specialized Murabaha deals, ring-fenced from the institution
Time deposit A client placing funds with the institution for a fixed term The financial institution itself A Murabaha-based investment: the deposit earns profit through Murabaha — the Sharia-compliant alternative to an interest-bearing term deposit
SPE (Special Purpose Entity) An external third party An external customer Murabaha execution as a service: the institution manages the entire transaction between two independent parties without being either party to the contract

Our clients are the financial institutions; their customers are the borrowers and depositors; the suppliers and traders provide the commodity side of the market; and LYNK administrators oversee the whole exchange. The platform's job is to let an institution turn "approve this financing" into a completed, fully documented, Sharia-valid trade — in seconds.

The Murabaha process — and why every step must happen

A commodity Murabaha on LYNK is a sequence of real transactions, each with a distinct legal meaning. Nothing in this sequence is ceremonial; each step transfers actual ownership of actual commodity units, and each must complete before the next may begin.saga ↓

Five-panel process flow: order created and approved; purchasing commodity on the open market with an institution ownership certificate; borrower ownership at cost plus profit with deferred instalments; sale to market through a wakala agreement to a genuinely different buyer; Murabaha completed with funds disbursed and units settled back to the market.
The commodity Murabaha (tawarruq) process flow: five steps, each a real transaction with its own legal evidence. Ownership of real commodity units moves market → institution → customer → market, with payment flowing back at each hop — and the sequence cannot be reordered.
  1. Order created & approved The institution submits the financing order — amount, customer, market, commodity preferences. Depending on its roles setup, a supervisor approves it. A trade request is born.
  2. Purchasing Commodity The platform finds eligible commodity units on the market that cover the financing amount, places them on hold, and executes the purchase. The institution now genuinely owns specific, identified units of a real commodity. Sharia requires this ownership to be real — you cannot sell what you do not own.
  3. Borrower Ownership The institution sells the commodity to the customer at cost plus the agreed profit, payable in instalments — this sale is the Murabaha. Ownership of the units transfers to the customer, evidenced by certificate.
  4. Sale to market The customer — typically through a wakala appointing the institution or platform as agent — sells the commodity back to the open market for cash. This provides the liquidity the customer needed. The commodity must move to a genuinely different buyer, which is why trade-rotation rules and, in newer flows, a Specialized Entity govern who may buy it.
  5. Murabaha Completed & settlement Funds flow to the customer, certificates are finalized, the order completes, and the commodity units settle back into the market's books, ready to serve a future order.
LYNK's Murabaha Details screen showing all five steps completed with green checkmarks: Purchasing Commodity in 1 second with its commodity certificate, Contract Signed in 28 seconds confirmed via API by the lender, Borrower Ownership Certificate in 0 seconds with its certificate, Client Wakala in 0 seconds, and Murabaha Completed in 0 seconds with the sell confirmation certificate — on 15 August 2026.
The process as users see it: a real order completing every legal step, with a downloadable certificate generated at each transfer of ownership. The platform's own steps are near-instant — Purchasing Commodity in 1 second, Borrower Ownership, Client Wakala, and Murabaha Completed in 0 seconds each. The only wait, 28 seconds at Contract Signed, is the lender confirming through their own API — the customer's time, not the machine's.

Stock is code — and every code must be traceable to its owner

The deepest consequence of the legal structure sits in how stock exists at all. On LYNK, a supplier's registered stock is not a quantity in a column — it is minted into individual units, each represented by its own unique code. Sharia requires the sale of identified, specified goods, not an abstract balance: when an institution buys "500 units of steel," it must be knowable which 500 units, and when the customer takes ownership, those exact coded units must now belong to that customer.

A busy commodity warehouse with tall racks of stock and workers moving pallets.
A commodity market is a real warehouse before it is a database. LYNK's job is to give every unit on those shelves a code, an owner, and a history.

So every unit lives as its own record carrying its code, its status (free or reserved), which order is holding it, who owns it now, and who owned it before. And every time ownership changes hands, the database itself — via a trigger, so no code path can forget — appends a row to an append-only ownership ledger. Pick any unit code, at any time, and the platform can replay its full legal history: supplier → institution → customer → market, order by order.

Supplier stock e.g. 500 units of steel minted one row per unit, each with a unique code UNIT 8FA3-72 status: FREE owner: Supplier S-014 UNIT 8FA3-72 status: RESERVED · hold_for #812 owner: Supplier S-014 UNIT 8FA3-72 status: FREE · settled owner: Customer C-1042 held owned every ownership change fires a DB trigger… OWNERSHIP LEDGER · APPEND-ONLY 8FA3-72 · Supplier S-014 → Institution L-001 · order #812 · purchase 8FA3-72 · Institution L-001 → Customer C-1042 · order #812 · murabaha sale 8FA3-72 · Customer C-1042 → Open market · order #812 · sale for cash any code, any time → full legal chain of ownership
Stock as code: supplier inventory is minted into individually coded units. Each unit tracks its status, the order holding it, and its current and previous owner — and a database trigger appends every ownership change to an append-only ledger, so any unit's code replays its complete legal history.

This design is what makes the platform legally sound — and it is also one of our hardest engineering challenges. A single financing order holds hundreds or thousands of units; five thousand concurrent orders means millions of unit rows being held, transferred, and settled at once, where two orders must never hold the same unit — not even for a millisecond — and where losing a single ledger entry would break a chain of ownership that has to stand up to audit. Much of the scaling story in Part 2 — the lock contention, the index engineering, the race-condition hunts — is really the story of keeping this per-unit, per-user tracking intact under industrial load.

The constraint we cannot optimize away Every performance engineer's instinct — skip the step, batch the work, fake the intermediate state, reorder the sequence — is forbidden here by design. The purchase must precede the sale. The units must be individually identified and genuinely held. The ownership chain must be complete and documented. A Murabaha with a shortcut in it is not a slow transaction; it is an invalid one. Sharia compliance is a hard correctness constraint, exactly like double-entry accounting — so all throughput must come from architecture, never from relaxing the rules of the trade.

The goals: what "a better platform" means for LYNK

Institutions do not create Murabaha orders one at a time. A consumer-finance company disburses hundreds of loans in a morning; a bank settles credit-card Murabaha in bursts; campaign days multiply everything. Our definition of a better platform therefore comes down to two primary goals, in tension with each other:

Goal 1 — Maximize the number of transactions we can handle at one time

Every concurrent order competes for the same commodity inventory, the same database rows, and the same workers. Capacity is not one number but a system of targets we test against continuously:

TargetMeasureWhere we've proven it
Concurrent volume5,000+ orders per runRoutine daily pre-production stress tests; 5,200 end-to-end
Per-order speedsub-second stepsPurchase averages 0.26s, P99 within 1s — see "How we test our performance" below
Reliability≥ 99.9% completion99.92–100% across 2,500–5,200-order campaigns
API responsiveness~1.2s create-orderMeasured while 5,000 orders flowed through the pipeline
Autonomyzero-touch runsFull AUTO cycle incl. Auto Complete Sell, unattended

Goal 2 — Every transaction must be Islamically legal

The second goal bounds the first. Whatever the load, each of those thousands of orders must individually satisfy the full legal sequence: real units found, genuinely held, actually purchased, ownership truly transferred, sold onward to a legitimately distinct buyer, and every link evidenced by certificate. This has concrete engineering consequences:

  • Strict per-order sequencing. Each order's pipeline is a state machine whose steps cannot be skipped or reordered — parallelism must come from running many orders side by side, never from cutting corners inside one.
  • Real inventory, really held. Units are locked and tracked individually; two orders may never "own" the same unit, even for a millisecond, which is why hold/lock logic and race-condition work dominate our database engineering.
  • Evidence as a deliverable. Certificates and ownership records are legal artifacts.
  • Rules even in the fast path. Trade-rotation limits and the Specialized Entity flow exist so the onward sale is genuinely valid. When we tested relaxing rotation from 2 to 1, the change was justified to the business on Sharia-structure grounds — and only adopted after tests proved performance was unaffected either way.
#1 #2 #3 ⋮ ×5,000 CreatePurchaseOwnershipSellComplete CreatePurchaseOwnershipSellComplete CreatePurchaseOwnershipSellComplete holds units — exclusively Shared commodity inventory — each unit belongs to at most one order at a time
Where the two goals meet: throughput comes from running thousands of pipelines side by side, while Sharia validity forces every pipeline through the same strict sequence — and all of them compete for exclusive holds on the same pool of real commodity units.
The thesis of this series A platform that is fast but cuts legal corners is worthless, and a platform that is compliant but handles ten orders is a prototype. LYNK's engineering story is the pursuit of both at once: industrial throughput for transactions whose every step is a genuine, documented, Sharia-valid trade.

How we test our performance

Claims like "seconds per step" mean nothing without a way to prove them — so performance testing is a standing routine, not an occasional event.test types ↓ Thousands of orders are created through the API in controlled pre-production runs (today's standard is 5,000 orders per run, daily), every order records how long each Murabaha step took, and each run is distilled into the same set of statistics per step. Every change to the platform is judged against that historypercentiles ↓: if the numbers move the wrong way, the change is caught within days.

A presenter pointing at a large bar chart on an easel.
Every test run ends the same way: someone pointing at a chart. The numbers below are what we point at.

How to read the numbers

The fairest way to describe thousands of order timings is to imagine lining every order up, fastest to slowest, and reading values off that line:

  • Min / Max — the single fastest and single slowest order in the run. Max shows the worst thing that happened to anyone.
  • Avg (average) — total time divided by number of orders. Useful, but it hides outliers: a thousand fast orders can bury ten terrible ones.
  • P25, P50, P75, P90, P95, P99 (percentiles) — "P" followed by a number reads as: that percentage of orders finished within this time. P25 = the fastest quarter of orders; P50 is the median — the typical order, half faster and half slower; P99 means 99 of every 100 orders were at least this fast — only 1 in 100 was slower. P90/P95/P99 describe the unluckiest customers' experience, which is exactly what averages hide — so those are the numbers we hold ourselves to.
MIN P50 P90 P99 MAX every order in the run, sorted fastest → slowest the slow tail — what averages hide
Percentiles, visually: sort every order in the run from fastest to slowest. P50 is the middle of the line (the typical order), P90 leaves only the slowest 10% to its right, and P99 sits at the edge of the slow tail — the amber bars an average would quietly smooth away.

Here is what those statistics look like from a real run today, for the three fully automated steps (values in whole seconds — a "0" means the step completed in under a second):

Step Performance Results from a stress-test run. Purchase: min 0, avg 0.26, max 3 seconds; P25 and P50 are 0.0 and P75 through P99 are 1.0. Borrower Ownership: min 0, avg 0.03, max 1; every percentile 0.0 except P99 at 1.0. Sell: min 0, avg 0.04, max 1; every percentile 0.0 except P99 at 1.0.
A real run's report card. Reading Purchase: the typical order (P50) finished in under a second, the average was 0.26s, 99 of every 100 orders (P99) finished within 1 second, and the single worst order of the whole run (Max) took 3 seconds. Borrower Ownership and Sell average 0.03–0.04s with even their P99 at 1 second. Two years ago the purchase step alone averaged nearly 12 seconds with a worst case of 65 — Part 2 tells that story.

None of this came easy

Everything described above — five legal steps in seconds, millions of tracked units, four products on one pipeline — is where the platform ended up. It is not where it started. In January 2025, a test of just ten automated orders left four of them stuck. Between that day and today's routine 5,000-order runs stand fifteen hard-won battles — the first ten fought in the code and the database, the last five in the infrastructure underneath it:

  • CASE 01Everything waited for everything. The first order couldn't purchase until all 49 others finished searching — and the first "stuck orders" root cause was a disk at 98%.
  • CASE 02The database fought back. Deadlocks and lock timeouts that took three rounds of fixes — the last one cut the worst order from 65s to 14s.
  • CASE 03A timeout nobody knew existed killed the first 11 orders of a 300-order run — and triggered a summer-long campaign on the purchase path.
  • CASE 04Every certificate cost a browser session. Tuning Chrome bought headroom, a PHP engine bought — but the winning move was a business decision: generate on demand, and the cost per step fell to 0 seconds.
  • CASE 05"Which units can this customer even buy?" — answering it scanned millions of rows per order, until a settled flag, and finally a precomputed eligibility ledger, made it a 0.1s lookup.
  • CASE 06Cover 1,000,000 exactly, using only the units this institution is allowed to hold. Two algorithms and a harness of invented markets later, the search answers in milliseconds — with a hard 3-second stop.
  • CASE 07The platform attacked itself: one job dispatched 22,400 times in hours, one query executed 114,000 times — fixed for an 85% query reduction.
  • CASE 08A bug-fix quietly added 2 seconds to every order — caught within a week, only because a baseline existed.
  • CASE 09The unit ledger under siege: 94 million reads on one index, race conditions on exclusive holds, and a caching experiment that had to be rolled back.
  • CASE 10Everything is a job — and jobs died silently. No retries, no overlap guards, locks that never expired: a transient blip froze an order, and two servers could grab the same work. Retry with escalating backoff became the road to 0 failed transactions.
  • CASE 110.5 seconds of work inside a 7.5-second step — the latency was hiding between the jobs, and fixing it made another step 3× slower before it made everything faster.
  • CASE 12Every split leaves something new to run. 3 worker containers became 122 processes across 22 queues — including one pinned forever at a single worker, on purpose.
  • CASE 13The workers were running last month's code. Jobs finished, follow-ups never started, and no error was raised anywhere — every deploy had been updating the web tier and none of the workers.
  • CASE 14The boring failures: full disks (twice), a 32,000-company integer overflow, and connection exhaustion at full worker scale.
  • CASE 15Three machines became two at identical queue concurrency — after discovering one node had been serving 100% of the traffic while another sat out of rotation for six months.

Further reading

This series names more than it can teach — a contract type here, an isolation level there, a queueing effect somewhere else. Where a term is carrying real weight in the text above, this is the primary source to go and read properly, rather than a summary of a summary. Every link was checked when this was published.

  • Murabaha and tawarruq as contracts. The step order this platform enforces is not an implementation preference — it comes from the contract standards themselves, in particular Shari'ah Standard No. 8 (Murabaha) and No. 30 (Monetization / Tawarruq). AAOIFI Shari'ah Standards.
  • The supervisory side of it. What a Saudi financier is actually regulated against: Saudi Central Bank (SAMA) rules and instructions, with the cross-border prudential standards at the Islamic Financial Services Board.
  • Why one order cannot be one database transaction. A Murabaha order spans minutes, several parties and an external signature, so it is a long-lived business transaction with compensating steps — described first in Garcia-Molina and Salem's "Sagas" (1987) and restated for services as the saga pattern.
  • Doing a step exactly once while still retrying it. Every step in this flow is retried, and none of them may happen twice. The clearest short treatment of idempotency keys is Stripe's idempotent requests.
  • Why the numbers here are percentiles, not averages. Dean and Barroso, "The Tail at Scale" — why the slowest 1% of requests decides what users think of a system.
  • What a stress-test program is shaped like. Smoke, load, stress, soak and spike tests, and what each one is for: Grafana k6, test types.
  • The rest of the series. Parts 2 and 3 carry their own reading lists — MySQL locking, isolation and indexing in Part 2; queues, worker fleets and deploys in Part 3.

← Blog