How Solana Priority Fees and Compute Units Work, With Code
The priority fee is price times the compute-unit limit you request, so a lazy default overpays on every transaction. Here is how to measure, price, cap and retry, with TypeScript.
By OnChain Team9 min read
A Solana priority fee is the price you set per compute unit (CU, the runtime's measure of work), multiplied by the compute-unit limit you request, and rounded up to a whole lamport. It is charged on the limit, not on what the transaction actually used. That one detail explains most of the money wasted on Solana fees: leave the limit at its default and you bid, and pay, for far more work than your transaction does. Both halves of the bid, how much work you ask for and how much you pay per unit of it, need their own measurement.
This guide builds a small sender in TypeScript that measures compute usage by simulation, prices the transaction from recent fees on the accounts it touches, caps the spend, and retries with a fresh blockhash and a higher price when a transaction expires.
How the two numbers work
Two instructions from the Compute Budget program control the bid. SetComputeUnitLimit says how many CUs the transaction may consume. SetComputeUnitPrice says how many micro-lamports (millionths of a lamport) you pay per CU. The fee on top of the per-signature base fee is, in the validator's own code, a ceiling division. The Agave source multiplies price by limit, adds 999,999 and divides by 1,000,000.
The limits come from the same codebase (execution_budget.rs):
- A transaction can request at most 1,400,000 CUs.
- Without a limit instruction, each non-builtin instruction is allotted 200,000 CUs. Builtin program instructions (the system program, for example) are allotted at most 3,000 each, as defined by SIMD-0170.
- Block space is also finite.
block_cost_limits.rscaps a block at 60,000,000 CUs in the current source, with a 100,000,000 variant defined for SIMD-0286, and caps any single writable account at 24,000,000 CUs per block.
That last cap is why which accounts you write to matters as much as how much you pay. A busy pool account is a queue of its own, and the going price is set by what others pay to write to that account, not by the network average.
Main flowSecondaryFailure pathSwipe to see the whole diagram →
Step 1: Do the maths before you write code
Put the fee formula in one function so every later decision can be checked against it.
const BASE_FEE_PER_SIGNATURE = 5_000; // lamports
// Mirrors the runtime: the price is in micro-lamports per CU, rounded up.
export function priorityFeeLamports(microLamportsPerCu: number, cuLimit: number) {
return Math.ceil((microLamportsPerCu * cuLimit) / 1_000_000);
}
export function totalFeeLamports(signatures: number, price: number, cuLimit: number) {
return signatures * BASE_FEE_PER_SIGNATURE + priorityFeeLamports(price, cuLimit);
}The base fee shown is the figure Solana's fee documentation gives at the time of writing. Treat it as a constant to verify, because fee parameters are set by the protocol and can change.
Now the arithmetic that matters. Take a price of 50,000 micro-lamports per CU:
→ Default limit of 200,000 CUs: ceil(50,000 × 200,000 / 1,000,000) = 10,000 lamports of priority fee.
→ A transaction that really uses 40,000 CUs and requests 44,000: 2,200 lamports.
Same transaction, same landing odds per unit price, a bit under a quarter of the cost. Across thousands of transactions a day, that gap is the whole fee budget.
Step 2: Measure compute units by simulation
Guessing a limit is how transactions fail with ComputationalBudgetExceeded. Measure instead. Simulate the transaction with the maximum limit so it cannot run out, read unitsConsumed from the response, and add a margin.
import {
ComputeBudgetProgram,
Connection,
PublicKey,
TransactionInstruction,
TransactionMessage,
VersionedTransaction,
} from "@solana/web3.js";
// Simulate with the maximum limit, read what the transaction really used, add margin.
export async function estimateComputeUnits(
connection: Connection,
payer: PublicKey,
instructions: TransactionInstruction[],
): Promise<number> {
const { blockhash } = await connection.getLatestBlockhash();
const message = new TransactionMessage({
payerKey: payer,
recentBlockhash: blockhash,
instructions: [
ComputeBudgetProgram.setComputeUnitLimit({ units: 1_400_000 }),
...instructions,
],
}).compileToV0Message();
const sim = await connection.simulateTransaction(new VersionedTransaction(message), {
sigVerify: false,
replaceRecentBlockhash: true, // the simulation needs no real signature or blockhash
});
if (sim.value.err)
throw new Error(`simulation failed: ${JSON.stringify(sim.value.err)}`);
const used = sim.value.unitsConsumed ?? 200_000;
return Math.ceil(used * 1.1); // 10% margin; state can shift before it lands
}Three details here. replaceRecentBlockhash lets the simulation run without a blockhash you fetched yourself, and sigVerify: false means you need no signature to simulate. The 10% margin is a judgement call, and the Solana guide on using priority fees makes the underlying point that a request below what the transaction needs makes it fail. And the number is only valid for the state you simulated: a swap through a pool whose liquidity moves can consume more units a second later. For routes whose cost varies, such as aggregator swaps, widen the margin or re-simulate just before sending.
One caveat: simulation costs an RPC call and a round trip. For a fixed instruction set, such as a plain token transfer, measure once, hard-code the limit and skip this step.
Step 3: Price from the accounts you will write to
The RPC method getRecentPrioritizationFees returns, per recent slot, the per-CU fee paid by at least one landed transaction. Called with no arguments it describes the cheapest way to land anywhere, which is a useless number for a swap on a hot pool. Pass the writable accounts of your own transaction and it reflects what it took to lock those accounts. The Solana guide above makes the same recommendation.
import { Connection, PublicKey } from "@solana/web3.js";
// Pick a percentile of recent fees paid by landed transactions that wrote
// to the same accounts you will write to.
export async function suggestPrice(
connection: Connection,
writableAccounts: PublicKey[],
percentile = 0.75,
floor = 1_000, // micro-lamports per CU; never go to zero on a busy account
): Promise<number> {
const recent = await connection.getRecentPrioritizationFees({
lockedWritableAccounts: writableAccounts,
});
const fees = recent.map((r) => r.prioritizationFee).sort((a, b) => a - b);
if (fees.length === 0) return floor;
const pick = fees[Math.min(fees.length - 1, Math.floor(fees.length * percentile))];
return Math.max(pick, floor);
}Two things to know about this data. Each entry is a fee that at least one landed transaction paid in that slot, not a price that guarantees inclusion, so a high percentile of the series is a safer bid than the latest value. And it is a lagging indicator: during a sudden rush it understates the going price. A percentile is a starting point for the first attempt, not a guarantee. The guide itself says there is no "perfect" way to set priority fees. That is why the next step retries.
Many providers sell their own fee estimate API. They are convenient and are often tuned better than a raw percentile, but they are still estimates from the same recent past.
Step 4: Send, cap and escalate
Here is where retries usually go wrong. A transaction carries a blockhash that is only valid for a limited window (the lastValidBlockHeight you get alongside it). If it has not landed by then it can never land, and the correct response is to build a new transaction with a fresh blockhash and a higher price. Re-sending the same bytes with a bigger price is not possible, because the price is part of the signed message.
Two failures need different handling. An on-chain error, such as a slippage check failing, is a real answer: paying more will not change it. Only expiry is evidence that you were outbid or dropped. The loop below escalates on expiry only, and stops at a hard per-transaction ceiling.
import {
ComputeBudgetProgram,
Connection,
Keypair,
TransactionInstruction,
TransactionExpiredBlockheightExceededError,
TransactionMessage,
VersionedTransaction,
} from "@solana/web3.js";
import { estimateComputeUnits } from "./measure";
import { suggestPrice } from "./price";
export async function sendWithEscalation(
connection: Connection,
payer: Keypair,
instructions: TransactionInstruction[],
maxAttempts = 4,
maxLamports = 200_000, // hard ceiling on the priority fee for this transaction
) {
const cuLimit = await estimateComputeUnits(connection, payer.publicKey, instructions);
const writable = instructions.flatMap((ix) =>
ix.keys.filter((k) => k.isWritable).map((k) => k.pubkey),
);
let price = await suggestPrice(connection, writable);
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
if ((price * cuLimit) / 1_000_000 > maxLamports) throw new Error("fee cap reached");
// Fresh blockhash on every attempt: an old one is what makes a retry expire.
const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash();
const message = new TransactionMessage({
payerKey: payer.publicKey,
recentBlockhash: blockhash,
instructions: [
ComputeBudgetProgram.setComputeUnitLimit({ units: cuLimit }),
ComputeBudgetProgram.setComputeUnitPrice({ microLamports: price }),
...instructions,
],
}).compileToV0Message();
const tx = new VersionedTransaction(message);
tx.sign([payer]);
const signature = await connection.sendTransaction(tx, { maxRetries: 0 });
try {
const result = await connection.confirmTransaction(
{ signature, blockhash, lastValidBlockHeight },
"confirmed",
);
// An on-chain error (slippage, bad input) will not be fixed by paying more.
if (result.value.err) throw new Error(JSON.stringify(result.value.err));
return signature;
} catch (e) {
if (!(e instanceof TransactionExpiredBlockheightExceededError)) throw e;
price = Math.ceil(price * 1.5); // never landed in time: outbid and retry
}
}
throw new Error("not landed after escalation");
}The fee cap is the most important line. Without it, a retry loop in a volatile market is an unbounded bill that you wrote yourself. A real system would also log each attempt's price and outcome, since that history is the only way to tune the percentile and the 1.5 multiplier from your own data instead of folklore.
maxRetries: 0 stops the RPC node from rebroadcasting on its own, so your loop is the only thing deciding when to retry. Whether that is better depends on your RPC provider, so test it against yours.
What priority fees do not do
A priority fee buys scheduling priority with the leader (the validator producing the current block). It does not protect you from sandwich attacks, and a fee is not a defence against being targeted. For that problem, see our MEV protection guide. It also does not replace bundle tips: if you send through Jito, you pay a tip instead of, or as well as, a priority fee, as covered in our cost breakdown.
The block limit above has a proposed increase (SIMD-0286) defined in the source, so check the Agave source or the Solana docs for the current figure before you hard-code one.
What we would do
Set an explicit compute-unit limit on every transaction, always. Measure it by simulation for variable routes and hard-code it for fixed ones. Price from a percentile of fees on the accounts you actually write to, set a per-transaction cap, and escalate only on blockhash expiry. Log every attempt, then tune from your own landing data. Resist any design that sets one global priority fee for the whole app; the right price differs per account and per minute.
For the surrounding system, our Solana trading platforms page describes how we handle transaction landing in the products we build. If you are deciding what to track about your own trades afterwards, this guide to real-time trader activity covers decoding them.
This is engineering guidance, not financial advice. Fee mechanics and limits change; code was checked against @solana/web3.js 1.99 and the Agave source on 2026-11-17.