DEX Architecture Explained: How Modern Decentralized Exchanges Actually Work Under the Hood
Most articles about decentralized exchanges describe what they do. This one describes how they work.
If you are a developer evaluating DEX architectures, a protocol team deciding how to build or integrate an exchange, or a technically curious trader who wants to understand what is happening between your order submission and your fill confirmation, this is the article I wish existed when we started building KalqiX.
I will walk through the four major DEX architecture models that exist today, explain the engineering tradeoffs of each, and describe why we chose the architecture we did.
The Four DEX Architecture Models
Every decentralized exchange in production today fits into one of four architectural categories. They differ in where orders are stored, where matching happens, where settlement occurs, and how correctness is verified.
Model 1: On-Chain AMM (Uniswap, Curve, PancakeSwap)
This is the model that made DeFi trading possible. It is also the simplest to understand architecturally.
How it works:
A smart contract holds reserves of two tokens in a liquidity pool. The price relationship between the tokens is determined by a mathematical invariant, typically the constant product formula (x * y = k). When a trader swaps token A for token B, they add token A to the pool and remove token B. The invariant recalculates the new price ratio.
There is no order book. There is no matching engine. There is no concept of a bid or ask. Every trade is a direct interaction with a smart contract that holds the pool's reserves.
The execution flow:
- Trader submits a swap transaction to the blockchain
- Transaction enters the public mempool (visible to everyone)
- Validator includes the transaction in a block
- Smart contract executes the swap using the AMM formula
- Token balances update atomically in the same transaction
Engineering strengths:
The beauty of this model is its simplicity. The entire exchange is a single smart contract. There are no off-chain components. There is no server to maintain, no matching engine to operate, no sequencer to trust. The protocol is fully permissionless and censorship-resistant at the smart contract level.
Liquidity provision is passive. Anyone can deposit tokens into a pool and start earning fees without any market-making expertise. This solved the cold-start liquidity problem that killed early on-chain order books.
Engineering limitations:
The constant product formula creates deterministic slippage that increases with trade size. This is not a bug in the implementation. It is a mathematical property of the pricing curve. For a pool with $10M in liquidity, a $100K trade might incur 1-2% slippage. On an order book with the same total liquidity, that trade could execute with near-zero slippage if the book has sufficient depth near the market price.
The public mempool is the root cause of MEV. Every pending swap transaction broadcasts its intent, size, and slippage tolerance to the entire network before execution. Sandwich bots monitor this mempool, detect profitable opportunities, and insert their own transactions before and after the victim's trade. This is not a theoretical risk. MEV extraction from AMM trades exceeds $1 billion annually.
Capital efficiency is structurally limited. In a standard constant product AMM, liquidity is distributed across an infinite price range. Only a small fraction of the total liquidity sits near the current market price where trades actually happen. Concentrated liquidity (Uniswap V3) improved this but introduced active management complexity that eliminated the passive liquidity provision advantage.
Model 2: Fully On-Chain CLOB (Hyperliquid, Serum)
This model brings traditional order book mechanics on-chain. Every order placement, cancellation, modification, and match is a blockchain transaction.
How it works:
The exchange operates as a blockchain, either a general-purpose chain (like Solana for Serum) or a purpose-built chain (like Hyperliquid's L1). The order book state is maintained by validators. When a trader places a limit order, it becomes a transaction that validators process and include in the chain state. When two orders cross (a buy at or above the lowest ask), the matching logic executes as part of block production.
The execution flow:
- Trader signs an order and submits it to the network
- Validators receive the order and include it in the next block
- Matching logic runs as part of block execution
- Matched trades update account balances in the chain state
- Block is finalized by consensus
Engineering strengths:
Full transparency. Every order and every trade is auditable on-chain. There is no hidden state, no off-chain component that could behave differently than claimed. The matching logic is deterministic and executed by the consensus mechanism.
Composability. Because the order book is part of the blockchain state, other smart contracts can interact with it directly. This enables on-chain vaults, automated strategies, and DeFi integrations that compose with the trading engine natively.
Engineering limitations:
Performance is bounded by consensus. The fastest possible matching is one trade per block. Hyperliquid achieves sub-second block times with HyperBFT, which is impressive for a blockchain but orders of magnitude slower than centralized exchange matching engines that operate in microseconds.
Public order flow. Every order is a transaction visible to validators and anyone monitoring the chain. This means your order size, price, and direction are known before execution. While the speed of the chain makes traditional mempool-based MEV harder, it does not eliminate the information asymmetry. Validators and sophisticated actors with low-latency access to the chain can still observe and potentially exploit order flow.
Chain-specific dependency. Trading requires your assets to be on the specific chain where the order book runs. For Hyperliquid, this means bridging USDC from Arbitrum. For Serum, it meant having assets on Solana. Each bridge introduces additional trust assumptions and friction.
Model 3: Off-Chain Matching with On-Chain Settlement (dYdX v3, 0x)
This model separates the high-frequency matching from the blockchain. Orders are matched off-chain by a centralized or semi-centralized engine, and only the resulting trades are settled on-chain.
How it works:
Traders sign orders cryptographically and submit them to an off-chain matching engine (sometimes called a relayer or sequencer). The engine maintains the order book in memory, matches orders using standard price-time priority, and periodically submits batches of matched trades to the blockchain for settlement. The blockchain's role is limited to custody (holding funds in smart contracts) and settlement (updating balances based on matched trades).
The execution flow:
- Trader signs an order with their private key
- Order is sent to the off-chain matching engine
- Engine matches the order against the book (millisecond latency)
- Matched trade is batched with other trades
- Batch is submitted to the blockchain for settlement
- Smart contract updates account balances
Engineering strengths:
Speed. The matching engine operates at centralized exchange speeds because it is not constrained by block times or consensus. Matching latency can be sub-millisecond. This is the same architecture that powers every major stock exchange and centralized crypto exchange.
Cost efficiency. Only matched trades go on-chain, not every order and cancellation. This dramatically reduces gas costs compared to fully on-chain order books where every order modification is a transaction.
Engineering limitations:
The critical weakness is the trust assumption. The off-chain matching engine is a centralized component. Traders must trust that it matches orders fairly, does not front-run, does not censor orders, and does not fabricate phantom liquidity. In dYdX v3, this engine was operated by dYdX Trading Inc. The company was reputable, but the architecture required trust in that specific operator.
If the matching engine goes offline, trading halts entirely. The blockchain holds funds safely, but no new trades can execute until the engine recovers. This is a single point of failure.
There is no cryptographic proof that the matching was done correctly. The blockchain sees the results (Alice bought 10 ETH from Bob at $3,000) but has no way to verify that this match was the correct one according to price-time priority, that no orders were skipped, or that the engine did not insert its own orders ahead of others.
Model 4: Off-Chain Matching with ZK-Proof Settlement (KalqiX, Lighter)
This is the newest architecture model and the one we chose for KalqiX. It takes the speed advantage of off-chain matching (Model 3) and adds cryptographic verification through zero-knowledge proofs, eliminating the trust assumption.
How it works:
Like Model 3, orders are matched off-chain at high speed. But after each batch of trades is matched, a zero-knowledge proof is generated that mathematically verifies the entire matching computation was correct. This proof, along with the resulting state changes, is submitted to the blockchain. A smart contract verifies the proof. If valid, the state updates are accepted. If invalid, the batch is rejected.
The execution flow:
- Trader signs an order with their private key
- Order is encrypted and sent directly to the matching engine
- Engine matches the order against the book (sub-10ms latency)
- Batch of matched trades is collected
- ZK proof is generated verifying correctness of all matches
- Proof and state changes are submitted to the settlement chain
- On-chain verifier contract validates the proof
- If valid, account balances are updated. If invalid, batch is rejected.
What the ZK proof verifies:
This is the critical part. The proof covers the following:
Every match followed price-time priority. If Alice's buy at $3,000 was placed before Bob's buy at $3,000, Alice gets filled first. The proof verifies this ordering was respected.
No orders were fabricated. Every order in the batch corresponds to a real, cryptographically signed order from a real user. The engine cannot create phantom orders.
No orders were censored. If an order should have matched based on the price-time priority rules, it was matched. The engine cannot selectively exclude orders.
Settlement arithmetic is correct. If Alice bought 10 ETH at $3,000, her account was debited exactly $30,000 and credited exactly 10 ETH. No rounding errors, no discrepancies.
State transitions are valid. The final state (all account balances after the batch) is the mathematically correct result of applying all matches to the previous state.
Engineering strengths:
Speed of off-chain matching without the trust assumption. This is the key innovation. You get sub-10ms matching latency (comparable to CEX performance) with mathematical verification of correctness (stronger than on-chain consensus verification).
Privacy. The ZK proof verifies correctness without revealing individual order details. The blockchain knows that the batch was computed correctly. It does not know who traded what, at what size, or in which direction. This eliminates the MEV information asymmetry at the architectural level.
Settlement on existing chains. Unlike fully on-chain CLOBs that require their own blockchain, ZK-proof settlement works on any chain that can verify the proof. KalqiX settles on Base and Arbitrum. This means no bridging to a custom L1, and you inherit the security of established chains.
Engineering challenges:
Proof generation latency. ZK proofs are computationally expensive to generate. While matching happens in sub-10ms, proof generation adds seconds of latency before the batch is finalized on-chain. For the trader, the fill is confirmed at match time (sub-10ms). Settlement finality comes when the proof is verified on-chain (seconds later). This is acceptable for most use cases but means the architecture is not suitable for use cases requiring instant on-chain finality.
Circuit complexity. Writing ZK circuits for order matching is significantly more complex than writing a standard matching engine. Every rule (price-time priority, partial fills, cancellations, settlement calculations) must be encoded in a form that can be proven in zero knowledge. This requires specialized cryptographic engineering. At KalqiX, we use SP1 (Succinct's proving system), which allows us to write matching logic in Rust and generate proofs without hand-coding circuits.
Prover infrastructure. The proof generation system must be reliable and performant. If the prover goes offline, new batches cannot be submitted to the chain. Well-designed systems include escape hatches that allow users to withdraw directly from the settlement contract if the prover is unavailable for an extended period.
Architecture Comparison Matrix
| Dimension | On-Chain AMM | On-Chain CLOB | Off-Chain + Settlement | Off-Chain + ZK Proofs |
|---|---|---|---|---|
| Matching latency | Block time (seconds) | Block time (sub-second) | Sub-millisecond | Sub-10ms |
| Verification | Smart contract execution | Blockchain consensus | Trust the operator | Zero-knowledge proof |
| Order privacy | None (public mempool) | None (public chain) | Operator sees orders | Full (encrypted orders) |
| MEV exposure | High | Medium | Operator-dependent | None |
| Settlement chain | Same chain | Own chain | Any chain | Any chain with ZK verifier |
| Composability | High (on-chain) | High (on-chain) | Low (off-chain state) | Low (off-chain state) |
| Custody model | Smart contract | Chain validators | Smart contract | Smart contract |
| Single point of failure | None | Validator set | Matching engine | Matching engine (with escape hatch) |
| Capital efficiency | Low (AMM curve) | High (order book) | High (order book) | High (order book) |
Why We Chose Model 4 for KalqiX
When we started building KalqiX, we evaluated all four models against three requirements.
Requirement 1: CEX-comparable matching speed. Professional traders and market makers need sub-10ms matching to operate effectively. Models 1 and 2 cannot achieve this because they are constrained by block times. Only Models 3 and 4 deliver the required performance.
Requirement 2: No trust in a centralized operator. Model 3 is fast but requires trusting the matching engine operator. We wanted mathematical verification of correctness. Only Model 4 provides this through ZK proofs.
Requirement 3: Order flow privacy. Public order flow enables MEV and leaks trading strategies. Models 1, 2, and 3 all expose order details at some point in the pipeline. Only Model 4, with encrypted order submission and ZK-proof settlement, keeps order flow private throughout.
The intersection of all three requirements pointed to one architecture: off-chain matching with ZK-proof settlement.
The KalqiX Implementation
Here is how these architectural principles translate into our specific implementation.
Matching engine. Written in Rust. Deterministic execution with no garbage collection pauses. Benchmarked at sub-10ms matching latency and 250,000+ operations per second. The engine implements standard CLOB matching with price-time priority, supporting market orders, limit orders, cancels, and amends.
Order encryption. Orders are encrypted before leaving the trader's client. The sequencer receives encrypted orders and only decrypts them at the moment of matching. No external observer can see order intent, size, or direction.
ZK proof system. We use SP1 from Succinct. SP1 allows us to write our matching and settlement logic in Rust and generate ZK proofs without manually constructing arithmetic circuits. This was a critical decision, as hand-writing circuits for complex matching logic would have added months of development time and introduced additional audit surface.
Settlement. Proofs are verified on Base (primary) and Arbitrum. The settlement smart contract holds user funds and updates balances only when a valid ZK proof is submitted. If no valid proof is submitted, funds remain in the contract and users can withdraw through the escape hatch mechanism.
Cross-chain deposits. We use Avail Nexus for cross-chain deposits and withdrawals across 10+ chains. Traders on Ethereum, Polygon, Arbitrum, Base, and other supported networks can deposit directly without using third-party bridges.
Data availability. Transaction data is posted to Avail's DA layer, ensuring that the full history of operations is publicly available for anyone who wants to reconstruct and verify the state independently.
What This Means for Builders
If you are evaluating DEX architectures for a new project, the decision framework is straightforward.
Choose an on-chain AMM if you need permissionless token listing, passive liquidity provision, and maximum composability with other on-chain protocols. Accept the slippage, MEV, and capital efficiency tradeoffs.
Choose a fully on-chain CLOB if you want full transparency and on-chain composability with order book mechanics. You will need your own high-performance chain or access to one.
Choose off-chain matching with ZK-proof settlement if you need CEX-grade speed, mathematical verification of correctness, and order flow privacy. Accept the prover infrastructure overhead and the reduced on-chain composability.
Or, instead of building from scratch, consider integrating with existing infrastructure. KalqiX's white-label model lets protocol teams plug a production-grade ZK CLOB engine under their own brand, inheriting shared liquidity from the network and earning protocol revenue from day one. Five DEXs are already live on our testnet with this model.
The architecture decisions in DeFi trading infrastructure are not getting simpler. They are getting better. Every model has legitimate use cases. The key is matching the architecture to the specific requirements of your users and your market.
KalqiX is a ZK-powered CLOB exchange infrastructure layer delivering sub-10ms matching, ZK-proof settlement, and full self-custody. Try the testnet →