Skip to content

Write Multi-Block Migrations

Introduction

A single-block storage migration must finish inside the block that enacts the runtime upgrade. When a migration touches more data than fits in one block, it cannot finish there, and on a parachain an overweight block can stall the chain. Multi-block migrations (MBMs) solve this by splitting the work into steps that run over as many blocks as needed, keeping their progress in storage between steps.

This guide shows how to add pallet-migrations to a runtime, implement the SteppedMigration trait, follow a migration's progress, handle failures, and test the result. The code excerpts come from pallet-example-mbm and the Polkadot SDK's kitchensink-runtime at the polkadot-stable2609-1 release.

Prerequisites

Before you begin, make sure you have the following:

  • A Polkadot SDK runtime you can build and upgrade, as described in Runtime Upgrades.
  • Familiarity with storage versions and single-block migrations from Storage Migrations.

When to Use Multi-Block Migrations

Use a multi-block migration when you cannot guarantee that a migration fits within a single block's weight and proof size limits. Typical cases include the following:

  • Migrating a storage map whose number of entries is unbounded or grows with usage.
  • Transforming nested or variable-length values whose weight is hard to predict.
  • Running several heavy migrations in the same upgrade.

A single-block migration remains the simpler choice when the amount of data is small and bounded and you have measured its weight.

Multi-block migrations come with a cost for users of the chain. While they run, the runtime only accepts inherents, so signed and unsigned transactions are paused until the last migration completes. Design each step to make as much progress as its weight allows so that the pause stays short.

How Multi-Block Migrations Run

Multi-block migrations are driven by the MultiBlockMigrator that you configure in frame_system, normally pallet-migrations. The process works as follows:

  1. On a runtime upgrade, pallet-migrations reads the migrations configured in its Migrations type, sets its Cursor storage item to the first one, and emits UpgradeStarted.
  2. In each following block, frame_executive calls the migrator right after the inherents are applied. The migrator calls the current migration's step function with a WeightMeter limited to MaxServiceWeight. Each migration advances at most one step per block.
  3. A step returns a new cursor while work remains, or None when the migration is complete. Completed migrations are recorded in the Historic storage map and are skipped in future upgrades.
  4. When no migrations remain, the pallet clears Cursor and emits UpgradeCompleted.

While migrations are ongoing, frame_executive only allows inherents in blocks and skips the on_idle and on_poll hooks, and frame_system rejects a new runtime code upgrade. Only change the Migrations list in a runtime upgrade after all previous migrations have completed.

Add pallet-migrations to a Runtime

The following steps add pallet-migrations to a runtime built on the parachain template, which imports pallets through the polkadot-sdk umbrella crate.

  1. In runtime/Cargo.toml, add pallet-migrations to the features of the polkadot-sdk dependency. The umbrella crate forwards the std, runtime-benchmarks, and try-runtime features to it.

    runtime/Cargo.toml
    polkadot-sdk = { workspace = true, default-features = false, features = [
        # ...existing features
        "pallet-migrations",
        "runtime",
    ] }
    
  2. Configure the pallet. The following configuration from kitchensink-runtime dedicates up to 80% of the maximum block weight to migrations:

    runtime/src/configs/mod.rs
    parameter_types! {
        pub MbmServiceWeight: Weight = Perbill::from_percent(80) * RuntimeBlockWeights::get().max_block;
    }
    
    impl pallet_migrations::Config for Runtime {
        type RuntimeEvent = RuntimeEvent;
        #[cfg(not(feature = "runtime-benchmarks"))]
        type Migrations = ();
        // Benchmarks need mocked migrations to guarantee that they succeed.
        #[cfg(feature = "runtime-benchmarks")]
        type Migrations = pallet_migrations::mock_helpers::MockedMigrations;
        type CursorMaxLen = ConstU32<65_536>;
        type IdentifierMaxLen = ConstU32<256>;
        type MigrationStatusHandler = ();
        type FailedMigrationHandler = frame_support::migrations::FreezeChainOnFailedMigration;
        type MaxServiceWeight = MbmServiceWeight;
        type WeightInfo = pallet_migrations::weights::SubstrateWeight<Runtime>;
    }
    

    The Migrations type is set to () here, and FailedMigrationHandler is set to FreezeChainOnFailedMigration, which you should review before you deploy, as described in Handle Failures. You replace Migrations with your migrations in Register the Migration. With the runtime-benchmarks feature, pallet-migrations requires the mocked migrations shown so that its benchmarks succeed.

  3. Add the pallet to the runtime in runtime/src/lib.rs, choosing an unused pallet index:

    runtime/src/lib.rs
    #[runtime::pallet_index(INSERT_PALLET_INDEX)]
    pub type MultiBlockMigrations = pallet_migrations;
    
  4. Set the pallet as the multi-block migrator in the frame_system configuration:

    runtime/src/configs/mod.rs
    impl frame_system::Config for Runtime {
        // ...existing configuration
        type MultiBlockMigrator = MultiBlockMigrations;
    }
    

    The pallet's integrity_test hook asserts that MultiBlockMigrator reports the state of pallet-migrations, so the runtime's integrity tests catch a missing or wrong setting.

The Config items of pallet-migrations are the following:

  • RuntimeEvent: The runtime's overarching event type.
  • Migrations: A tuple of the multi-block migrations to run, each implementing SteppedMigration.
  • CursorMaxLen: The maximum encoded length of a migration cursor. The integrity_test checks that every configured migration's cursor fits.
  • IdentifierMaxLen: The maximum encoded length of a migration identifier, checked the same way.
  • MigrationStatusHandler: A hook notified when migrations start and complete, for example to pause other subsystems. Use () for none.
  • FailedMigrationHandler: Decides what happens when a migration fails. See Handle Failures.
  • MaxServiceWeight: The maximum weight spent on migrations in each block. The integrity_test checks that it does not exceed the maximum block weight.
  • WeightInfo: Weights for the pallet's own logic and calls.

Implement a Multi-Block Migration

The pallet-example-mbm pallet migrates the values of a StorageMap from u32 to u64. The migration lives in the pallet's migrations/v1 module, following the layout described in Storage Migrations.

Define a Migration Identifier

Every multi-block migration needs a unique identifier. pallet-migrations stores the identifiers of completed migrations in Historic and skips any migration whose identifier it has already seen, so two migrations with the same identifier are treated as the same migration.

The example defines a constant prefix for the pallet instead of deriving it from the crate name, so renaming the crate never causes old migrations to run again:

migrations/mod.rs
/// A unique identifier across all pallets.
///
/// This constant represents a unique identifier for the migrations of this pallet.
/// It helps differentiate migrations for this pallet from those of others. Note that we don't
/// directly pull the crate name from the environment, since that would change if the crate were
/// ever to be renamed and could cause historic migrations to run again.
pub const PALLET_MIGRATIONS_ID: &[u8; 18] = b"pallet-example-mbm";

The migration combines this prefix with the storage versions it migrates between using the MigrationId helper type.

Implement the SteppedMigration Trait

The migration reads values through a storage_alias of the old u32 map and writes them to the new u64 map. Because both maps use the same key hasher, the last processed key serves as the cursor:

migrations/v1/mod.rs
/// Migrates the items of the [`crate::MyMap`] map from `u32` to `u64`.
///
/// The `step` function will be called once per block. It is very important that this function
/// *never* panics and never uses more weight than it got in its meter. The migrations should also
/// try to make maximal progress per step, so that the total time it takes to migrate stays low.
pub struct LazyMigrationV1<T: Config, W: weights::WeightInfo>(PhantomData<(T, W)>);
impl<T: Config, W: weights::WeightInfo> SteppedMigration for LazyMigrationV1<T, W> {
    type Cursor = u32;
    // Without the explicit length here the construction of the ID would not be infallible.
    type Identifier = MigrationId<18>;

    /// The identifier of this migration. Which should be globally unique.
    fn id() -> Self::Identifier {
        MigrationId { pallet_id: *PALLET_MIGRATIONS_ID, version_from: 0, version_to: 1 }
    }

    /// The actual logic of the migration.
    ///
    /// This function is called repeatedly until it returns `Ok(None)`, indicating that the
    /// migration is complete. Ideally, the migration should be designed in such a way that each
    /// step consumes as much weight as possible. However, this is simplified to perform one stored
    /// value mutation per block.
    fn step(
        mut cursor: Option<Self::Cursor>,
        meter: &mut WeightMeter,
    ) -> Result<Option<Self::Cursor>, SteppedMigrationError> {
        let required = W::step();
        // If there is not enough weight for a single step, return an error. This case can be
        // problematic if it is the first migration that ran in this block. But there is nothing
        // that we can do about it here.
        if meter.remaining().any_lt(required) {
            return Err(SteppedMigrationError::InsufficientWeight { required });
        }

        // We loop here to do as much progress as possible per step.
        loop {
            if meter.try_consume(required).is_err() {
                break;
            }

            let mut iter = if let Some(last_key) = cursor {
                // If a cursor is provided, start iterating from the stored value
                // corresponding to the last key processed in the previous step.
                // Note that this only works if the old and the new map use the same way to hash
                // storage keys.
                v0::MyMap::<T>::iter_from(v0::MyMap::<T>::hashed_key_for(last_key))
            } else {
                // If no cursor is provided, start iterating from the beginning.
                v0::MyMap::<T>::iter()
            };

            // If there's a next item in the iterator, perform the migration.
            if let Some((last_key, value)) = iter.next() {
                // Migrate the inner value: u32 -> u64.
                let value = value as u64;
                // We can just insert here since the old and the new map share the same key-space.
                // Otherwise it would have to invert the concat hash function and re-hash it.
                MyMap::<T>::insert(last_key, value);
                cursor = Some(last_key) // Return the processed key as the new cursor.
            } else {
                cursor = None; // Signal that the migration is complete (no more items to process).
                break;
            }
        }
        Ok(cursor)
    }

The trait has the following required items:

  • Cursor: The type that records the migration's progress between steps. It must implement FullCodec and MaxEncodedLen, and its maximum encoded length must fit in CursorMaxLen.
  • Identifier: The type of the migration's unique identifier, with the same codec bounds. Its maximum encoded length must fit in IdentifierMaxLen.
  • id: Returns the migration's identifier.
  • step: Performs as much work as the WeightMeter allows. It receives None on the first call and the previously returned cursor afterward. It returns Ok(Some(cursor)) while work remains and Ok(None) when the migration is complete.

The step function must never panic and must never consume more weight than the meter allows. The example checks the remaining weight against the benchmarked cost of one iteration, W::step(), before every iteration. Benchmark that cost for your own migration, as the example does in its benchmarks.rs.

The trait also provides the following optional items with default implementations:

  • max_steps: The maximum number of steps the migration may take. pallet-migrations treats a migration that exceeds it as failed. The default, None, sets no limit, but the pallet only guarantees progress if you set a sensible limit.
  • migrating_prefixes: The storage prefixes the migration changes, exposed through the pallet's status so that tools know which state may not be readable during the migration. Defaults to None.
  • pre_upgrade and post_upgrade: Test hooks compiled with the try-runtime feature. See Test with try-runtime.

pallet-migrations calls step through transactional_step, which rolls back the storage changes of a step that returns an error.

Register the Migration

Add the migration to the Migrations tuple of pallet_migrations::Config. The example's mock runtime registers it as follows:

mock.rs
#[cfg(not(feature = "runtime-benchmarks"))]
type Migrations = (
    crate::migrations::v1::LazyMigrationV1<
        Runtime,
        crate::migrations::v1::weights::SubstrateWeight<Runtime>,
    >,
);

pallet-migrations runs the migrations in tuple order, one after another. A production runtime registers its multi-block migrations the same way. For example, Asset Hub Westend lists migrations from several pallets in its Migrations tuple.

Track Migration Status

pallet-migrations emits the following events during an upgrade:

  • UpgradeStarted: Migrations started. The migrations field holds how many the upgrade contains.
  • MigrationAdvanced: A migration completed a step but is not finished. The index field is its position in the Migrations tuple, and took is the number of blocks it has run.
  • MigrationCompleted: A migration finished.
  • MigrationSkipped: A migration was skipped because its identifier is already in Historic.
  • MigrationFailed: A migration failed, which fails the whole upgrade.
  • UpgradeCompleted: All migrations finished.
  • UpgradeFailed: The upgrade failed and needs intervention.
  • HistoricCleared: Entries were removed from Historic by the clear_historic call.

You can also read the Cursor storage item directly. It is empty when no migrations are running, Active with the current migration index and inner cursor while they run, and Stuck after a failure. The pallet also exposes view functions such as status, which returns whether migrations are ongoing, progress information for the current migration, and its affected storage prefixes.

Handle Failures

A step can return one of the following SteppedMigrationError variants:

  • InsufficientWeight: The meter does not have the required weight for any progress. If the migration was the first to run in the block, or required exceeds the meter's limit, the migration fails. Otherwise, the pallet retries it in the next block.
  • InvalidCursor: The migration cannot decode its cursor. The migration fails.
  • Failed: The migration hit a permanent error. The migration fails.

When a migration fails, pallet-migrations emits MigrationFailed and UpgradeFailed and calls the configured FailedMigrationHandler. Failed migrations are not added to Historic. The handler returns one of the following FailedMigrationHandling values:

  • KeepStuck: Sets the cursor to Stuck. Because the cursor is not empty, the runtime keeps accepting only inherents.
  • ForceUnstuck: Clears the cursor and resumes transaction processing without completing the upgrade, exposing any half-migrated state to users.
  • Ignore: Leaves the cursor unchanged so that the handler can manage it. A handler that returns this value without acting keeps failing in every block.

frame_support provides the following handlers:

  • FreezeChainOnFailedMigration: Always returns KeepStuck. Its reference documentation warns that it is not a sane default because it prevents governance intervention.
  • ForceUnstuckOnFailedMigration: Always returns ForceUnstuck. Its reference documentation describes this as equivalent to how a faulty single-block migration is handled.
  • EnterSafeModeOnFailedMigration: Enters or extends safe mode and returns KeepStuck, or falls back to another handler if safe mode cannot be entered.

No handler is safe for every chain. The pallet-migrations documentation advises choosing one that lets governance act while preventing other transactions from interacting with the inconsistent state, for example by combining it with pallet-safe-mode or pallet-tx-pause. Monitor for the UpgradeFailed event so that you learn about failures immediately.

The pallet provides the following root-only calls for emergencies and maintenance:

  • force_set_cursor: Sets the cursor to any value, which can start, stop, or move the migration process.
  • force_set_active_cursor: Sets an active cursor with a given migration index and inner cursor.
  • force_onboard_mbms: Starts the configured migrations as if a runtime upgrade had happened. Requires that no migrations are running.
  • clear_historic: Removes entries from Historic, either specific identifiers or a bounded batch.

Test Multi-Block Migrations

Test a multi-block migration at two levels: unit tests against a mock runtime, and a dry run against real chain state with try-runtime.

Write Unit Tests

In a mock runtime, configure pallet-migrations and set it as the MultiBlockMigrator, as in the example's mock.rs. Because frame_executive does not run in unit tests, the mock calls the migrator's step function itself on every block:

mock.rs
#[allow(dead_code)]
pub fn run_to_block(n: u64) {
    System::run_to_block_with::<AllPalletsWithSystem>(
        n,
        frame_system::RunToBlockHooks::default().after_initialize(|_| {
            // Done by Executive:
            <Runtime as frame_system::Config>::MultiBlockMigrator::step();
        }),
    );
}

The example's test fills the old map, gives the migrator enough weight for exactly 16 iterations per block, triggers the upgrade with on_runtime_upgrade, and checks after every block that exactly 16 more values were migrated:

migrations/v1/tests.rs
#[test]
fn lazy_migration_works() {
    new_test_ext().execute_with(|| {
        frame_support::__private::sp_tracing::try_init_simple();
        // Insert some values into the old storage map.
        for i in 0..1024 {
            v1::v0::MyMap::<T>::insert(i, i);
        }

        // Give it enough weight do do exactly 16 iterations:
        let limit = <T as pallet_migrations::Config>::WeightInfo::progress_mbms_none() +
            pallet_migrations::Pallet::<T>::exec_migration_max_weight() +
            weights::SubstrateWeight::<T>::step() * 16;
        MigratorServiceWeight::set(&limit);

        System::set_block_number(1);
        AllPalletsWithSystem::on_runtime_upgrade(); // onboard MBMs

        let mut last_decodable = 0;
        for block in 2..=65 {
            run_to_block(block);

            let mut decodable = 0;
            for i in 0..1024 {
                let key = crate::MyMap::<T>::hashed_key_for(i);
                let value =
                    frame_support::storage::unhashed::get_raw(&key[..]).expect("value exists");

                if let Ok(value) = u64::decode(&mut &value[..]) {
                    assert_eq!(value, i as u64);
                    decodable += 1;
                } else {
                    assert_eq!(u32::decode(&mut &value[..]).expect("not migrated yet"), i);
                }
            }

            assert_eq!(decodable, last_decodable + 16);
            last_decodable = decodable;
        }

        // Check that everything is decodable now:
        for i in 0..1024 {
            assert_eq!(crate::MyMap::<T>::get(i), Some(i as u64));
        }
    });
}

Test with try-runtime

SteppedMigration has its own pre_upgrade and post_upgrade hooks. With the try-runtime feature enabled, pallet-migrations calls pre_upgrade before a migration's first step and post_upgrade, with the bytes pre_upgrade returned, after its last step. The example captures the old map and verifies every migrated value:

migrations/v1/mod.rs
#[cfg(feature = "try-runtime")]
fn pre_upgrade() -> Result<Vec<u8>, frame_support::sp_runtime::TryRuntimeError> {
    use codec::Encode;

    // Return the state of the storage before the migration.
    Ok(v0::MyMap::<T>::iter().collect::<BTreeMap<_, _>>().encode())
}

#[cfg(feature = "try-runtime")]
fn post_upgrade(prev: Vec<u8>) -> Result<(), frame_support::sp_runtime::TryRuntimeError> {
    use codec::Decode;

    // Check the state of the storage after the migration.
    let prev_map = BTreeMap::<u32, u32>::decode(&mut &prev[..])
        .expect("Failed to decode the previous storage state");

    // Check the len of prev and post are the same.
    assert_eq!(
        MyMap::<T>::iter().count(),
        prev_map.len(),
        "Migration failed: the number of items in the storage after the migration is not the same as before"
    );

    for (key, value) in prev_map {
        let new_value =
            MyMap::<T>::get(key).expect("Failed to get the value after the migration");
        assert_eq!(
            value as u64, new_value,
            "Migration failed: the value after the migration is not the same as before"
        );
    }

    Ok(())
}

With the try-runtime feature enabled, pallet-migrations panics instead of calling the FailedMigrationHandler when a migration fails, so failures surface immediately in tests.

To dry-run the migrations against a snapshot or a running node, use the on-runtime-upgrade command of try-runtime-cli. By default, it produces blocks until all multi-block migrations finish and fails if they take longer than --mbm-max-blocks blocks. Set --blocktime to your chain's block time in milliseconds:

try-runtime \
  --runtime ./target/release/wbuild/parachain-template-runtime/parachain_template_runtime.compact.compressed.wasm \
  on-runtime-upgrade \
  --blocktime 6000 \
  --checks=all \
  snap --path parachain-template.snap

See Test Runtime Upgrades with try-runtime for how to build the runtime with the try-runtime feature, create a snapshot, and run this check in CI.

Where to Go Next

  • Guide Test Runtime Upgrades with try-runtime


    Dry-run your runtime upgrade and its migrations against a snapshot of real chain state.

    Get Started

  • Guide Storage Migrations


    Write single-block migrations with VersionedMigration for small, bounded storage changes.

    Get Started

  • Tutorial Runtime Upgrades


    Build a new runtime version and submit the upgrade to your local chain.

    Get Started

Last update: November 17, 2026
| Created: November 17, 2026