AWS Web3 Blog
Building decentralized perpetual futures exchanges on AWS
Perpetual futures are financial contracts that provide leveraged exposure to an asset’s price without direct ownership. Unlike traditional futures, they carry no expiration date, allowing positions to remain open as long as margin requirements are met. Decentralized exchanges (DEXs) support high-performance perpetual futures trading while preserving self-custody and transparent on-chain settlement. Beyond cryptocurrencies like Bitcoin and Ethereum, these markets now offer exposure to commodities, individual stocks, pre-IPO equities, and market indices.
In this post, we provide examples of common architecture patterns for modern perpetual DEXs, and discuss how AWS services can be used to build the decentralized, secure, and scalable infrastructure required to operate them.
What makes a perpetual futures exchange different?
Unlike centralized exchanges, decentralized perpetual futures platforms coordinate pricing, collateral, execution, and settlement across a blockchain network in near real time, allowing distinct capabilities:
| Capability | Advantage | Requirements |
| Non-custodial collateral management | Eliminates custodial counterparty risk | Secure key management, transaction validation, smart contract integrity |
| Transparent settlement | Auditable on-chain system of record for all positions, liquidations, and funding payments | Privacy controls for institutional trading workflows |
| Permissionless access | Global accessibility without account creation or centralized approval | Infrastructure capable of handling highly variable demand patterns |
| Composability | Enables structured products, automated trading, and portfolio-level financial workflows | Well-defined on-chain interfaces for external application integration |
Understanding the perpetual trading lifecycle
The following process flow diagram traces the lifecycle of a single trade. The subsequent sections provide an explanation of each step and the underlying infrastructure requirements of the core components involved.
Step 1: Connect and deposit collateral
The trader connects a self-custodial wallet and deposits collateral into a margin vault smart contract. Many platforms use session-based signing mechanisms to reduce friction while preserving security.
Step 2: Submit an order
The trader submits a perpetual futures order through the DEX trading interface, which forwards the request to backend systems through API or persistent WebSocket connections.
Step 3: Validate and match
The trading engine validates margin availability, order constraints, and position limits before routing valid orders to the matching engine. The matching engine maintains per-market order books and executes trades using price-time priority. This component is typically the most latency-sensitive part of the system.
Step 4: Update risk state
After execution, the risk engine updates account-level margin, unrealized profit and loss, and liquidation thresholds. Many systems operate redundant risk services to achieve deterministic and fault-tolerant computation.
Step 5: Monitor positions
Market prices are continuously updated using oracle data streams. Margin ratios and position health are recalculated in real time or at fixed intervals depending on system design. This monitoring is a continuous loop rather than a one-time check: steps 4 through 6 repeat on every cycle, for every open position, independently of any trader action.
Step 6: Execute liquidations (if triggered)
If margin falls below maintenance thresholds, liquidation workflows are triggered by the risk engine itself. No trader action is involved, which is what distinguishes a liquidation from a voluntary close. Positions are closed through automated systems or external liquidators, and insurance mechanisms might absorb losses under extreme conditions.
Step 7: Settle and withdraw
Whether a position was closed by the trader or liquidated by the risk engine, settlement follows the same path. Realized profit and loss is recorded on-chain and reflected in a trader’s account balance. Traders can then submit signed withdrawal requests to transfer available funds from the protocol to their wallet.
This lifecycle illustrates that a perpetual futures platform is a distributed system composed of multiple coordinated subsystems rather than a single application or smart contract.
Common perpetual futures architecture models
Decentralized perpetual futures exchanges have converged around two architectural models, hybrid and fully on-chain.
A hybrid perpetual futures DEX runs its performance-critical path. Order matching, margin validation, and price aggregation off-chain, then settles the results to a blockchain for finality and custody. This architecture delivers centralized-exchange-grade latency while preserving on-chain verifiability of positions and funds.
In fully on-chain perpetual DEX architecture, order books, matching logic, and settlements execute directly on a purpose-built blockchain network. This approach maximizes transparency and verifiability.
| Dimension | Hybrid (Off-chain matching + on-chain settlement) | Fully On-Chain (All logic inside validators) |
| KYC requirements | Can enforce identity verification at the API gateway layer before granting order submission access. Supports tiered KYC with progressive access controls. | Permissionless by default. KYC enforcement requires on-chain identity attestations or allowlisted wallet registries, adding protocol complexity. |
| Matching latency | Sub-millisecond. The matching engine runs on bare-metal EC2 in a Cluster Placement Group, optimized the same way as a centralized exchange. | Bounded by block time (tens to hundreds of milliseconds). Matching runs inside the validator binary at native speed, but finality depends on consensus rounds. |
| Transparency and verifiability | Settlement is on-chain and auditable. However, order matching itself happens off-chain and is not independently verifiable by external observers. | Every order, match, margin check, and liquidation executes on-chain. All state transitions are fully verifiable by anyone running a node. |
| Decentralization profile | Settlement inherits the decentralization of the underlying L1/L2. The matching engine is a centralized service operated by the exchange team. | Validator set size is typically 16 to 25 nodes. The chain trades broad decentralization for throughput and deterministic finality. |
| Composability | Limited. External protocols can read on-chain positions but cannot interact with the off-chain order book or trigger executions programmatically. | Full. On-chain positions, collateral, and execution are composable, enabling structured products, automated strategies, and portfolio-level workflows natively. |
| Scalability path | Horizontal. Each component scales independently (add cache shards, more Lambda concurrency, larger instances). Throughput is bounded by instance size and network, not block capacity. | Vertical. Throughput is bounded by validator hardware and consensus protocol limits. Scaling requires chain upgrades or sharding the application across multiple chains. |
The following sections explore both architectures in detail. For each component, we explain its purpose, then cover the critical implementation details.
Hybrid perpetual DEX solution architectures
In hybrid architectures, order matching and execution occur off-chain while settlement is recorded on-chain through smart contracts on Layer 1, Layer 2, or application-specific blockchain networks.
This approach facilitates optimization of latency-sensitive components using traditional infrastructure similar to centralized exchanges while preserving non-custodial settlement guarantees and transparency through blockchain systems.
The following diagram (Figure 2) shows the hybrid architecture with its ten components.
Next, we explain the business purpose and critical technical implementation details of each component.
Component 1: API and connection management
This component provides the primary interface for traders, trading bots, and liquidity providers to submit orders, retrieve account information, and receive real-time market data. It is responsible for delivering a responsive user experience similar to a centralized exchange, while supporting large numbers of concurrent client connections.
Use Amazon API Gateway where sub-millisecond latency is not required. The REST API (HTTP API type) handles stateless operations: order submission, position queries, trade history, and funding rate history, routed through a virtual private cloud (VPC) link to an internal Application Load Balancer. The WebSocket API maintains persistent connections for market data. On $connect, an AWS Lambda function registers the connection ID in Amazon DynamoDB. On $default, subscription messages update the connection’s channel set.
Edge layer: CDN and security
Front the REST API with an Amazon CloudFront distribution to serve cacheable responses (market metadata, funding history, candle snapshots) from the location closest to each trader. Two hooks run inside the CloudFront request lifecycle: CloudFront Functions for viewer-stage header/URL rewrites, and Lambda@Edge for heavier origin-stage logic (request validation, free-versus-paid tiering, routing prioritization). AWS WAF filters unintended requests and AWS Shield absorbs DDoS. The WebSocket API stays off CloudFront so market-data streams connect directly for minimal latency, retaining always-on AWS Shield Standard, but not the WAF/Lambda@Edge layer.
For an example, see the case study on how Jupiter, a decentralized exchange, moved its interface layer to CloudFront and Lambda@Edge to differentiate free and paid users, prioritize routing, and validate requests at the edge, cutting API latency by roughly 60%.
Component 2: Matching engine
The matching engine is the most latency-sensitive component of the exchange. Before executing an order, it verifies that the trader has sufficient collateral, validates the execution price against the oracle price, and enforces market risk limits such as maximum open interest as depicted in Figure 1. These checks help protect the platform from undercollateralized positions and price manipulation.
Matching engine latency optimization for hybrid DEX follows the same principles as in centralized exchanges (CEX). Consider running it on the largest instance size in an Amazon Elastic Compute Cloud (Amazon EC2) instance family, or on a bare metal (.metal) instance and then co-locating engine and gateway instances in a Cluster Placement Group so packets travel the shortest physical path. Apply these choices in order of impact, starting with Region and Availability Zone placement and ending with operating system tuning.
For a deep dive into latency optimization, see the AWS tick-to-trade series Part 1 on architecture and networking and Part 2 on EC2 compute selection.
To learn how Derive implemented this pattern using AWS Graviton and Amazon Elastic Kubernetes Service (Amazon EKS), see How Derive scaled their low-latency, decentralized trading platform.
Component 3: Oracle and price infrastructure
A perpetual futures DEX relies on accurate external asset prices provided by oracles to validate margin, calculate funding, monitor positions, and trigger liquidations. Incorrect, manipulated, or stale prices can lead to unfair liquidations or allow undercollateralized positions to persist, making price integrity essential to a platform’s solvency.
Run the oracle aggregation service as a persistent Amazon Elastic Container Service (Amazon ECS) AWS Fargate task connecting to multiple independent sources: on-chain price feeds (through self-hosted RPC nodes), pull-based oracle networks delivering signed attestations over WebSocket, and several centralized exchange spot APIs for resilience.
The aggregator discards stale sources, typically anything older than 10 seconds, then takes the median and rejects outliers deviating more than 1% from it. Each price gets a recorded confidence level. The mark price used for all margin, liquidation, and funding calculations blends the oracle index with the order book midpoint (typically 70% oracle, 30% book). This blend forces a threat actor to manipulate the majority of external sources at once. Self-hosted oracle nodes on Amazon EC2 give full control over update frequency and staleness thresholds. As an alternative, Chainlink (an AWS partner) offers its Data Feeds and Data Streams directly through AWS Marketplace, providing managed decentralized oracle infrastructure without the operational overhead of running your own nodes.
Component 4: Margin and risk engine
The margin and risk engine continuously evaluates the financial health of every position. It determines whether positions meet margin requirements, calculates funding payments, and identifies when positions should be liquidated to protect the protocol from bad debt.
Run margin calculations as stateless AWS Lambda functions against the Amazon ElastiCache state cache. For every open position, compute unrealized PnL, account equity, margin ratio, and the estimated liquidation price. Each invocation reads from the cache (sub-millisecond), performs arithmetic (microseconds), and returns, so the engine scales per market without redeploying stateful services. It is invoked synchronously during pre-trade validation and asynchronously on every new block by the margin monitor. A scheduled Lambda invocation advances a global funding index each period. Per-position funding is not pushed on-chain every period. Instead it is realized when a position is next touched (opened, modified, or closed), and until then is carried as accrued funding in the margin check. This avoids a per-period on-chain write across all open positions.
Component 5: Liquidation engine
This is the most operationally critical component in the stack. Its failure mode is protocol insolvency. In a falling market, latency is money, so the path from “margin breached” to “transaction on chain” must be as thin as possible.
The closing logic is a three-tier cascade that protects the protocol while limiting market impact: market liquidation against the order book first (partial for large positions to avoid a death spiral that cascades into other traders), then a backstop vault that unwinds gradually, and finally auto-deleveraging of the highest-PnL opposing traders as a last resort.
The cascade logic itself lives in the clearinghouse contract and executes atomically on-chain, keeping the keeper thin. Run keeper tasks in multi-AZ and multi-Region configurations with cross-Region cache replication so a Region failure during a crash is covered within seconds. Fargate suits L2 chains with two-second-or-longer block times. Dedicated Amazon EC2 instances suit keepers needing predictable low-latency networking.
Component 6: Transaction submission and MEV protection
This component connects the off-chain engine to the blockchain and handles two transaction classes with different priorities. Trading settlement transactions tolerate a few seconds of delay. Liquidation transactions are time-critical and must never queue behind settlement, because delay during a falling market creates bad debt. Both must also be shielded from maximal extractable value (MEV): sandwich attacks on trades and front-running of liquidations.
Maintain separate Amazon Simple Queue Service (Amazon SQS) FIFO queues per class, each handling nonce management and gas estimation with repricing, and retry with dead-letter queues. Route transactions through a private relay to block builders rather than the public mempool, eliminating mempool-based MEV.
Component 7: Blockchain interface and settlement
This component is the on-chain trust boundary. The off-chain margin check exists for user experience. The on-chain check cannot be bypassed. Settlement re-validates the oracle price and margin, transfers collateral, records the position, and updates open interest, reverting atomically if any step fails. This is what makes the exchange non-custodial and auditable.
Run self-hosted blockchain nodes on Amazon EC2 sized for the target chain. For AWS Cloud Development Kit (AWS CDK) templates for self-managed nodes and guidance on selecting and optimizing EC2 instances and Amazon Elastic Block Store (Amazon EBS) storage for different protocols and transaction throughput, see the AWS Blockchain Node Runners project. A persistent Amazon ECS Fargate task subscribes to node logs, decodes events (PositionOpened, Liquidation, FundingPaid, and others), and publishes them to the event stream.
Component 8: Key management and vault security
Cryptographic keys secure the exchange’s treasury, insurance fund, settlement wallets, and other hot wallets. Protecting these keys is critical, because a compromise could result in loss of funds or unauthorized transactions. The signing key must never be exposed, even if the host operating system is fully compromised.
Use AWS Key Management Service (AWS KMS) and AWS Nitro Enclaves to implement a secure key management and signing solution. To learn more, see the AWS Nitro Enclaves for secure blockchain key management blog post series and How to sign EIP-1559 transaction using AWS KMS.
Component 9: Data pipeline and indexing
Every position change, liquidation, and funding payment must reach risk systems, traders, charts, and analytics consistently and in order. This pipeline turns raw events into the queryable state that powers the trading UI, regulatory reporting, and the ability to rebuild derived state without replaying the blockchain.
Use Amazon Kinesis Data Streams as the unified event bus, partitioned by trading pair to guarantee per-pair ordering.
Parallel AWS Lambda consumers fan out: a state updater writes to Amazon ElastiCache (the latency-sensitive path), a WebSocket publisher pushes client messages, a candle builder writes open-high-low-close-volume (OHLCV) series to Amazon Timestream for InfluxDB, a trade recorder persists to Amazon Relational Database Service (Amazon RDS), and an archiver writes Parquet to Amazon Simple Storage Service (Amazon S3). See Building a blockchain indexer on AWS for additional details on blockchain data stream processing.
Component 10: State cache and real-time distribution
The state cache is the shared substrate every latency-sensitive engine reads from concurrently: order book depth, open positions, mark prices, and open interest. Its read volume scales with open positions rather than trade volume, growing steadily over time, which makes it a primary capacity-planning concern.
Deploy Amazon ElastiCache in cluster mode, spreading keys across shards with a multi-AZ replica per shard (primary serves writes, replica serves reads). It serves two patterns at once. The margin monitor polls all positions every block, the matching engine reads order book and oracle state per order, and every Kinesis consumer pushes event-driven updates.
Fully on-chain architectures
A fully on-chain perpetual futures DEX embeds the matching engine, margin engine, and liquidation logic directly into the blockchain’s execution environment. Rather than building off-chain services that compensate for a general-purpose chain, this approach builds on a chain optimized for one purpose: high-throughput trading with deterministic finality.
Because of deterministic finality and high-throughput requirements, on-chain perpetual DEXs trade decentralization for performance. These systems often rely on smaller blockchain network validator sets and might exhibit a higher geographic concentration of nodes.
This architecture turns the hybrid Components 3 through 7 (oracle, margin, liquidation, transaction submission, and settlement) into native chain logic running inside the validator binary, so they are no longer separate AWS services. What remains is the infrastructure that runs the chain, connects users to it and provides analytics capabilities.
The on-chain architecture groups into five components, shown in Figure 3. Each of the following components states why it matters and how to build it on AWS, referencing the hybrid section wherever a pattern is shared.
Component 1: Interfaces
The majority of retail traders and bots are not exposed to raw consensus protocols, so they need HTTP and WebSocket endpoints that accept order parameters and return market data. This boundary holds no trading state and runs no trading logic, because all trading logic runs on-chain.
As in the hybrid design’s Component 1: API and connection management, Amazon API Gateway provides the REST and WebSocket endpoints. REST handles stateless operations such as order submission, position queries, and trade history. WebSocket maintains persistent connections for order book depth, trade confirmations, position updates, and funding ticks. The WebSocket fan-out originates from the read path in Component 2, which pushes formatted updates to connected clients. The same edge layer carries over: an Amazon CloudFront distribution (with CloudFront Functions and Lambda@Edge, behind AWS WAF and Shield) fronts the REST API, while WebSocket streams connect directly to keep latency minimal.
Component 2: Transaction processing and indexing
This component moves data in both directions between clients and the chain. The write path protects scarce consensus capacity by rejecting invalid orders before they reach validators. The read path serves all market data without burdening the chain’s RPC interface, so a failure here degrades the user-facing data experience without affecting trading, which runs entirely on-chain.
The order gateway validates each order before forwarding it, checking the signature and the price, size, and leverage against market limits, then rejecting invalid orders so they never consume validator compute. Valid orders go to the validator set over RPC.
On the read path, a block indexer decodes trading events from each block and feeds an event aggregator that holds an in-memory replica. This replica powers the WebSocket fan-out and serves REST snapshot queries. In the hybrid design, Amazon ElastiCache fills this role as a shared cache for off-chain engines, whereas here the aggregator is a read-only replica that exists only to serve external queries. A candle aggregator builds OHLCV series and writes them to Amazon S3 as a Parquet data lake.
Component 3: Validator and application chain infrastructure
This single component absorbs the work the hybrid architecture spreads across five services (oracle, margin, liquidation, transaction submission, and settlement). Matching, pre-trade margin validation, on-chain price derivation, liquidation cascade, and deterministic ordering all run inside one validator binary within a single consensus round. As a result, a liquidation check never contends with a margin calculation, and the price cannot go stale between them. The cost is a small validator set, typically 16-25 nodes, whose honest majority the exchange depends on for liveness and safety.
The business logic compiles into the validator binary rather than running as smart contracts on a general-purpose virtual machine such as Ethereum Virtual Machine (EVM) so that it can execute at native speed. Validators also need to run on Amazon EC2 sized for the chain’s compute, network and storage performance profile.
Amazon EC2 instance attestation can be used to build the AMI in a reproducible and remotely attestable way, enforcing zero operator access on the validator nodes. For more details, see the Amazon EC2 instance attestation documentation.
Component 4: Bridging
Cross-chain deposits, for example, move USD Coin (USDC) from chains such as Ethereum and Solana onto the application chain. The relayer’s signing keys are the highest-risk material in the architecture, because a compromised bridge key can mint unbacked assets and steal from every user. Validators are protected by consensus, but the relayer is a single service with a hot key, so it warrants the strongest controls.
Bridge contracts on the source chains emit deposit events that a relayer on Amazon ECS observes. After sufficient source-chain finality, the relayer mints the corresponding asset on the application chain, and the reverse path releases locked USDC on burn events. The bridge signing path reuses the enclave-based key stack from hybrid Component 8, which is AWS Nitro Enclaves for isolated signing, AWS KMS releasing the key only on a matching attestation. Multi-signature schemes, time-locked withdrawals, and rate-limited minting add application-level protection on top of that foundation.
Component 5: Public blockchain network infrastructure
The application chain settles to, or derives security from, a public Layer 1 network. The lag between the chain’s latest finalized block and the latest state posted to Layer 1 is the key health signal, because a growing lag means the security guarantee is degrading.
If the chain posts state roots or batches to Ethereum as a rollup or Validium, it needs Layer 1 connectivity for settlement submission and finality verification. If it is a sovereign Layer 1, this component peers with other networks for cross-chain communication and bridge verification. The settlement flow reuses the hybrid Component 6 patterns of nonce management, gas estimation, and retry with FIFO queuing, with one difference. Cadence is relaxed, because settlement batches every few minutes or hours rather than per trade.
Expose the validators’ peer-to-peer gossip endpoints to the public internet so that external nodes can sync and gossip, no matter where those nodes run. Publish the node software as a reproducible build with a known-good hash. Document the bootstrap peers and chain parameters so an operator can stand up a node in their own AWS account or on-premises.
Conclusion
Building a perpetual futures trading platform requires coordinating multiple distributed systems operating under strict requirements for latency, availability, and security. Trading engines, risk systems, market data pipelines, custody infrastructure, analytics services, and blockchain settlement layers must work together to deliver a consistent and reliable trading experience.
While implementation approaches vary, most systems converge on a shared set of requirements: efficient execution, real-time risk management, secure custody, scalable data distribution, and verifiable settlement.
AWS provides a broad set of infrastructure services that support these requirements, including compute, networking, storage, analytics, and security capabilities designed for distributed financial systems. Whether building hybrid architectures or fully on-chain systems, teams can use AWS services to design scalable and secure trading platforms that support the continued evolution of decentralized derivatives markets.
Ready to build your perpetual futures exchange on AWS? See how Derive scaled their low-latency, decentralized trading platform using AWS Graviton, Amazon EKS, and Amazon Aurora. Contact your AWS account team or visit the AWS Blockchain page to explore reference architectures, connect with solutions architects, and start designing your decentralized derivatives platform today.



