Transactions, Instructions, and Execution
12 min read
Welcome to Module 3! In previous modules, you learned that Solana accounts are just passive storage bins holding raw bytes and lamports. But storage bins don't do anything on their own. If you want to transfer tokens, swap on an AMM, or mint an NFT, you need an engine to mutate that state.
That engine is the transaction.
In this guide, you will learn how transactions are structured under the hood, how Solana's parallel runtime (Sealevel) reads your instructions, how to tune your Compute Units so your transactions don't get stuck in traffic, and how Address Lookup Tables (ALTs) allow modern Solana apps to pack massive amounts of data into tiny network packets.
1. Anatomy of a Transaction and Instruction Data
The Definition
A Transaction is an atomic bundle of one or more instructions sent to the cluster to be signed, executed, and committed to the ledger. If any single instruction fails, the entire transaction reverts, leaving account states untouched (though network fees are still deducted).
An Instruction is the smallest operational unit of execution on Solana. It specifies which program to call, which accounts that program is allowed to read or write, and what raw input data (arguments) to pass to it.
┌────────────────────────────────────────────────────────┐
│ Transaction │
│ ┌──────────────────────────────────────────────────┐ │
│ │ Signatures Array: [Sig1, Sig2, ...] │ │
│ └──────────────────────────────────────────────────┘ │
│ ┌──────────────────────────────────────────────────┐ │
│ │ Message │ │
│ │ ├─ Header (num signers, read-only counts, etc.) │ │
│ │ ├─ Account Keys Array: [Pubkey1, Pubkey2, ...] │ │
│ │ ├─ Recent Blockhash (prevents replay attacks) │ │
│ │ └─ Instructions Array: │ │
│ │ ├─ Instruction 0: [ProgramID, Keys, Data] │ │
│ │ └─ Instruction 1: [ProgramID, Keys, Data] │ │
│ └──────────────────────────────────────────────────┘ │
└────────────────────────────────────────────────────────┘The Problem It Solves
On traditional EVM chains, a transaction calls one contract entrypoint, which can then dynamically call other contracts on the fly without declaring touched storage keys upfront.
While dynamic calls sound flexible, they create a massive bottleneck: the validator cannot know which parts of the database will be touched until the smart contract is already running. Consequently, EVM nodes must process transactions sequentially on a single thread.
Solana takes the opposite approach: Explicit Upfront Declaration. Every transaction must declare every account it plans to inspect or mutate before execution starts. Because the runtime knows this in advance, it can schedule thousands of non-overlapping transactions across different CPU cores simultaneously.
The Anatomy of an Instruction
Every instruction submitted to a program contains exactly three fields:
programId(PublicKey): The address of the on-chain program you are invoking (e.g., the System Program, Token Program, or a custom Anchor program).keys(AccountMeta[]): A list of account metadata objects describing every account the program needs access to during this instruction.data(Buffer/ byte array): Serialized binary arguments telling the program what action to take (e.g., an instruction discriminator + amount to transfer).
import { PublicKey, TransactionInstruction } from "@solana/web3.js";
// Creating a raw instruction from scratch
const instruction = new TransactionInstruction({
programId: new PublicKey("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"), // Memo Program
keys: [
// AccountMeta: { pubkey, isSigner, isWritable }
{ pubkey: senderPublicKey, isSigner: true, isWritable: false }
],
// Data is passed as raw bytes (UTF-8 bytes of our memo text)
data: Buffer.from("Hello from freeCodeCamp Solana Guide!", "utf-8"),
});Scope & Boundaries: The 1,232-Byte Hard Limit 🛑
Solana transactions have a strict ceiling: 1,232 bytes.
Why this specific number? Solana's network layer operates over UDP using a standard Maximum Transmission Unit (MTU) size of 1,280 bytes (the minimum guaranteed IPv6 packet size across the global internet). Once you subtract 40 bytes for the IPv6 header and 8 bytes for the UDP header, exactly 1,232 bytes remain for the transaction packet.
- What is possible: You can bundle 5, 10, or even 20 instructions into a single transaction—provided the total serialized byte count (signatures + account keys + instruction data) stays at or below 1,232 bytes.
- What is NOT possible: You cannot send a 1,233-byte transaction. The validator's network stack will drop it immediately at the transport layer before any program even sees it.
2. Signers, Read-Only, and Writable Account Flags
The Definition
When declaring accounts in an instruction's keys array, every account is wrapped in an AccountMeta structure containing two critical boolean flags:
isSigner: Did the private key corresponding to this public key sign this transaction?isWritable: Will this account's internal state (lamports, data, or owner) change during execution?
export interface AccountMeta {
pubkey: PublicKey;
isSigner: boolean;
isWritable: boolean;
}The Problem It Solves
How does Solana achieve tens of thousands of transactions per second on bare-metal hardware without corrupting state?
Enter Sealevel, Solana's parallel runtime.
Think of Sealevel like a high-end database handling concurrent read/write locks:
- If Transaction A is writing to Account
Alice, no other transaction can read or write to AccountAliceuntil Transaction A finishes. - If Transaction B and Transaction C are only reading Account
Alice, both can run concurrently on different CPU cores. - If Transaction D writes to Account
Boband Transaction E writes to AccountCharlie, both run completely in parallel because their writable sets do not intersect.
Thread 1: [Tx A: Writes to Alice] ───> [Tx C: Reads Alice]
Thread 2: [Tx D: Writes to Bob] ───> [Tx E: Writes to Charlie]The Rules of the Road
- Signer Verification: If your on-chain program checks
account.is_signer == true, but the transaction was not signed by that key pair, the transaction fails with an authorization error. - Writable Enforcement: If your program tries to mutate lamports or modify data bytes of an account that was passed with
isWritable: false, the runtime halts execution and reverts the transaction. - The Privilege Rule: An instruction can demote privileges, but never promote them. If Account X is marked as read-only in the transaction message header, an individual instruction cannot treat Account X as writable.
What is Possible vs. What is NOT
- Can you mark every account as writable "just to be safe"?
Technically, yes, the transaction will serialize. However, you should never do this. Marking an account as writable locks that account across the entire validator. If your app marks a popular pool (like a SOL-USDC liquidity pool) as writable when it only needs to read the price, every other transaction on Solana trying to use that pool must wait in line behind you. Over-locking accounts tanks your transaction landing rate. - Can a program modify an account it does not own?
No. Programs can only write data to accounts whereaccount.owner == programId. A program can, however, credit lamports to any account, or deduct lamports from accounts owned by itself.
3. Compute Units, Fees, and Priority Fee Optimization
The Definition
A Compute Unit (CU) is the measure of computational resources (CPU instructions, memory allocations, cryptographic operations) consumed by an on-chain program.
Every instruction executed consumes CUs until the transaction completes or exhausts its budget.
The Problem It Solves
Without execution metering, a malicious user could deploy an infinite loop (while (true) {}) and freeze the validator's CPU. EVM solves this with "Gas". Solana solves this with Compute Budgets.
On Solana, transaction fees consist of two parts:
- Base Fee: Fixed at 5,000 lamports (0.000005 SOL) per signature. If your transaction has 1 signature, the base fee is 5,000 lamports. If it has 2 signers, it costs 10,000 lamports.
- Priority Fee: An optional tip paid to the validator to incentivize them to prioritize your transaction when accounts are congested.
Understanding the Compute Budget Limits
- Default CU per Transaction: 200,000 CUs (unless requested otherwise).
- Maximum CU per Transaction: 1,400,000 CUs (the hard ceiling for any single transaction).
- If your transaction uses 200,001 CUs under the default budget, it halts immediately with an error:
Program failed to complete: ComputationalBudgetExceeded. Your fees are still burned!
How Priority Fees Work
Unlike Ethereum's global gas auction, Solana uses localized fee markets. Priority fees are priced in Micro-Lamports per Compute Unit ().
💡 The Pro-Tip: Validators sort transactions by fee density (). If you request 1,400,000 CUs but only use 40,000 CUs, you are penalized because the validator reserves the full 1,400,000 CUs on its scheduling thread. Always set your CU limit close to your actual consumption!
Hands-on: Requesting Custom CUs and Priority Fees
You adjust your compute budget by adding instructions from the ComputeBudgetProgram to the top of your transaction.
import {
ComputeBudgetProgram,
TransactionMessage,
VersionedTransaction,
Connection,
PublicKey
} from "@solana/web3.js";
// Step 1: Set the exact CU limit you need
const setComputeLimitIx = ComputeBudgetProgram.setComputeUnitLimit({
units: 85_000, // Determined via simulation + a 10-15% safety buffer
});
// Step 2: Set the priority fee price
const setPriorityFeeIx = ComputeBudgetProgram.setComputeUnitPrice({
microLamports: 50_000, // 50,000 micro-lamports per CU (~0.05 lamports/CU)
});
// Calculate the extra priority fee paid:
// (85,000 units * 50,000 micro-lamports) / 1,000,000 = 4,250 lamports (~0.00000425 SOL)4. Versioned Transactions and Address Lookup Tables (ALTs)
The Definition
Versioned Transactions allow the Solana runtime to support multiple transaction formats. Currently, Solana supports:
legacy: The original transaction format.0(v0): The modern format introducing support for Address Lookup Tables (ALTs).
An Address Lookup Table (ALT) is an on-chain account that stores an array of up to 256 account public keys.
The Problem It Solves
Remember the 1,232-byte packet ceiling?
Every public key takes up 32 bytes.
If an advanced DeFi transaction (e.g., a multi-hop swap through Jupiter across Raydium, Orca, and Phoenix) touches 35 accounts:
Add the signatures and instruction data, and the transaction blows past the 1,232-byte limit. For years, complex composability was blocked by this single constraint.
The Solution: Address Lookup Tables
Instead of inlining the full 32-byte public key inside the transaction, you store the public keys once in an on-chain table. Inside your transaction, you reference the address using a 1-byte index (0 to 255).
Traditional Transaction:
[ 32-byte Pubkey A ] [ 32-byte Pubkey B ] [ 32-byte Pubkey C ] = 96 bytes
v0 Transaction using ALT:
[ 1-byte index (0x00) ] [ 1-byte index (0x01) ] [ 1-byte index (0x02) ] = 3 bytes!By compressing 32 bytes into 1 byte, a single transaction can load up to 64 accounts without exceeding the 1,232-byte network limit.
┌─────────────────────────────────────────────────────────┐
│ On-Chain Address Lookup Table (ALT) │
│ Index 0: 7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU │
│ Index 1: EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v │
│ Index 2: So11111111111111111111111111111111111111112 │
└─────────────────────────────────────────────────────────┘
▲
│ Resolves index pointers
┌────────────────────────────┴────────────────────────────┐
│ Versioned Transaction (v0) │
│ ALT Pointer: <ALT_Pubkey> │
│ Loaded Accounts: [ Index 0, Index 1, Index 2 ] │
│ Total address payload: ~3 bytes instead of 96 bytes! │
└─────────────────────────────────────────────────────────┘Boundary & Scope: What ALTs CANNOT Do ⚠️
ALTs CANNOT store transaction signers.
Any account that needs to sign the transaction (isSigner: true) must be explicitly included in the transaction's primary account keys array as a full 32-byte public key.Why? The validator verifies cryptographic signatures at the network layer before loading state from the database. It cannot inspect an ALT on-chain to figure out who was supposed to sign the packet.
Hands-on: Building a v0 Transaction with an ALT
import {
Connection,
PublicKey,
TransactionMessage,
VersionedTransaction,
AddressLookupTableAccount,
} from "@solana/web3.js";
async function sendV0Transaction(
connection: Connection,
payer: PublicKey,
instructions: any[],
lookupTableAddress: PublicKey
) {
// 1. Fetch the recent blockhash
const { blockhash } = await connection.getLatestBlockhash();
// 2. Fetch the Address Lookup Table account from the cluster
const lookupTableAccount = (
await connection.getAddressLookupTable(lookupTableAddress)
).value;
if (!lookupTableAccount) {
throw new Error("Lookup table not found!");
}
// 3. Compile the message using TransactionMessage (v0)
const messageV0 = new TransactionMessage({
payerKey: payer,
recentBlockhash: blockhash,
instructions: instructions,
}).compileToV0Message([lookupTableAccount]); // Pass lookup tables here
// 4. Create the VersionedTransaction instance
const transaction = new VersionedTransaction(messageV0);
// Ready to sign and send:
// transaction.sign([payerKeypair]);
// await connection.sendTransaction(transaction);
return transaction;
}Concept Check 🧠
Let's test your mental model before moving to the next module:
| Scenario | What happens? | Why? |
|---|---|---|
| A transaction uses 205,000 CUs without requesting a higher budget. | ❌ Fails with ComputationalBudgetExceeded |
The default ceiling is 200,000 CUs. The transaction halts, state reverts, and the base fee is still charged. |
| You put a required signer's pubkey inside an Address Lookup Table (ALT). | ❌ Fails during serialization / verification | Signers must exist in the transaction message header so validators can verify signatures before disk reads. |
| Two completely unrelated users transfer SOL to two completely different merchants at the exact same millisecond. | ✅ Executes concurrently on parallel threads | Neither transaction writes to intersecting accounts; Sealevel parallelizes them across separate CPU cores. |
| Your transaction payload measures 1,235 bytes. | ❌ Dropped at the network layer | Exceeds the 1,232-byte IPv6/UDP MTU packet limit. |
Summary
- A transaction contains an array of signatures and a message composed of instructions.
- Every instruction declares its target program, needed accounts (
AccountMeta), and arbitrary byte data. - Account flags (
isSigner,isWritable) allow the Sealevel parallel runtime to run non-conflicting transactions across multiple CPU cores simultaneously. - Execution is metered using Compute Units (CUs). You can prioritize execution by setting a priority fee with
ComputeBudgetProgram.setComputeUnitPrice. - To stay under the 1,232-byte MTU limit, modern Solana apps use v0 Versioned Transactions and Address Lookup Tables (ALTs) to compress 32-byte account addresses into 1-byte lookups.
References & Documentation
Challenge
Solana transaction design requires precise handling of resource constraints (size, Compute Units) and strict operational rules. Below are three conceptual questions based on practical industry implementation of Solana programs. Provide concise, technical answers for each question, focusing on the mechanisms and constraints described in the summary.
Expected result
Please provide technical, concise answers for each of the three questions. Answers should focus on Solana terminology (e.g., AccountMeta, ALTs, Sealevel, ComputeBudgetProgram, etc.). No code snippets are required.