> ## Documentation Index
> Fetch the complete documentation index at: https://solana.com/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> This page is part of the Solana developer documentation at https://solana.com/developers/docs. Append `.md` to any docs URL, or send `Accept: text/markdown`, to get the page as Markdown.
> Index of all pages: https://solana.com/llms.txt. Per-section indexes such as https://solana.com/developers/docs/payments/llms.txt are smaller; prefer them when working on one task.
> Coding agents: install the official Solana skill for current APIs and conventions with `npx skills add https://github.com/solana-foundation/solana-dev-skill` (also served at https://solana.com/SKILL.md).
> Code in the cookbook and task pages comes from tested example files. Prefer it over writing API calls from memory.

# Retrying Transactions

> Learn how to handle dropped transactions and implement custom retry logic on Solana. This guide covers transaction rebroadcasting, preflight checks, and best practices for managing transaction retries to ensure reliable transaction processing on the Solana blockchain.

On some occasions, a seemingly valid transaction may be dropped before it is
included in a block. This most often occurs during periods of network
congestion, when an RPC node fails to rebroadcast the transaction to the
[leader](/developers/docs/references/terminology#leader). To an end-user, it may appear as
if their transaction disappears entirely. While RPC nodes are equipped with a
generic rebroadcasting algorithm, application developers are also capable of
developing their own custom rebroadcasting logic.

## TLDR;

- RPC nodes will attempt to rebroadcast transactions using a generic algorithm
- Application developers can implement their own custom rebroadcasting logic
- Developers should take advantage of the `maxRetries` parameter on the
  `sendTransaction` JSON-RPC method
- Developers should enable preflight checks to raise errors before transactions
  are submitted
- Before re-signing any transaction, it is **very important** to ensure that the
  initial transaction's blockhash has expired

## The Journey of a Transaction

### How Clients Submit Transactions

In Solana, there is no concept of a mempool. All transactions, whether they are
initiated programmatically or by an end-user, are efficiently routed to leaders
so that they can be processed into a block. There are two main ways in which a
transaction can be sent to leaders:

1. By proxy via an RPC server and the
   [sendTransaction](/developers/docs/rpc/http/sendtransaction) JSON-RPC method
2. Directly to leaders via a
   [TPU Client](https://docs.rs/solana-client/latest/solana_client/tpu_client/index.html)

The vast majority of end-users will submit transactions via an RPC server. When
a client submits a transaction, the receiving RPC node will in turn attempt to
broadcast the transaction to both the current and next leaders. Until the
transaction is processed by a leader, there is no record of the transaction
outside of what the client and the relaying RPC nodes are aware of. In the case
of a TPU client, rebroadcast and leader forwarding is handled entirely by the
client software.

<Frame caption="Overview of a transactions journey, from client to leader">
  ![Overview of a transactions journey, from client to leader](/docs-assets/assets/docs/rt-tx-journey.png)
</Frame>

### How RPC Nodes Broadcast Transactions

After an RPC node receives a transaction via `sendTransaction`, it will convert
the transaction into a
[UDP](https://en.wikipedia.org/wiki/User_Datagram_Protocol) packet before
forwarding it to the relevant leaders. UDP allows validators to quickly
communicate with one another, but does not provide any guarantees regarding
transaction delivery.

Because Solana's leader schedule is known in advance of every
[epoch](/developers/docs/references/terminology#epoch) (432,000 slots, about 24
hours at 200ms slots), an RPC node will
broadcast its transaction directly to the current and next leaders. This is in
contrast to other gossip protocols such as Ethereum that propagate transactions
randomly and broadly across the entire network. By default, RPC nodes will try
to forward transactions to leaders every two seconds until either the
transaction is finalized or the transaction's blockhash expires (150 blocks,
about 30 seconds at 200ms slots). If the outstanding
rebroadcast queue size is greater than
[10,000 transactions](https://github.com/solana-labs/solana/blob/bfbbc53dac93b3a5c6be9b4b65f679fdb13e41d9/send-transaction-service/src/send_transaction_service.rs#L20),
newly submitted transactions are dropped. There are command-line
[arguments](https://github.com/solana-labs/solana/blob/bfbbc53dac93b3a5c6be9b4b65f679fdb13e41d9/validator/src/main.rs#L1172)
that RPC operators can adjust to change the default behavior of this retry
logic.

When an RPC node broadcasts a transaction, it will attempt to forward the
transaction to a leader's
[Transaction Processing Unit (TPU)](https://github.com/solana-labs/solana/blob/cd6f931223181d5a1d47cba64e857785a175a760/core/src/validator.rs#L867).
The TPU processes transactions in four main stages:

- [Fetch Stage](https://github.com/solana-labs/solana/blob/cd6f931223181d5a1d47cba64e857785a175a760/core/src/fetch_stage.rs#L21)
- [SigVerify Stage](https://github.com/solana-labs/solana/blob/cd6f931223181d5a1d47cba64e857785a175a760/core/src/tpu.rs#L91)
- [Banking Stage](https://github.com/solana-labs/solana/blob/cd6f931223181d5a1d47cba64e857785a175a760/core/src/banking_stage.rs#L249)
- [Broadcast Stage](https://github.com/solana-labs/solana/blob/cd6f931223181d5a1d47cba64e857785a175a760/core/src/tpu.rs#L136)

Of these stages, the Fetch Stage is responsible for receiving transactions.
Within the Fetch Stage, validators will categorize incoming transactions
according to two ports:

- [tpu](https://github.com/solana-labs/solana/blob/cd6f931223181d5a1d47cba64e857785a175a760/gossip/src/contact_info.rs#L27)
  handles regular transactions such as token transfers, NFT mints, and program
  instructions
- [tpu_forwards](https://github.com/solana-labs/solana/blob/cd6f931223181d5a1d47cba64e857785a175a760/gossip/src/contact_info.rs#L29)
  forwards unprocessed packets to the next leader if the current leader is
  unable to process all transactions

Validator votes don't pass through the TPU. They aren't transactions; validators
send them directly to each other.

For more information on the TPU, please refer to
[this excellent writeup by Jito Labs](https://jito-labs.medium.com/solana-validator-101-transaction-processing-90bcdc271143).

## How Transactions Get Dropped

Throughout a transaction's journey, there are a few scenarios in which the
transaction can be unintentionally dropped from the network.

### Before a transaction is processed

If the network drops a transaction, it will most likely do so before the
transaction is processed by a leader. UDP
[packet loss](https://en.wikipedia.org/wiki/Packet_loss) is the simplest reason
why this might occur. During times of intense network load, it's also possible
for validators to become overwhelmed by the sheer number of transactions
required for processing. While validators are equipped to forward surplus
transactions via `tpu_forwards`, there is a limit to the amount of data that can
be
[forwarded](https://github.com/solana-labs/solana/blob/cd6f931223181d5a1d47cba64e857785a175a760/core/src/banking_stage.rs#L364-L370).
Furthermore, each forward is limited to a single hop between validators. That
is, transactions received on the `tpu_forwards` port are not forwarded on to
other validators.

There are also two lesser known reasons why a transaction may be dropped before
it is processed. The first scenario involves transactions that are submitted via
an RPC pool. Occasionally, part of the RPC pool can be sufficiently ahead of the
rest of the pool. This can cause issues when nodes within the pool are required
to work together. In this example, the transaction's
[recentBlockhash](/developers/docs/core/transactions/transaction-structure#recent-blockhash)
is queried from the advanced part of the pool (Backend A). When the transaction
is submitted to the lagging part of the pool (Backend B), the nodes will not
recognize the advanced blockhash and will drop the transaction. This can be
detected upon transaction submission if developers enable
[preflight checks](/developers/docs/rpc/http/sendtransaction) on `sendTransaction`.

<Frame caption="Transaction dropped via an RPC Pool">
  ![Transaction dropped via an RPC Pool](/docs-assets/assets/docs/rt-dropped-via-rpc-pool.png)
</Frame>

Skipped blocks can also result in dropped transactions. A block that an RPC node
has processed can still be skipped by the cluster instead of finalized. If a
client builds a transaction that references a `recentBlockhash` from that block,
the transaction is dropped because the blockhash is not found on the finalized
chain.

<Frame caption="Transaction dropped because its blockhash is from a skipped block (before processed)">
  ![Transaction dropped because its blockhash is from a skipped block (before processed)](/docs-assets/assets/docs/rt-dropped-minority-fork-pre-process.png)
</Frame>

### After a transaction is processed and before it is finalized

A transaction can also be processed in a block that the cluster then skips
instead of finalizing, for example because the block didn't reach enough
validators in time. The transaction is dropped with that block, before it could
be finalized.

<Frame caption="Transaction dropped because its block was skipped (after processed)">
  ![Transaction dropped because its block was skipped (after processed)](/docs-assets/assets/docs/rt-dropped-minority-fork-post-process.png)
</Frame>

## Handling Dropped Transactions

While RPC nodes will attempt to rebroadcast transactions, the algorithm they
employ is generic and often ill-suited for the needs of specific applications.
To prepare for times of network congestion, application developers should
customize their own rebroadcasting logic.

### An In-Depth Look at sendTransaction

When it comes to submitting transactions, the `sendTransaction` RPC method is
the primary tool available to developers. `sendTransaction` is only responsible
for relaying a transaction from a client to an RPC node. If the node receives
the transaction, `sendTransaction` will return the transaction id that can be
used to track the transaction. A successful response does not indicate whether
the transaction will be processed or finalized by the cluster.

### Request Parameters

- `transaction`: `string` - fully-signed Transaction, as encoded string
- (optional) `configuration object`: `object`
  - `skipPreflight`: `boolean` - if true, skip the preflight transaction checks
    (default: false)
  - (optional) `preflightCommitment`: `string` -
    [Commitment](/developers/docs/rpc/#configuring-state-commitment) level to use for
    preflight simulations against the bank slot (default: "finalized").
  - (optional) `encoding`: `string` - Encoding used for the transaction data.
    Either "base58" (slow), or "base64". (default: "base58").
  - (optional) `maxRetries`: `usize` - Maximum number of times for the RPC node
    to retry sending the transaction to the leader. If this parameter is not
    provided, the RPC node will retry the transaction until it is finalized or
    until the blockhash expires.

**Response:**

- `transaction id`: `string` - First transaction signature embedded in the
  transaction, as base-58 encoded string. This transaction id can be used with
  [`getSignatureStatuses`](/developers/docs/rpc/http/getsignaturestatuses) to poll for
  status updates.

## Customizing Rebroadcast Logic

In order to develop their own rebroadcasting logic, developers should take
advantage of `sendTransaction`'s `maxRetries` parameter. If provided,
`maxRetries` will override an RPC node's default retry logic, allowing
developers to manually control the retry process
[within reasonable bounds](https://github.com/solana-labs/solana/blob/98707baec2385a4f7114d2167ef6dfb1406f954f/validator/src/main.rs#L1258-L1274).

A common pattern for manually retrying transactions involves temporarily storing
the `lastValidBlockHeight` that comes from
[getLatestBlockhash](/developers/docs/rpc/http/getlatestblockhash). Once stashed, an
application can then
[poll the cluster's blockheight](/developers/docs/rpc/http/getblockheight) and manually
retry the transaction at an appropriate interval. In times of network
congestion, it's advantageous to set `maxRetries` to 0 and manually rebroadcast
via a custom algorithm. While some applications may employ an
[exponential backoff](https://en.wikipedia.org/wiki/Exponential_backoff)
algorithm, others such as Mango opt to
[continuously resubmit](https://github.com/blockworks-foundation/mango-ui/blob/b6abfc6c13b71fc17ebbe766f50b8215fa1ec54f/src/utils/send.tsx#L713)
transactions at a constant interval until some timeout has occurred.

<CodeGroup>

<Warning>
  **`@solana/web3.js` 1.x is no longer actively maintained**

  It receives critical fixes only. Use [Kit](/developers/docs/clients/official/javascript#solana-kit) for new code. To migrate existing code, follow the [Kit upgrade guide](https://www.solanakit.com/docs/upgrade-guide), or the [web3.js v3 migration guide](https://github.com/solana-foundation/solana-web3.js/blob/main/docs/web3js-v1-to-v3-migration.md) to keep the class-based API.

  To run this code, install 1.x with `npm install @solana/web3.js@1`. A plain `npm install @solana/web3.js` installs v3, which this code doesn't run on.
</Warning>

```ts title="Web3.js (legacy)"
import {
  Keypair,
  Connection,
  LAMPORTS_PER_SOL,
  SystemProgram,
  Transaction
} from "@solana/web3.js";
import nacl from "tweetnacl";

const sleep = async (ms: number) => {
  return new Promise((r) => setTimeout(r, ms));
};

(async () => {
  const payer = Keypair.generate();
  const toAccount = Keypair.generate().publicKey;

  const connection = new Connection("http://127.0.0.1:8899", "confirmed");

  const airdropSignature = await connection.requestAirdrop(
    payer.publicKey,
    LAMPORTS_PER_SOL
  );
  await connection.confirmTransaction({
    signature: airdropSignature,
    ...(await connection.getLatestBlockhash())
  });

  // The transaction can land until the block height passes lastValidBlockHeight
  const { blockhash, lastValidBlockHeight } =
    await connection.getLatestBlockhash();

  const transaction = new Transaction({
    feePayer: payer.publicKey,
    blockhash,
    lastValidBlockHeight
  }).add(
    SystemProgram.transfer({
      fromPubkey: payer.publicKey,
      toPubkey: toAccount,
      lamports: 1000000
    })
  );
  const message = transaction.serializeMessage();
  const signature = nacl.sign.detached(message, payer.secretKey);
  transaction.addSignature(payer.publicKey, Buffer.from(signature));
  const rawTransaction = transaction.serialize();

  // maxRetries: 0 turns off the RPC node's own rebroadcasting
  const txid = await connection.sendRawTransaction(rawTransaction, {
    skipPreflight: true,
    maxRetries: 0
  });

  // Resend the same signed transaction every 500 ms until it is confirmed or
  // its blockhash expires
  let blockheight = await connection.getBlockHeight();
  while (blockheight <= lastValidBlockHeight) {
    await sleep(500);
    const { value: status } = await connection.getSignatureStatus(txid);
    // A "processed" transaction can still be dropped, so wait for "confirmed"
    if (
      status?.confirmationStatus === "confirmed" ||
      status?.confirmationStatus === "finalized"
    ) {
      if (status.err) {
        throw new Error(`Transaction failed: ${JSON.stringify(status.err)}`);
      }
      console.log("Signature:", txid);
      return;
    }
    await connection
      .sendRawTransaction(rawTransaction, { skipPreflight: true, maxRetries: 0 })
      .catch(() => {}); // a node may reject a copy it already processed
    blockheight = await connection.getBlockHeight();
  }
  throw new Error("Blockhash expired: sign the transaction again");
})();
```

```py Python
import asyncio

from solana.rpc.async_api import AsyncClient
from solana.rpc.commitment import Confirmed
from solana.rpc.models import TxOpts
from solders.keypair import Keypair
from solders.message import MessageV0
from solders.system_program import TransferParams, transfer
from solders.transaction import VersionedTransaction
from solders.transaction_status import TransactionConfirmationStatus


async def main():
    async with AsyncClient("http://localhost:8899", commitment=Confirmed) as client:
        payer = Keypair()
        to_account = Keypair().pubkey()
        airdrop = await client.request_airdrop(payer.pubkey(), 1_000_000_000)
        await client.confirm_transaction(airdrop.value)

        latest = (await client.get_latest_blockhash()).value
        transfer_instruction = transfer(
            TransferParams(
                from_pubkey=payer.pubkey(), to_pubkey=to_account, lamports=1_000_000
            )
        )
        message = MessageV0.try_compile(
            payer.pubkey(), [transfer_instruction], [], latest.blockhash
        )
        transaction = VersionedTransaction(message, [payer])
        raw_transaction = bytes(transaction)
        signature = transaction.signatures[0]

        # Resend the same signed transaction until it lands or its blockhash expires.
        # max_retries=0 turns off the RPC node's own rebroadcasting.
        while (await client.get_block_height()).value <= latest.last_valid_block_height:
            await client.send_raw_transaction(
                raw_transaction, opts=TxOpts(skip_preflight=True, max_retries=0)
            )
            await asyncio.sleep(0.5)
            status = (await client.get_signature_statuses([signature])).value[0]
            # Keep resending until confirmed: a "processed" transaction can still be dropped.
            if (
                status is not None
                and status.confirmation_status != TransactionConfirmationStatus.Processed
            ):
                if status.err:
                    raise RuntimeError(f"Transaction failed: {status.err}")
                break

        print("Signature:", signature)


asyncio.run(main())
```

```go Go
package main

import (
	"context"
	"fmt"
	"time"

	"github.com/solana-foundation/solana-go/v2"
	"github.com/solana-foundation/solana-go/v2/programs/system"
	"github.com/solana-foundation/solana-go/v2/rpc"
)

func main() {
	ctx := context.Background()
	client := rpc.New("http://localhost:8899")

	payer := solana.NewWallet()
	toAccount := solana.NewWallet().PublicKey()
	_, err := client.RequestAirdrop(ctx, payer.PublicKey(), solana.LAMPORTS_PER_SOL, rpc.CommitmentConfirmed)
	if err != nil {
		panic(err)
	}
	time.Sleep(2 * time.Second)

	latest, err := client.GetLatestBlockhash(ctx, rpc.CommitmentConfirmed)
	if err != nil {
		panic(err)
	}
	tx, err := solana.NewTransaction(
		[]solana.Instruction{
			system.NewTransferInstruction(1_000_000, payer.PublicKey(), toAccount).Build(),
		},
		latest.Value.Blockhash,
		solana.TransactionPayer(payer.PublicKey()),
	)
	if err != nil {
		panic(err)
	}
	tx.Sign(func(solana.PublicKey) *solana.PrivateKey { return &payer.PrivateKey })
	rawTx, err := tx.MarshalBinary()
	if err != nil {
		panic(err)
	}
	signature := tx.Signatures[0]

	// Resend the same signed transaction until it lands or its blockhash expires.
	// MaxRetries 0 turns off the RPC node's own rebroadcasting.
	maxRetries := uint(0)
	for {
		height, err := client.GetBlockHeight(ctx, rpc.CommitmentConfirmed)
		if err != nil {
			panic(err)
		}
		if height > latest.Value.LastValidBlockHeight {
			break
		}
		client.SendRawTransactionWithOpts(ctx, rawTx, rpc.TransactionOpts{SkipPreflight: true, MaxRetries: &maxRetries})
		time.Sleep(500 * time.Millisecond)
		statuses, err := client.GetSignatureStatuses(ctx, false, signature)
		if err != nil {
			panic(err)
		}
		// Keep resending until confirmed: a "processed" transaction can still be dropped.
		if status := statuses.Value[0]; status != nil && status.ConfirmationStatus != rpc.ConfirmationStatusProcessed {
			if status.Err != nil {
				panic(fmt.Sprintf("transaction failed: %v", status.Err))
			}
			break
		}
	}

	fmt.Println("Signature:", signature)
}
```

</CodeGroup>

When polling via `getLatestBlockhash`, applications should specify their
intended [commitment](/developers/docs/rpc/#configuring-state-commitment) level. By setting
its commitment to `finalized` (about 150ms after the block is produced;
`confirmed` is equivalent), an application avoids polling a blockhash from a
block that is later skipped.

If an application has access to RPC nodes behind a load balancer, it can also
choose to divide its workload amongst specific nodes. RPC nodes that serve
data-intensive requests such as
[getProgramAccounts](/developers/docs/rpc/http/getprogramaccounts) may be prone to falling
behind and can be ill-suited for also forwarding transactions. For applications
that handle time-sensitive transactions, it may be prudent to have dedicated
nodes that only handle `sendTransaction`.

### The Cost of Skipping Preflight

By default, `sendTransaction` will perform three preflight checks prior to
submitting a transaction. Specifically, `sendTransaction` will:

- Verify that all signatures are valid
- Check that the referenced blockhash is within the last 150 blocks
- Simulate the transaction against the bank slot specified by the
  `preflightCommitment`

In the event that any of these three preflight checks fail, `sendTransaction`
will raise an error prior to submitting the transaction. Preflight checks can
often be the difference between losing a transaction and allowing a client to
gracefully handle an error. To ensure that these common errors are accounted
for, it is recommended that developers keep `skipPreflight` set to `false`.

### When to Re-Sign Transactions

Despite all attempts to rebroadcast, there may be times in which a client is
required to re-sign a transaction. Before re-signing any transaction, it is
**very important** to ensure that the initial transaction's blockhash has
expired. If the initial blockhash is still valid, it is possible for both
transactions to be accepted by the network. To an end-user, this would appear as
if they unintentionally sent the same transaction twice.

In Solana, a dropped transaction can be safely discarded once the blockhash it
references is older than the `lastValidBlockHeight` received from
`getLatestBlockhash`. Developers should keep track of this
`lastValidBlockHeight` by querying [`getEpochInfo`](/developers/docs/rpc/http/getepochinfo)
and comparing with `blockHeight` in the response. Once a blockhash is
invalidated, clients may re-sign with a newly-queried blockhash.
