Sub topic 7
Nonces and Transaction Ordering
This chapter assumes you know what an account and an address are, and that you understand gas fees at the level of the previous chapter. The code examples use JavaScript with ethers v6. The nonce model described here is the one used by Ethereum and other EVM-compatible networks.
What a nonce is
A nonce is a counter attached to an account. It records how many transactions that account has sent. The first transaction from a new account uses nonce 0, the next uses nonce 1, and so on.
The nonce is part of every transaction you sign. The network accepts a transaction only when its nonce is exactly the next number the account expects. This one rule does two jobs:
- It orders your transactions. Nonce 5 cannot run before nonce 4.
- It prevents replay. A signed transaction can be included only once, because after it runs, the account's nonce has moved past that number.
The word "nonce" also appears in proof-of-work mining, where it means something different. In this chapter it always means the account transaction counter.
Why the account model needs it
In the account model, a transaction says "move 0.5 from account A to account B". Nothing in that statement identifies it as a single, specific payment. If someone copied your signed transaction and broadcast it again, the network would have no reason to reject it unless something made it unique.
The nonce makes each signed transaction valid for exactly one position in the account's history. Once nonce 7 is used, a second copy of the same signed transaction is invalid.
Bitcoin-style UTXO chains solve this differently. Each transaction spends specific outputs, and an output can be spent only once, so no account-level counter is needed.
How the network applies nonces
When a node receives your transaction, it compares the transaction's nonce with the account's current nonce. There are three cases.
| Transaction nonce compared with account nonce | What happens |
|---|---|
| Lower than expected | Rejected. That nonce was already used. |
| Exactly the expected value | Valid. It can be included in the next block. |
| Higher than expected | Held back, typically in the node's pending pool, until the gap is filled. |
The third case is the source of many "stuck" transactions. If you send nonce 10 while the network is still waiting for nonce 9, nonce 10 sits in the pool. It does not fail. It waits.
Two counts: confirmed and pending
An account has more than one useful nonce value, depending on what you count.
- The confirmed nonce counts transactions that have been included in a block.
- The pending nonce also counts transactions that your node has seen but that are not yet in a block.
In ethers, you can read both by passing a block tag to getTransactionCount.
import { JsonRpcProvider } from "ethers";
const provider = new JsonRpcProvider(process.env.RPC_URL);
const address = process.env.ADDRESS;
const confirmed = await provider.getTransactionCount(address, "latest");
const pending = await provider.getTransactionCount(address, "pending");
console.log("Confirmed nonce:", confirmed);
console.log("Pending nonce:", pending);
if (pending > confirmed) {
console.log(`${pending - confirmed} transaction(s) are waiting to be included.`);
} else {
console.log("No transactions are waiting.");
}The value returned is the next nonce to use, which equals the number of transactions counted. If pending is larger than confirmed, at least one transaction from this account is still waiting.
A wallet application normally chooses the nonce for you, using the pending count. This works well for one transaction at a time. It becomes a problem when you send several quickly from code.
Ordering transactions from one account
Nonces fix the order of transactions from a single account. They do not order transactions between different accounts. Two separate accounts each have their own nonce sequence, and block producers decide how to arrange transactions from different senders, usually favoring higher fees.
This has practical consequences:
- If you send a payment and then a second payment from the same account, the second cannot be mined before the first. That order is guaranteed.
- If two different accounts send transactions at the same time, there is no guaranteed order between them.
- A gas price increase on nonce 8 does not help nonce 7 get included. Nonce 7 must go first regardless of what nonce 8 pays.
The last point matters in practice. If nonce 7 is underpriced and stuck, every later transaction from that account is blocked behind it, however much they offer.
Sending several transactions in a row
A common mistake is to fire several sends in a loop and let the library pick each nonce. If the library asks the node for the nonce each time, and the earlier transactions have not yet reached the node's pool, two sends can receive the same nonce. One will then replace or collide with the other.
The safer approach is to read the starting nonce once and assign nonces yourself.
import { JsonRpcProvider, Wallet, parseEther } from "ethers";
const provider = new JsonRpcProvider(process.env.RPC_URL);
const wallet = new Wallet(process.env.PRIVATE_KEY, provider);
const recipients = [
"0x0000000000000000000000000000000000000001",
"0x0000000000000000000000000000000000000002",
"0x0000000000000000000000000000000000000003",
];
let nonce = await provider.getTransactionCount(wallet.address, "pending");
const sent = [];
for (const to of recipients) {
const tx = await wallet.sendTransaction({
to,
value: parseEther("0.001"),
nonce,
});
console.log(`Nonce ${nonce} -> ${tx.hash}`);
sent.push(tx);
nonce += 1;
}
for (const tx of sent) {
const receipt = await tx.wait();
console.log(tx.hash, receipt.status === 1 ? "success" : "failed");
}The code reads the pending nonce once, increments it locally, and then waits for every transaction. Use a testnet and a throwaway key while you practice.
This approach has a limit. If your program crashes halfway through, your local counter is lost. On restart, read the nonce from the network again before sending anything.
Nonce gaps
A gap appears when a nonce is skipped. Suppose nonces 4 and 5 are sent, but 5 is dropped by a node, and you then send 6. The network expects 5. Nonce 6 waits, and nothing from the account moves until 5 arrives.
Typical causes of gaps:
- A transaction was dropped from the pool because its fee was too low or the pool was full.
- A transaction was sent to one node, and a later one to a different node that never saw the first.
- Code assigned nonces manually and skipped a number after an error.
To close a gap, send any valid transaction with the missing nonce. The next section shows a common way.
Replacing and cancelling a pending transaction
Because a nonce can be used only once, you can replace a transaction that has not been mined. You sign a new transaction with the same nonce and a higher fee. Nodes generally require the new fee to exceed the old one by a minimum margin, often around 10 percent. Check your network's rules, because the exact threshold is set by each node's software.
There are two common uses:
- Speed up. Resend the same transaction, with the same recipient and amount, and a higher fee.
- Cancel. Send a zero-value transaction from your account to itself, using the same nonce and a higher fee.
import { JsonRpcProvider, Wallet } from "ethers";
const provider = new JsonRpcProvider(process.env.RPC_URL);
const wallet = new Wallet(process.env.PRIVATE_KEY, provider);
const stuckNonce = await provider.getTransactionCount(wallet.address, "latest");
const feeData = await provider.getFeeData();
const bump = (value) => (value * 130n) / 100n;
const cancel = await wallet.sendTransaction({
to: wallet.address,
value: 0n,
nonce: stuckNonce,
maxFeePerGas: bump(feeData.maxFeePerGas),
maxPriorityFeePerGas: bump(feeData.maxPriorityFeePerGas),
});
console.log("Replacement submitted:", cancel.hash);
const receipt = await cancel.wait();
console.log("Status:", receipt.status === 1 ? "success" : "failed");This code reads the confirmed nonce, which is the next nonce the chain expects, so it targets the oldest unmined transaction. Fees are raised by 30 percent to clear the replacement threshold.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| "nonce too low" | The nonce was already used, or your local counter is behind | Read the nonce again from the network and resend |
| "replacement transaction underpriced" | You reused a nonce without raising the fee enough | Raise both max fee and priority fee, usually by at least 10 percent, more to be safe |
| Several transactions pending, none confirming | An earlier nonce is stuck or missing | Find the lowest pending nonce and replace it or fill the gap |
| Two sends from code collide | Both read the same nonce | Assign nonces yourself, as shown above |
| Wallet shows "pending" for a long time after you used the same account in two apps | Two apps each track their own nonce | Use one tool at a time, or read the pending nonce before each send |
Using the same account in more than one place
Importing one seed phrase into several wallet apps is allowed, but each app reads the nonce from the network separately. If you send from both within a short window, you can create a collision. A server that sends payments automatically has the same risk if several processes share one key.
For services that send many transactions, a common design is a single sender process or queue that owns the nonce counter, hands out numbers in order, and recovers by re-reading the network after a restart or an error.
Summary of the working model
- Each account has a counter, and each transaction must use the next value.
- Transactions from one account run in nonce order. Different accounts have no shared order.
- A transaction with a nonce that is too high waits. One that is too low is rejected.
- A stuck transaction blocks everything behind it, and a higher fee on a later transaction cannot help.
- You can replace a pending transaction by reusing its nonce with a higher fee, but only until it is mined.
Exercise
Your account has a confirmed nonce of 12. You send a transaction with nonce 12 that pays a very low fee and stays pending. You then send a second transaction with nonce 13 and a very high fee. Which transaction is included first, and what do you do to get both moving?
Show answer
Neither can be included before nonce 12, so nonce 12 must go first, whatever nonce 13 pays. Nonce 13 waits behind it. To get both moving, replace nonce 12 by sending a transaction with the same nonce and a higher fee, at least about 10 percent above the original. Once nonce 12 is mined, nonce 13 becomes eligible.
Exercise
A script sends five payments in a loop. Each call asks the node for the nonce just before sending. Two of the payments fail with a replacement or nonce error. Why does this happen, and how would you change the script?
Show answer
The earlier transactions may not yet appear in the node's pending count when the next one asks for a nonce, so two sends receive the same value. Read the pending nonce once before the loop, pass an explicit nonce to each send, and increase the local counter by one after each. After a crash or error, read the nonce from the network again.
Exercise
A cancel transaction (zero value, to yourself) was sent with the same nonce as a payment, but the original payment was still delivered. What most likely happened?
Show answer
The original payment was mined before the replacement reached the block producer, or before it was accepted. Once the original used that nonce, the replacement became invalid. A replacement only works if it is accepted while the original is still pending.