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:
- On a runtime upgrade,
pallet-migrationsreads the migrations configured in itsMigrationstype, sets itsCursorstorage item to the first one, and emitsUpgradeStarted. - In each following block,
frame_executivecalls the migrator right after the inherents are applied. The migrator calls the current migration'sstepfunction with aWeightMeterlimited toMaxServiceWeight. Each migration advances at most one step per block. - A step returns a new cursor while work remains, or
Nonewhen the migration is complete. Completed migrations are recorded in theHistoricstorage map and are skipped in future upgrades. - When no migrations remain, the pallet clears
Cursorand emitsUpgradeCompleted.
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.
-
In
runtime/Cargo.toml, addpallet-migrationsto the features of thepolkadot-sdkdependency. The umbrella crate forwards thestd,runtime-benchmarks, andtry-runtimefeatures to it. -
Configure the pallet. The following configuration from
kitchensink-runtimededicates up to 80% of the maximum block weight to migrations:runtime/src/configs/mod.rsparameter_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
Migrationstype is set to()here, andFailedMigrationHandleris set toFreezeChainOnFailedMigration, which you should review before you deploy, as described in Handle Failures. You replaceMigrationswith your migrations in Register the Migration. With theruntime-benchmarksfeature,pallet-migrationsrequires the mocked migrations shown so that its benchmarks succeed. -
Add the pallet to the runtime in
runtime/src/lib.rs, choosing an unused pallet index: -
Set the pallet as the multi-block migrator in the
frame_systemconfiguration:runtime/src/configs/mod.rsimpl frame_system::Config for Runtime { // ...existing configuration type MultiBlockMigrator = MultiBlockMigrations; }The pallet's
integrity_testhook asserts thatMultiBlockMigratorreports the state ofpallet-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 implementingSteppedMigration.CursorMaxLen: The maximum encoded length of a migration cursor. Theintegrity_testchecks 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. Theintegrity_testchecks 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:
/// 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:
/// 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 implementFullCodecandMaxEncodedLen, and its maximum encoded length must fit inCursorMaxLen.Identifier: The type of the migration's unique identifier, with the same codec bounds. Its maximum encoded length must fit inIdentifierMaxLen.id: Returns the migration's identifier.step: Performs as much work as theWeightMeterallows. It receivesNoneon the first call and the previously returned cursor afterward. It returnsOk(Some(cursor))while work remains andOk(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-migrationstreats 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 toNone.pre_upgradeandpost_upgrade: Test hooks compiled with thetry-runtimefeature. 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:
#[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. Themigrationsfield holds how many the upgrade contains.MigrationAdvanced: A migration completed a step but is not finished. Theindexfield is its position in theMigrationstuple, andtookis the number of blocks it has run.MigrationCompleted: A migration finished.MigrationSkipped: A migration was skipped because its identifier is already inHistoric.MigrationFailed: A migration failed, which fails the whole upgrade.UpgradeCompleted: All migrations finished.UpgradeFailed: The upgrade failed and needs intervention.HistoricCleared: Entries were removed fromHistoricby theclear_historiccall.
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 therequiredweight for any progress. If the migration was the first to run in the block, orrequiredexceeds 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 toStuck. 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 returnsKeepStuck. Its reference documentation warns that it is not a sane default because it prevents governance intervention.ForceUnstuckOnFailedMigration: Always returnsForceUnstuck. Its reference documentation describes this as equivalent to how a faulty single-block migration is handled.EnterSafeModeOnFailedMigration: Enters or extends safe mode and returnsKeepStuck, 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 fromHistoric, 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:
#[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:
#[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:
#[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.
-
Guide Storage Migrations
Write single-block migrations with
VersionedMigrationfor small, bounded storage changes. -
Tutorial Runtime Upgrades
Build a new runtime version and submit the upgrade to your local chain.
| Created: November 17, 2026