Building Uniswap Bots Without Getting Front-Run: Mempool Strategies, Private RPCs, and When MEV Protection Isn’t Worth the Cost

A developer deploying a token-swap bot faces a practical problem on day one: transactions submitted to the public Ethereum mempool are visible to searchers, validators, and other bots before they settle. A profitable arbitrage opportunity or large trade broadcast carelessly can be front-run, sandwiched, or otherwise intercepted by extracting value that should have belonged to the trader. The conventional response is to use private transaction pools, MEV-resistant relays, or encrypted mempools. But these solutions cost money, introduce latency, reduce visibility into what happened on-chain, and may not be necessary for every bot strategy. The central question is not whether front-running exists. It is which protection method—if any—makes economic sense for a given trade size, profit margin, and network.

The answer requires comparing three different architectures: sending transactions through public endpoints and accepting MEV as a cost of doing business, routing through private relay services such as MEV-Protect or Flashbots Relay, and participating in encrypted batch auctions where transactions are ordered by the protocol rather than by market dynamics. Each approach trades off speed, privacy, cost, and certainty. A small swap bot trading on thin margins may find that MEV protection costs more than it saves. An arbitrage bot targeting large liquidity shifts may find that private submission is essential. A market-making bot might need a hybrid approach that varies per trade. Understanding the actual numbers—not the marketing claims—is the difference between a profitable system and one that bleeds value through unnecessary fees.

Diagram showing the three transaction submission paths: public mempool with visible transactions, private relay endpoint routing, and encrypted batch auction ordering

How front-running and MEV extraction actually work on Ethereum

When a transaction is submitted to a public Ethereum RPC endpoint, it enters the mempool—a shared waiting area where hundreds of nodes, validators, and bots monitor pending transactions. Anyone observing the mempool can see the transaction data, including the swap amount, token addresses, and slippage parameters. That transparency is by design: Ethereum’s base layer provides no privacy guarantees. A searcher can now examine whether front-running that transaction is profitable by submitting a transaction with a higher gas price to execute first, moving the price in an unfavorable direction for the original sender, and then allowing the original transaction to settle at worse terms.

This is front-running in the classical sense. Sandwiching is a variant where the searcher inserts a transaction both before and after the victim’s transaction: first, a large swap that moves the price, then the victim’s swap at worsened rates, then a third transaction that reverses the initial move and captures the spread. The cost to the victim is not a fixed fee but a percentage of the swap amount—larger trades are more profitable to sandwich. On Uniswap’s automated market maker pools, a 1,000 ETH swap might have sandwich losses ranging from 0.1% to 0.5% or more depending on the liquidity depth and market activity. For a swap of 10 ETH, the absolute loss might be only $50 to $200, but if the bot’s profit margin is 0.2%, that loss is catastrophic.

The mechanism relies on several details. First, the searcher or bot must be able to simulate the transaction outcome in advance—determining what price and slippage would result from their sandwich. This uses Uniswap’s algorithmic pricing model and pool state, which are public and queryable. Second, the transaction must be included in a block quickly, which favors bots with low latency and those who can pay high gas prices. Third, the profit from the sandwich attack must exceed the cost of the front-running transaction itself, the extra gas spent, and any failed transactions that were simulated but not included.

This is why MEV (maximal extractable value) is significant but not uniformly catastrophic. A small swap on Uniswap V3 with concentrated liquidity that moves only a few basis points might be too small to sandwich profitably—the gas cost and slippage reversal cost would exceed the gain. Conversely, a large arbitrage trade across two pools with significant price discrepancy is highly visible and highly profitable to sandwich. The searcher extracts MEV not by hacking but by observing the mempool, simulating outcomes, and paying gas prices to be included first.

Public mempool bots and the cost of accepting MEV

The simplest bot architecture uses a standard RPC endpoint and sends transactions to the public mempool. This means no additional privacy service, no special routing, and no batch auction mechanism. The bot constructs a transaction, calls eth_sendTransaction or eth_sendRawTransaction, and hopes the transaction settles before a sandwicher sees it. This approach has two advantages: it is cheap (only standard network fees apply) and it is straightforward to implement and monitor.

The cost of accepting MEV depends on transaction size and strategy. For a bot that executes 100 small swaps per day on Uniswap, each 0.5 ETH, the expected sandwich loss might be 0.05% to 0.15% per transaction. That is $25 to $75 in MEV cost per swap, or $2,500 to $7,500 per day. If the bot’s profit margin is $1,000 per swap on average, MEV is a 2.5% to 7.5% drag—unpleasant but survivable. If the profit margin is $200, MEV consumes 12.5% to 37.5% of profits. If the margin is $50, the bot is negative before it even starts.

The calculation changes when transaction size grows. A bot executing three large arbitrage trades per day, each 50 ETH, on a volatile market might face sandwich losses of 0.2% to 0.4% per trade because the price movement is significant and the profit opportunity is obvious. That is $4,000 to $8,000 per trade, or $12,000 to $24,000 per day in losses. The bot’s strategy must generate $25,000+ in profit per day just to break even. For many bots, that is infeasible. Public mempool submission becomes a losing proposition, and some form of MEV protection becomes necessary for the business model to work.

The calculation also factors in network congestion and latency. During high-activity periods, even small transactions take longer to include, creating more time for a sandwicher to observe and respond. A bot’s reaction time—from detecting an opportunity to submitting a transaction—might be 50 to 200 milliseconds under normal conditions. During congestion, that could extend to 500 milliseconds or more. Each additional second of latency is another opportunity for a competitor or sandwicher to move first.

Private RPC endpoints and MEV-protected relays

A private RPC endpoint routes transactions through a service that does not broadcast them to the public mempool. Instead, the transaction goes directly to validators, MEV relays, or a private pool. The validators then order and execute it without exposing it to general observation. Services such as MEV-Protect, Flashbots Relay, MEV-Blocker, and similar platforms offer this arrangement. The bot submits the transaction using the private endpoint URL instead of a public Infura or Alchemy endpoint, and the transaction is handled outside the public mempool.

The benefit is clear: a private transaction cannot be sandwiched by a searcher who only monitors the public mempool because the transaction is not visible there. For large trades, this can eliminate most sandwich losses. A 50 ETH swap that would face 0.3% MEV loss in the public mempool might face only 0.05% loss through a private relay if the relay’s searchers are less aggressive or if the protocol itself limits MEV extraction. The absolute savings could be several thousand dollars per large trade.

The cost of private relays typically includes a fee charged per transaction or per block. Some services charge a flat 0.25% to 0.5% of the transaction value; others charge per-transaction fees of $1 to $10. Some services offer no explicit fee but capture a share of MEV savings through sophisticated ordering or reordering strategies. The math becomes: Does the MEV protection save more than the relay fee costs? For a 50 ETH swap with expected 0.3% MEV loss ($3,000) and a 0.3% relay fee ($3,000), the bot breaks even and is indifferent. For a 5 ETH swap with expected 0.3% MEV loss ($300) and a $5 flat fee, the relay is expensive relative to the protection it provides.

Private relays also introduce latency and opacity. The transaction must traverse an additional service, which adds milliseconds to the round-trip time. The bot may not receive immediate confirmation of inclusion and may need to poll on-chain to verify settlement. If the relay is overloaded or the searchers disagree on ordering, the transaction might be delayed or reordered disadvantageously. Debugging why a transaction behaved unexpectedly is harder when it passed through a private route rather than being visible in the public mempool.

Encrypted batch auctions and protocol-enforced ordering

Encrypted batch auctions, such as Threshold Encrypted Mempools (tEMP) or services like MEV-Blocker that use similar ideas, represent a different approach. Transactions are submitted encrypted so that even the relay cannot see their contents before they are ordered. The relay orders them according to a predetermined rule—often random ordering to prevent any specific searcher from profiting from knowledge of pending transactions—and then executes them. This prevents front-running and sandwiching by design rather than by obfuscation.

The protection is genuine and comprehensive. Even if the relay operator wanted to sandwich a transaction, it cannot because it does not know the transaction contents until after ordering is committed. This makes encrypted batch auctions attractive for bots executing large, predictable trades. The trade-off is increased latency and reduced flexibility. The bot must submit the transaction, wait for the batch to be assembled (typically 4 to 12 seconds per batch on Ethereum), and then execute. If the market opportunity has a shorter time window, the batch latency is unacceptable. If the bot needs to adjust parameters based on market conditions in the last moment before submission, encrypted submission prevents that.

Cost is another consideration. Encrypted batch auctions sometimes charge a small fee to participate, or they may capture a portion of the MEV savings themselves. The fee is usually lower than traditional private relays (0.05% to 0.15%), but the benefit is also more limited for small transactions. A 0.5 ETH swap through an encrypted batch auction might pay a $2 fee to avoid a $30 sandwich loss—a clean win. A 50 ETH swap through the same service might avoid $3,000 in sandwich loss for a $15 fee—also a win, but the absolute savings are less interesting because the bot might have other ways to reduce MEV on large trades.

Encrypted batch auctions also work best when multiple participants use them. If only one bot in a batch is executing, the protocol cannot achieve strong privacy or MEV reduction because the transaction contents are revealed once execution occurs. The benefits scale with participation, which creates a chicken-and-egg problem for newer services. Additionally, some encrypted batch systems do not guarantee transaction inclusion; if the batch is full or if the transaction is rejected, the bot must resubmit, potentially through a different route. This unpredictability can be unacceptable for time-sensitive strategies.

Choosing a strategy: Bot size, profit margin, and network

The decision between public mempool, private relay, and encrypted batch depends on three variables: transaction size, profit margin per transaction, and the volatility of the opportunity. A bot executing 100 swaps per day of 0.1 ETH each, with a profit margin of $10 per swap, should use the public mempool and accept MEV as a cost. The transactions are too small to sandwich profitably, and adding relay fees would turn profitable trades into losses. The bot’s defense is speed and consistency: fast reaction time to detect opportunities and rapid execution to settle before others.

A bot executing 10 swaps per day of 10 ETH each, with a profit margin of $500 per swap, should evaluate private relays with concrete numbers. If the expected sandwich loss is $100 per swap and the relay fee is $50 per swap, the relay saves $50 per swap, or $500 per day. That is worth the complexity and monitoring overhead. If the relay fee is $150 per swap, the relay costs more than it saves, and public mempool is preferable even with the sandwich risk.

A bot executing 5 swaps per day of 50 ETH each, with a profit margin of $2,000 per swap, should probably use private relays or encrypted batch auctions as a standard practice. The transactions are large enough that sandwich losses are substantial (potentially $2,000 to $4,000 per swap), and relay fees (typically $50 to $300 per swap) are a small price relative to the protection. The real decision is which service offers the best combination of fees, latency, and reliability. For this bot, speed is less critical because the opportunities are large and the latency cost of a private relay is acceptable.

Network selection also matters significantly. On Ethereum Layer 1, MEV competition is intense, and private relays are common. On Arbitrum or Optimism, MEV pressure is lower because block times are shorter and the cost of front-running is higher relative to the profit. A bot on Arbitrum might skip private relays entirely, while the same bot’s Ethereum version might be mandatory. On Layer 2 networks with higher finality, a bot might use Uniswap app and similar protocols but submit to the public mempool with confidence that sandwich risks are manageable due to block structure and validator incentives differing from Layer 1.

Implementation considerations and hidden costs

Switching to a private relay or batch auction is not a one-line code change. The bot must integrate with the new endpoint, handle new error codes and response formats, adjust gas price strategies because private relays may not respect base-fee mechanisms in the same way, and monitor for transaction inclusion differently. Some private relays provide webhooks or polling endpoints to confirm settlement; others require the bot to query the blockchain directly. Debugging is harder because the private route is not visible in public transaction explorers.

Gas price strategy also shifts with private relays. On public mempool, gas price bidding is competitive and transparent. On private relays, the relay controls inclusion order, so high gas bids may not help. Some private relays use a flat fee regardless of base fee or priority fee; others use hybrid models where the bot still bids gas price but the relay’s ordering algorithm considers it differently than Ethereum’s standard mechanism. A bot optimized for public mempool gas bidding may underbid on private relays, causing transactions to be delayed or reordered disadvantageously.

Another hidden cost is redundancy. A bot relying on a single private relay is vulnerable to relay downtime, operator errors, or regulatory changes. Several private relay services have faced outages or compatibility issues. The safest approach is to route some transactions through multiple relays or maintain a public mempool fallback for critical trades. This adds complexity: the bot must choose between relays per transaction, retry logic, and monitoring to ensure coverage.

Regulatory and custody questions also arise. Some private relay operators may be subject to geographic restrictions or may ask for user information. If the bot is not user-facing and is purely algorithmic, this may not apply, but if the bot is part of a larger service or is used by others, the operator’s terms and policies matter. Encrypted batch auctions sometimes use distributed systems or threshold cryptography, which can raise questions about control and jurisdiction. A bot developer should review the operator’s policies and infrastructure to understand what assumptions the strategy depends on.

Testing and monitoring MEV protection effectiveness

Once a bot deploys with a chosen MEV strategy, measuring whether it actually works is essential. The test is not whether MEV disappears but whether the realized slippage and costs match the expected levels. For a bot using a private relay, calculate the average slippage across transactions, compare it to equivalent transactions sent through public mempool on similar market conditions, and verify that the slippage reduction exceeds the relay fee.

Practical monitoring involves several metrics. First, on-chain slippage: the difference between the expected price based on pool state and the actual price at which the swap executed. This should be lower for private relay transactions. Second, **gas costs**: private relays may charge different effective gas costs than public mempool submissions, and this must be accounted for in profitability calculations. Third, **inclusion latency**: how long between submission and on-chain execution. Private relays may have longer latency even if they provide better price protection, and that is a trade-off to understand.

A useful audit is to run the same bot logic through two submission paths simultaneously on separate capital and compare results over a week or month of operation. If private relay transactions consistently show lower slippage and higher profitability despite higher fees, the strategy is working. If slippage is similar or worse, the fee is not justified and the bot should revert to public mempool or try a different relay operator.

Keep in mind that MEV dynamics change with market conditions and network state. During high-volatility periods, sandwich opportunities are more profitable and MEV protection becomes more valuable. During calm periods, MEV may be minimal and private relay fees are wasted. A bot might use a hybrid strategy: route small transactions through public mempool, large transactions through private relays, and adjust the thresholds based on realized sandwich losses over time.

When and why MEV protection fails

Private relay services and encrypted batch auctions are not invulnerable. Several failure modes deserve attention. First, relay operator incentives can misalign. If the relay captures MEV for itself rather than passing savings to the bot, the bot receives minimal benefit. Some relays are transparent about their cut; others are opaque. A bot should evaluate whether the relay’s published ordering rule actually protects against MEV or simply relocates the extraction opportunity from external searchers to the relay operator.

Second, encrypted batch auctions depend on cryptography and secure computation, which adds assumptions. If the threshold encryption scheme is broken, implemented incorrectly, or if an operator breaches the protocol, privacy is lost. This is not likely for mature systems, but it is a risk to model. A bot should not depend on encryption for legally required privacy; encryption provides protection against economic extraction but not against determined adversaries with access to infrastructure.

Third, privacy solutions do not protect against all forms of MEV. A bot’s strategy might be vulnerable to contract-level MEV, where an attacker manipulates state directly through protocol interaction rather than through mempool observation. Encrypted batch auctions protect against front-running and sandwiching but not against logic-level attacks that exploit the bot’s smart contract code or assumptions. If the bot calls a Uniswap pool with a slippage tolerance that is too high, a relay cannot protect against the bot approving a bad deal.

Fourth, timing analysis and correlation attacks can sometimes infer transaction contents even from encrypted submissions. If a bot always submits transactions at certain times or in response to visible market events, an observer might correlate transaction arrival with market movements and predict contents with reasonable probability. Encrypted batch auctions reduce this risk through batching multiple transactions together, but the risk is not zero.

Real-world bot architecture: A case study

A concrete example illustrates the decision-making process. Suppose a bot identifies arbitrage opportunities between Uniswap pools on Ethereum Layer 1, detecting price differences that persist for seconds and executing swaps to capture the spread. The bot’s profit per trade is $500 on average, and it executes 20 trades per day, or $10,000 in daily profit before MEV costs.

The bot starts with public mempool submission and measures results. Over a week, it accumulates data showing that 30% of trades are sandwiched with an average loss of $100 per sandwiched trade. That is roughly $300 in weekly MEV cost, or $43,000 annualized—a significant leak from a $3.65M annual gross profit. The operator investigates private relays. MEV-Protect charges 0.5% of transaction value on average; at $500 average swap size, this is $2.50 per transaction. For 20 trades per day, that is $50 per day, or $18,250 annualized. The MEV-Protect option saves $43,000 minus $18,250 = $24,750 per year while adding latency and monitoring complexity.

The bot’s operator implements MEV-Protect as a primary route and maintains public mempool as a fallback for high-urgency trades that cannot wait for batch inclusion. After one month of monitoring, the data confirms sandwich loss is nearly eliminated, and the net profit after relay fees is higher than before. The operator then experiments with an encrypted batch auction service that charges only 0.1% per transaction ($1 per transaction, $20 per day). Inclusion latency is slightly longer, but slippage is similar to MEV-Protect and the fee is lower. The bot routes half its volume through the batch auction and half through public mempool, optimizing for trade opportunity urgency and improving overall profitability.

This is the actual optimization process: measure, calculate, implement, monitor, and iterate. No single approach is universally optimal, and the best strategy for one bot may not be best for another. Understanding the costs and benefits with concrete numbers prevents spending money on protection that does not pay for itself.

Frequently asked questions

What is MEV and why does it matter for trading bots?

MEV (maximal extractable value) is value that can be extracted from a transaction by reordering, inserting, or censoring it. Front-running and sandwiching are forms of MEV extraction that cost traders money by moving prices unfavorably. For bots executing large transactions on public mempool, MEV losses can range from 0.05% to 0.5% or more, which can exceed the bot’s profit margin if margins are thin.

Should every Uniswap bot use a private relay or encrypted batch auction?

No. Private relays and batch auctions charge fees that may exceed the MEV protection they provide for small transactions. A bot executing 0.1 ETH swaps might face only $5 in sandwich loss but $10 in relay fees, making public mempool submission preferable despite MEV risk. The decision depends on transaction size, profit margin, and measured sandwich losses in your specific use case.

What is the difference between private relays and encrypted batch auctions?

Private relays (such as MEV-Protect) receive transactions in the clear and route them to validators or searchers outside the public mempool. Encrypted batch auctions keep transactions encrypted until after ordering is committed, preventing even the relay operator from observing transaction contents before execution. Encrypted batch auctions provide stronger privacy but typically have longer inclusion latency and lower fees. Private relays are faster but provide less privacy and often higher fees.

Social Sharing
Scroll to Top