-
Cryptocurrencies
-
Exchanges
-
Media
All languages
Cryptocurrencies
Exchanges
Media
Share
Author: danny; Source: X, @agintender
Open Binance spot and perpetual, the order books are almost identical. But at the moment of "selling", there are two completely different mechanisms behind it. Why does perp maintain two sets of prices? Why does Iron Condor have to be sold on all four legs? Why is Polymarket’s fee the most expensive when p=0.5? These questions are asking about the mechanism on the surface, but they are asking about the same thing in essence - the matching engine is never an independent engineering module, it is shaped by the assets it serves.
The differences between the four forms of spot, perpetual, options and Polymarket are far deeper than the similarities. This article takes them apart and looks at the forces that fragmented Matchmaking into mostly unrelated engineering entities.
If you have only seen the matching implementation of spot trading, you may think that the "matching engine" is a mature, convergent, and almost non-technical thing - a sorted order book, a price-time priority matching loop, plus a one-time settlement path, end of the story.
Then you are dead wrong. . .
When you look from Coinbase’s BTC/USDT to Binance’s BTCUSDT perpetual contract, then to Deribit’s BTC-26DEC25-50000-C, and finally to an event market on Polymarket, you will find that the matching engines behind these four markets are almost four different machines in structure. They share a certain algorithmic similarity - they all have buyers, sellers, prices, and quantities - but when you get down to the levels of state machines, risk control couplings, transaction boundaries, and trust assumptions, the differences are so great that the word "matching engine" itself seems too abstract.
What this article wants to do is to dismantle these four typical forms and see clearly what forces make the same underlying concept differentiate into different engineering entities under different objectives.
Spot matching is a standard model, and almost all textbooks and open source projects (LMAX Disruptor, a simplified version of CME Globex, various open source matching engines) start here.
The core data structure is usually two price trees (bid side, ask side), and each price node hangs a FIFO queue. The matching loop is very straightforward: when a taker arrives, scan starts from the counterparty's best price range, consuming the maker queue in chronological order until the taker quantity is exhausted or the price crosses the limit price.
Core FeaturesThere are several key points worth mentioning:
First, assets are homogeneous and separable. The buyer holds the quote asset (USDT), and the seller holds the base asset (BTC). The essence of matching is an asset replacement. The operation on the ledger is the addition and subtraction of a pair of balances bound in a transaction, and settlement and matching are completed within the same transaction. The matching engine requires almost no external dependencies - matching is settlement, and there are no downstream links.
Second, the risk is eliminated immediately. The moment a spot transaction is completed, all position relationships disappear, and there is no continuation of the concept of "position" at the matching level. The engine does not need to care about whether your position will be liquidated due to price fluctuations in the next second, because there is no such thing as a "position".
Third, order types are relatively convergent. Limit, Market, IOC, FOK, Post-only, Stop - these are all variations on order lifecycle management.

Give a specific scenario. BTC/USDT sells the first tranche of 50,001 × 1.5 BTC (maker A placed the order at 09:30:00.100), and sells the second tranche of 50,002 × 3.0 BTC (maker B placed the order at 09:30:00.200, maker C placed the order at 2.0). A market buy order for 4.0 BTC arrives. Matching cycle: first eat all 1.5 @ 50,001 of A, then go to the next level in FIFO order - B precedes C, eat all 1.0 @ 50,002 of B first, then eat 1.5 of C (leaving 0.5 left in the book). The Taker account deducted 200,006.5 USDT and increased 4.0 BTC in the same transaction, and the three maker accounts were updated in the opposite direction. This series of operations is completed in a database transaction, and the matching is settlement. It is worth noting that B was traded before C not because of the price (same price), but because it was placed first - this is the actual embodiment of price-time priority.
The difficulty in the spot matching project is actually not logic, but performance: how to maintain microsecond-level latency under millions of TPS, how to handle the cache locality of hot and cold paths, and how to achieve deterministic replay. But these are optimization issues, not mechanism issues.
If you put a screenshot of the Binance perpetual contract order book next to the spot order book, the difference may not be visible to the naked eye. But the bottom floor is a different scene.
The key change is: the matching engine is not the end point of settlement, but just an event source. (aka a domino)
The completion of each perp matching triggers a complex downstream link: mark price update, position update, margin recalculation, unrealized profit and loss refresh, and possible liquidation trigger. The matching engine and risk engine are deeply coupled here in perp, and the coupling method determines the character of the entire system.
Dual price system is the first unique structure of perp. The matching itself is still driven by the "last traded price", but the maintenance margin, forced liquidation trigger, and UPnL calculations use the "mark price", which is synthesized from multiple spot market indices plus funding adjustment. This is an anti-manipulation design: if the matching price and the mark price are one, the attacker can use a small amount of funds to pull the order book to an extreme price, instantly triggering the liquidation of all reverse positions. The dual-track system eliminates this attack surface.
Give a specific scenario to illustrate the role of dual prices. A trader has 50x more than 1 BTC, enters the market with 60,000, initial margin is 1,200 USDT, and maintenance margin is 300 USDT. At a certain moment, the order book was instantly penetrated by a large market order to last price = 58,500 - based on last calculation, the unrealized loss was 1,500 USDT, which meant that the position was exhausted. But at the same time, the mark price (multi-spot index weighted + funding adj) = 59,400, the unrealized loss based on mark is 600 USDT, the account equity is 600 > the maintenance margin 300, and the liquidation is not triggered. Seconds later the last price returned to 59,400 and the trader was not swept away by the pin glitch. If matching and liquidation share the same last price, and an attacker uses a small sum of money to push the price to an extreme position when the order book is weak, he can trigger a series of reverse position liquidations and then buy them back at a low price - this is the type of event that frequently occurred in the early days of BitMEX. The dual-track system is not "for accuracy", but "for the sake of not being attacked".

Pre-trade risk control is another key insertion point. In spot, the taker order is matched directly as soon as it arrives; in perp, the taker order must first pass a margin check - can your available margin cover the position changes caused by this transaction? If it is cross-margin mode, this check will also consider the mutual hedging of all positions in your account. This check must be completed simultaneously in the matching cycle, otherwise there will be an inconsistent state of "it is discovered after the transaction is completed that the margin is insufficient".
The liquidated special matching channel is the most interesting part of the perp engine. When the account margin rate falls below the maintenance line, the liquidation engine will take over - it will send an IOC order to the order book at the account's bankruptcy price (or a certain protection price) in an attempt to close the position. What should I do if the order book is too thin and I can’t afford the liquidation order? There are several engineering options here: one is to access the insurance fund to cover the bottom line, and the other is to trigger ADL (automatic position reduction), and the system will forcibly reduce the position of the profitable counterparty.
ADL is essentially the "last link of matching": when the order book and insurance fund fail, the system skips the order book and directly performs forced settlement between the two accounts. This is a design that extends the concept of "matching" from "voluntary matching" to "involuntary matching" - it is no longer matching in the traditional sense, but it must exist, otherwise the system will go bankrupt in extreme market conditions.

The complication of self-transaction prevention (STP) is also perp-specific. In spot, self-transaction prevention mainly prevents order laundering; in perp, the same account can hold long and short positions at the same time (hedge mode), so the semantics of STP need to be subdivided: by sub-account, by user ID, or by master account? Different exchanges have different options.
To summarize: the "difficulty" of perp matching is not in the order book itself, but in the entire set of state machines behind the order book that are bound to the risk engine. The designer must think clearly: which checks are on the main path of matching (synchronous) and which can be asynchronous; what execution model is used for liquidation; how to accrue insurance funds; how to sort the priority queue triggered by ADL (usually sorted by "profit percentage × leverage multiple", so that those who make the most money and have the highest leverage are lightened first).
There is another layer of perp matching that deserves special discussion: This path of forced liquidation merges with ordinary orders during the matching process, but it has a completely different set of logic before and after the merger. Understanding this layer is critical when designing or debugging a perp engine - otherwise you will repeatedly blur the boundaries between "matching" and "liquidation".
Break the forced liquidation into three levels:
The first level is trigger determination. Use mark price - the purpose is that the decision "whether it should be liquidated" is not affected by instantaneous manipulation of the order book. This layer is completely separate from the depth of the field and is an independent risk control judgment.
The second level is the order structure. After the liquidation engine decides to liquidate, it constructs an IOC order and sends it to the order book. This order is structurally different from the user's ordinary order in many dimensions: the price is not selected by the user but the engine uses the bankruptcy price as the limit price; the type is always IOC and rest in book is not allowed; the handling fee is based on the liquidation rate (0.5–1.5%) instead of the taker rate, and flows to the insurance fund; the order authority belongs to the system rather than the account - when the account is liquidated, it will even be forced to cancel all pending orders on the book (to avoid contaminating the liquidation with self-contained transactions); the failure fallback is different - user IOC If it cannot be eaten, it will disappear. If the liquidated IOC cannot be eaten, it will trigger the cascade of insurance fund → ADL.
The third level is matchmaking and execution. Once entered into the order book, liquidated IOCs and ordinary IOCs follow exactly the same price-time priority rules to eat up counterparty liquidity. This layer is symmetrical, and the matching engine does not "specially treat" the matching priority of liquidated orders - the matching loop should not have such if-else, otherwise it will break the deterministic replay.
So the precise description is: The matching cycle itself is not divided into two sets, but the source, structure, billing, and failure path of the order are divided into two sets. From the perspective of the main matching path, forced liquidation and ordinary orders are equal; from a business perspective, they are two parallel channels that only merge at the matching stage.

There is another point worth noting here - mark price determines "at what price it should be liquidated" (trigger condition), but last price (market depth) determines "at what price it can actually be liquidated". When the order book is thin and the depth is completely exhausted, the actual transaction price of the liquidated IOC along the book is far worse than the bankruptcy price. This gap is the "source of profit and loss" of the insurance fund. The essence of the insurance fund is to absorb the deviation between the "theoretical clearing price given by mark" and the "actual transaction price executed on the market." If the two were always consistent, the insurance fund wouldn't need to exist at all.
A more radical design (dYdX's early backstop liquidator network) simply adds a layer of "independent counterparty channels for liquidation paths" in front of the order book - allowing backstop vaults or whitelisted liquidators to take over the entire position first, bypassing the slow path of the order book. The essence of this is to completely separate "forced liquidation execution" from on-site matching and give the liquidation path its own matching channel. Here's another way to answer the dual path question:Some exchanges think that cramming two paths into the same order book is a compromise and simply let them use different matching channels.
Back to the core of perp matching complexity: the main matching loop itself can be kept simple, but the state machines around it - risk control, liquidation, insurance funds, ADL, and possibly the backstop liquidator network - constitute a much more complex system than the order book itself. Behind the optical illusion that "the order book looks the same as the spot", there are actually two independent entrance channels and four different exit paths. This is the true form of "difficulty" in perp matching. (It is said that some exchanges have also made b books)
After seeing this, do you feel that there is a reason why you lost so much money on the perpetual contract?
Options are the only category among these four categories where the quantity of the underlying asset itself has exploded. A BTC spot market has only one order book; a BTC perpetual market has only one; but BTC options - taking Deribit as an example - have hundreds of active contracts at any point in time, which are combined from the three dimensions of strike × expiry × call/put. Each contract requires a separate order book.
This brings up the first fundamental problem:Liquidity is sparse. Deep in-the-money or out-of-the-money contracts may only have a few transactions a day, and the order book is often empty or has only two pending orders from the market maker. This sparsity makes pure LOB models almost unusable - an average buyer placing a limit order might have to wait several days for the transaction to be filled.
The industry’s solution is to mix three models:
LOB is used for the most liquid contracts, primarily ATM options and front-month contracts. This part is not essentially different from the spot logic.
RFQ (Request For Quote) is used for contracts with sparse liquidity. A trader sends a quote request, multiple market makers respond, and the trader chooses the best one. This process operates outside of LOB and matches "inquiry vs. multiple quotation responses", which is essentially a reverse auction.
Block trade is used for very large orders. The two counterparties negotiate a price off-site and report the transaction to the exchange for registration and settlement. The order book does not participate in matching, only in registration.
Simultaneous multi-leg matching is another core requirement for option matching. A common strategy - such as iron condor - involves buying and selling four different options contracts simultaneously. If four legs are matched independently on four order books, the result may be that two of the legs are completed and the other two are not, and the trader's risk exposure is completely undesirable. Therefore, the option matching engine must support combo book or multi-leg atomic execution: all four legs are either filled or not, and are processed as a whole.
Deribit's approach should be regarded as the current industry reference standard: it has an independent combo order book, and combo orders can be placed independently or implied matching with single-leg order books - the system will automatically synthesize combo prices from single-leg liquidity, and vice versa. This is a very delicate design, but it also means that the status synchronization of the "virtual order book" must be maintained on the main matching path.
Give a specific scenario to explain why multi-leg simultaneous matching is not optional. The current price of ETH is 3,000. Traders predict that it will fluctuate in the [2,900, 3,100] range in the next seven days, and construct Iron Condor: sell 3,100 Call, buy 3,200 Call, sell 2,900 Put, and buy 2,800 Put. The net income of the four legs is the maximum profit of the portfolio, and the maximum loss is strictly capped because of the protective legs - this is the premise for the establishment of the strategy. If four orders are independently submitted to four order books for matching, the most common failure scenario is: the first two orders (call spread part) are completed, ETH jumps to 2,950 in milliseconds, the counterparty quotes of the last two orders (put spread part) have become invalid, the market maker cancels the order or makes a significant adjustment, and C and D are not completed. As a result, the trader holds a naked call spread - the directional exposure is completely reversed, the original "shock benefit" strategy becomes "put put loss", and the maximum loss is no longer bounded. Combo book packages four legs into a whole: either all or nothing; implied matching further allows the liquidity of the single-leg order book to be synthesized into combo quotes in real time, and conversely the liquidity of the combo order book will flow back to the single leg, and the two layers of liquidity complement each other.

The market maker's pricing algorithm mainly uses IV Implied Volatility rather than price (which is also unique to options). Market makers will not place "50000 strike call $1500", they will place "buy at 65 vol, sell at 67 vol", and the system will use BSM (or a more complex model) to calculate the actual quote based on the current underlying price every time the quote takes effect. This means that the market maker's quotation dynamically follows the underlying price, and the order book will automatically adjust when the underlying price changes - this makes the "pending order" in options a continuous function rather than a discrete event.
Greeks-based portfolio margin makes risk control different. In perp, margin is calculated independently for each position; in options, the market maker may hold hundreds of contracts at the same time, and calculating the margin for each contract separately will make the capital efficiency so low that it cannot be operated. Therefore, options exchanges usually use a combination of margins based on Greek letters (delta, gamma, vega, theta), treat the entire portfolio as a net exposure, and calculate margins based on net Greeks. This in turn affects matching - the "margin cost" of a deal depends on whether it hedges your existing position.
Before we dive in, let’s answer a possible question: Why list Polymarket separately, and why not discuss AMM? Instead of merging it into a generalized “DEX matching” category?
Because the specificity of Polymarket is not in the "on-chain" tag. What is truly unique about Polymarket is the superposition of three mechanisms: [0, 1] price clamping + CTF complementary casting + UMA result determination (similar to mark price). These three together create a state machine form that is different from spot, perp, options and other DEXs - the price space is discrete and bounded, the source of liquidity comes out of nothing, and the life cycle has an end.
The following is based on these three mechanisms and the trust assumptions behind them.
Polymarket is a (first?) prediction market built on Polygon. All positions are ERC-1155 tokens issued by Gnosis's Conditional Token Framework (CTF). A market—such as a binary prediction of a certain presidential election—will issue two tokens: YES tokens and NO tokens, with one token worth $1 and the other worth $0 at the end of the market.
The complementary casting mechanism is the core of CTF. Anyone can deposit 1 USDC and get 1 YES + 1 NO. Anyone can also destroy 1 YES + 1 NO and redeem 1 USDC. The existence of this mechanism allows market makers to provide liquidity to the market "out of nothing" - the market maker does not need to hold tokens before they can sell them, he can cast them instantly and then sell them. From the perspective of the matching engine, this is equivalent to the market maker having an unlimited initial inventory, but the cost is bounded in the margin - this is a key difference between Polymarket and traditional CLOB.
Off-chain matching + on-chain settlement is the overall architecture of Polymarket. The specific process: the user signs a limit order with EIP-712 and sends it to Polymarket's centralized matching server; the server maintains a traditional LOB; when two orders match, the server packages the two signatures into an on-chain transaction and calls the exchange contract to complete settlement. So the matching itself is off-chain (millisecond level), but the settlement is on-chain (second level).
This architecture has a special feature at the trust level: the matching server cannot forge transactions because it does not have the user's private key; but it can review transactions - rejecting the matching of certain orders.
Gas economics shapes settlement paths rather than user behavior. A common misunderstanding is to attribute Polymarket's gas cost to the user - in fact, the gas is paid by the relayer (Polymarket's operator). Users sign orders with EIP-712, and the relayer submits the transactions in batches to the chain after matching. The gas is borne by Polymarket and is recovered through transaction fees. This means that for users, placing orders and canceling orders are free of charge - the order cancellation is not even uploaded to the chain at all, but only the matching server is notified to remove the order. The logic is not essentially different from the CEX order cancellation.
But this does not mean that gas is not binding, but the restriction is transferred to the relayer side: the on-chain settlement cost of each transaction is borne by Polymarket, and the relayer's gas budget + Polygon's throughput upper limit jointly determine the maximum transaction frequency of the system. What market makers feel when there is extreme congestion is not "expensive orders", but settlement delays and throughput bottlenecks - this is a completely different congestion transmission path from CEX.
The real shaping that this architecture imposes on the matching engine is that the relayer must be able to batch settle multiple transactions (amortize gas), while keeping each transaction independently verifiable in the settlement contract (to prevent relayer tampering or misappropriation). Therefore, Polymarket's exchange contract is designed to accept a structure of "multiple signature orders + one batch submission". Gas does not turn Polymarket into a "low-frequency market", but it makes its matching-settlement coupling method different from that of CEX and pure on-chain DEX - the matching layer completely inherits the lightweightness of CEX (millisecond order cancellation, zero gas pending order), but the settlement layer inherits the verifiability constraints of on-chain DEX.
The finality of the oracle’s result determination is the most special aspect of prediction market matching. The other three types of markets are "continuously running" - prices are always changing and the market is always open. However, the prediction market has a clear "end moment": an event occurs, the result is analyzed by the oracle (Polymarket uses UMA's optimistic oracle), YES or NO is determined (there are also times when it is argued, which will not be discussed in this article), and all positions are settled at 1:0 or 0:1. This means that the matching engine has to deal with a "market freeze" state machine: new orders are prohibited within the resolution window, challenges are allowed within the dispute window, and all trading activity is stopped after final settlement. This state machine has no counterpart in CEX spot.
Price being clamped at [0, 1] is another mechanism constraint. This may seem like an advantage (you won’t blow your position to infinity), but it means that the order book has limited space for price tiers – usually 1 cent per tier, with a maximum of 100 tiers. This is a strong constraint on the matching data structure (you can use a fixed-size array instead of a tree), but it also means that there is an upper limit on the accuracy of price discovery.

Give a specific scenario to illustrate how mint/redeem shapes market making behavior. In a certain market, YES is quoted at $0.65, and NO is quoted at $0.35 (YES + NO must be equal to $1, otherwise the arbitrageur will immediately mint or redeem to level). Market maker M wants to provide selling liquidity for this market but does not have YES in hand - he deposits 100 USDC into the CTF contract and instantly gets 100 YES + 100 NO, and sells 100 YES at 0.66 and 100 NO at 0.36. After both transactions are completed, M holds 0 net exposure and earns a bilateral spread of 0.02 × 100 = 2 USDC. This is the standard method of market making in Polymarket: use mint/redeem to replace "capital occupation" with "two-way quotation spread".
What deserves special analysis is: YES + NO = 1. This invariant matching engine does not require active maintenance. It is automatically guaranteed by the market structure through arbitrageurs. This "invariant of the market structure" does not exist in traditional LOB, and it is impossible for market makers to "sell without inventory in hand." The design of the Polymarket matching engine can therefore eliminate some of the inventory constraint checks required by CEX, but the price is that the mint/redeem path must be integrated into the settlement contract as a first-class citizen.
To summarize the specificity of Polymarket matching: the trust assumption is a mixture of "off-chain matching + on-chain settlement", the token model is the complementary casting of CTF, the price space is a bounded discrete of [0,1], the time dimension has an end, and gas is borne by the relayer and recovered through handling fees. These constraints add up to a matching engine that is completely different from the first three.
Looking at these four forms, we can extract five dimensions to explain why matching engines differentiate under different targets:

Putting the five-dimensional framework on the two dimensions of "matching-risk control coupling" and "liquidity density", the positions of the four forms are clear at a glance: spot is in the comfort zone of low coupling and high density, sustainability is in the high coupling and high density (the most complex engineering reality), options are in high coupling and low density (RFQ + combo must be used to make up for the sparsity), and Polymarket falls in the middle - the coupling degree is raised by on-chain settlement, and the density is pulled up by complementary casting.

Each dimension puts pressure on the matching engine:
The asset shape determines the quantity and sparsity of the order book. Single-dimensional homogeneity (spot, perp) requires only one book, multi-dimensional sparse (options) requires hundreds of books and must solve sparsity, and discrete complementation (Polymarket) requires "casting/redemption" to be integrated into the matching path.
The settlement sequence determines the complexity of the state machine. Instant synchronization (spot) makes matching equal to settlement; continuous accounting (perp, options) requires maintaining position status, margin status, PnL status, and updating after each matching; final analysis (Polymarket) requires the conversion of the state machine from "open" to "frozen" to "analytic".
Risk topology determines the degree of risk control coupling. Linear zero position (spot) requires almost no risk control; linear continuous exposure (perp) requires pre-trade margin check and liquidation engine; convexity (options) requires Greeks-based portfolio margin; binary bounded (prediction) requires almost no risk control (the maximum loss is the money paid).
Liquidity density determines liquidity source strategy. High-density markets can be purely LOB; sparse markets must introduce supplementary mechanisms such as RFQ, AMM, and market maker incentives.
The trust boundary determines which components must be verifiable. In CEX, all components are within the exchange; in pure DEX, all components are on the chain; in the hybrid architecture, it needs to be clear what must be on-chain (settlement), what can be off-chain (matching), and what the attack model is (cannot steal money but can be audited).
Going back to the original question - why has the "matching engine" differentiated into four almost different machines in different markets?
Because matching is never an independent engineering module, it is the product of the combined effect of five variables: the nature of the subject matter itself, the settlement model, the risk structure, the liquidity form, and the trust assumption. The matching engine is what these variables look like - if you see what matching looks like, you can in turn deduce what the financial structure of this market is like.
The simplicity of spot matching corresponds to the clean structure of "homogeneous assets + one-time settlement + zero position continuation";
The complexity of perpetual contract matching corresponds to the engineering reality of "synthetic assets + continuous exposure + risk control - deep coupling of matching";
The hybrid form of option matching corresponds to the market structure of "dimensional explosion + sparse liquidity + market maker dominance";
The on-chain and off-chain split coordinated by Polymarket corresponds to an engineering compromise between the two security goals of "no censorship" and "anti-theft".
If clearing is the conscience of the exchange, then the matching mechanism is the bottom line of the exchange.