Platform Engineering · Lesson 17

LVM and RAID in Practice: Grow, Snapshot, Replace a Disk

Two storage jobs come up on every long-lived server: a volume is nearly full and must grow without downtime, and a disk in a mirror dies and must be replaced without losing data. LVM handles the first (add a disk, extend the volume group, grow the logical volume and its file system online) and takes snapshots before risky changes. Linux software RAID (mdadm) handles the second. This lesson runs both jobs on one database server, including the two ways they quietly go wrong.

Difficulty: Advanced · Know this first: Lesson 11, Lesson 16

Run it as:

When it breaks, I check

One thing to remember

Where the time goes

This bar adds up admin minutes for both jobs, growing a volume and replacing a mirrored disk. It is a worked example, not a measurement. The snapshot and failure hops are where an unwatched setting becomes hours of recovery.

Try it: will the snapshot survive the upgrade?

A snapshot stores the old copy of every block that changes while it exists. Set its size, how much data the upgrade rewrites, and how long you keep the snapshot afterwards while the database keeps writing.

7.0 GBchanges to store
70%Data% at the end
validsnapshot

Valid: you can still roll back with lvconvert --merge

Check yourself

Three questions. No score is saved anywhere — this is just you against the material.

Basic to master

Storage operations grow in four levels: reading LVM and RAID state, growing and snapshotting safely, running RAID through failures, and designing storage for a fleet.

Basic — Read the layers

At the basic level you can read LVM and RAID state.

  • pvs, vgs, lvs, lsblk: disks, pool, volumes.
  • cat /proc/mdstat: [UU] healthy, [U_] degraded, "recovery" while resyncing.
  • df -h for the file system on top.

Where it breaks: confusing a logical volume's size (lvs) with the file system's size (df).

Try it: Basic

/proc/mdstat shows md0 : active raid1 sdb[1] sda[0] ... [2/1] [U_]. What does that mean?

Now do it: Read /proc/mdstat on a server with software RAID.

Intermediate — Grow and snapshot

At the intermediate level you change storage online.

  • pvcreate, vgextend, lvextend -r -L +N.
  • lvcreate -s -L SIZE -n name vg/lv; lvconvert --merge to roll back; lvremove when done.
  • Keep free extents in every VG.

Try it: Intermediate

Before a risky upgrade you want a rollback point on the same server. What is the right size for the snapshot?

Now do it: Create a snapshot of a loop-device LV, write to the origin, and watch Data% rise.

Advanced — RAID through failures

At the advanced level you replace disks without risk.

  • mdadm --fail, --remove, --add; resync progress in /proc/mdstat.
  • MAILADDR in /etc/mdadm/mdadm.conf and the mdmonitor service; SMART checks with smartd.
  • RAID levels: 1 (mirror), 10 (striped mirrors), 5 and 6 (parity, slow rebuilds on large disks).

Try it: Advanced

Why is RAID 5 risky on very large disks?

Now do it: Estimate the rebuild time for your largest array at 150 MB/s.

Master — Storage design for a fleet

At the master level storage risk is designed, not discovered.

  • Cloud volumes are already replicated; LVM is still useful for growth and snapshots, mdadm rarely is.
  • Snapshots for rollback, backups for recovery, replicas for availability: three different tools.
  • Alerts tested by failing things on purpose in staging.

Trade-off: RAID 1 halves usable capacity for protection against one failure; erasure coding and replication across hosts protect more, at the cost of complexity and network traffic.

Try it: Master

Ransomware encrypts a RAID 1 array. What recovers the data?

Now do it: For one important server, write down which tool covers disk failure, deletion, and ransomware.

Go deeper

Run both jobs on loop devices, so no real disk is touched. You need lvm2 and mdadm (sudo apt install -y lvm2 mdadm).

Grow a volume online and take a snapshot

for i in 1 2; do truncate -s 1G d$i.img; done
A=$(sudo losetup --find --show d1.img); B=$(sudo losetup --find --show d2.img)
sudo pvcreate -q "$A"; sudo vgcreate -q vg_lab "$A"
sudo lvcreate -q -L 600M -n lv_data vg_lab; sudo mkfs.ext4 -q /dev/vg_lab/lv_data
sudo mkdir -p /mnt/lab && sudo mount /dev/vg_lab/lv_data /mnt/lab
sudo pvcreate -q "$B"; sudo vgextend -q vg_lab "$B"          # add a disk
sudo lvextend -q -r -L +800M vg_lab/lv_data; df -h /mnt/lab   # grow, still mounted
sudo lvcreate -q -s -L 200M -n snap vg_lab/lv_data            # snapshot
sudo dd if=/dev/urandom of=/mnt/lab/blob bs=1M count=100 status=none
sudo lvs -o lv_name,origin,data_percent vg_lab                # Data% rises
sudo lvremove -qy vg_lab/snap

A mirror, a failure, and a replacement

for i in 3 4 5; do truncate -s 500M d$i.img; done
C=$(sudo losetup --find --show d3.img); D=$(sudo losetup --find --show d4.img); E=$(sudo losetup --find --show d5.img)
sudo mdadm --create /dev/md100 --level=1 --raid-devices=2 --run "$C" "$D"
cat /proc/mdstat
sudo mdadm /dev/md100 --fail "$D" --remove "$D"; cat /proc/mdstat   # degraded [U_]
sudo mdadm /dev/md100 --add "$E"; sleep 5; cat /proc/mdstat          # resync
# clean up
sudo mdadm --stop /dev/md100; sudo umount /mnt/lab; sudo vgremove -qy vg_lab
for f in d?.img; do losetup -j "$f" | cut -d: -f1 | xargs -r sudo losetup -d; done; rm d?.img

One time it broke

This is a composite of a failure pattern that keeps repeating; the details are illustrative. A mirror lost its second disk.

Timeline

  • Week 0One disk of a RAID 1 on a file server fails. mdadm.conf has no MAILADDR and nothing else watches /proc/mdstat. Users notice nothing.
  • Week 3The second disk, from the same batch and with the same hours, fails. The array is gone.
  • Week 3, +8 hData is restored from the weekly backup on new disks. Five days of changes are lost.

What changed after

Degraded arrays and SMART warnings page on-call, alerts are tested by failing a member in staging, disks in a mirror are bought from different batches, and backups run nightly with a restore test each month.

Try it yourself, from scratch

Everything here runs on any Linux machine: your own laptop, WSL on Windows (run wsl --install in PowerShell once), or a small cloud VM. The Python needs only Python 3 and its standard library; check that you have it with python3 --version.

Before you start: A Linux VM or a spare machine where you have sudo (a cloud VM, Multipass, or VirtualBox). Some commands change the system; do not run them on a shared server. Disk commands here use loop devices (files acting as disks), so no real disk is touched. Install the tools with sudo apt install -y lvm2 mdadm.

1. Linux commands

Type each one, read what it prints, and compare it with the note above it.

  1. Two practice disks, a volume group, and a logical volume with a file system.

    for i in 1 2; do truncate -s 600M lv$i.img; done
    A=$(sudo losetup --find --show lv1.img); B=$(sudo losetup --find --show lv2.img)
    sudo pvcreate -q "$A"; sudo vgcreate -q vg_lab "$A"; sudo lvcreate -q -L 400M -n data vg_lab
    sudo mkfs.ext4 -q /dev/vg_lab/data; sudo mkdir -p /mnt/lvlab; sudo mount /dev/vg_lab/data /mnt/lvlab; df -h /mnt/lvlab
  2. Add the second disk and grow the volume and file system online.

    sudo pvcreate -q "$B"; sudo vgextend -q vg_lab "$B"; sudo vgs vg_lab
    sudo lvextend -q -r -L +500M vg_lab/data; df -h /mnt/lvlab
  3. A snapshot: write data and watch its Data% grow.

    sudo lvcreate -q -s -L 100M -n snap vg_lab/data
    sudo dd if=/dev/urandom of=/mnt/lvlab/blob bs=1M count=40 status=none; sync
    sudo lvs -o lv_name,origin,data_percent vg_lab; sudo lvremove -qy vg_lab/snap
  4. A RAID 1 mirror, a failed member, and a replacement; then clean up everything.

    for i in 1 2 3; do truncate -s 200M md$i.img; done
    M1=$(sudo losetup --find --show md1.img); M2=$(sudo losetup --find --show md2.img); M3=$(sudo losetup --find --show md3.img)
    sudo mdadm --create /dev/md50 --level=1 --raid-devices=2 --run "$M1" "$M2"; cat /proc/mdstat
    sudo mdadm /dev/md50 --fail "$M2" --remove "$M2"; cat /proc/mdstat
    sudo mdadm /dev/md50 --add "$M3"; sleep 4; cat /proc/mdstat
    sudo mdadm --stop /dev/md50; sudo umount /mnt/lvlab; sudo vgremove -qy vg_lab
    for f in lv?.img md?.img; do losetup -j "$f" | cut -d: -f1 | xargs -r sudo losetup -d; done; rm lv?.img md?.img

2. Python: storage_risk.py

This program estimates two storage risks: whether a snapshot survives a change, and how exposed a degraded RAID 1 is while nobody notices and while it resyncs. Save it as storage_risk.py, then run it.

# storage_risk.py
def snapshot(size_gb, change_gb, keep_hours, writes_gb_per_hour=0.5):
    used = change_gb + keep_hours * writes_gb_per_hour
    state = "VALID" if used <= size_gb else "INVALID (overflowed)"
    return f"snapshot {size_gb:>2} GB, upgrade rewrites {change_gb} GB, kept {keep_hours:>2} h: {used:4.1f} GB used -> {state}"

for args in [(10, 6, 2), (1, 6, 0), (10, 6, 12)]:
    print(snapshot(*args))

afr = 0.02                     # 2% annual failure rate per disk
hourly = afr / (365 * 24)
disk_tb, resync_mb_s = 4, 150
resync_h = disk_tb * 1e6 / resync_mb_s / 3600
for unnoticed_days in [0, 7, 21]:
    window_h = unnoticed_days * 24 + resync_h
    p_second = 1 - (1 - hourly) ** window_h
    print(f"degraded unnoticed {unnoticed_days:>2} days + {resync_h:.1f} h resync: "
          f"chance the other disk fails too = {p_second:.4%}")

Run it, and you should see this output:

$ python3 storage_risk.py
snapshot 10 GB, upgrade rewrites 6 GB, kept  2 h:  7.0 GB used -> VALID
snapshot  1 GB, upgrade rewrites 6 GB, kept  0 h:  6.0 GB used -> INVALID (overflowed)
snapshot 10 GB, upgrade rewrites 6 GB, kept 12 h: 12.0 GB used -> INVALID (overflowed)
degraded unnoticed  0 days + 7.4 h resync: chance the other disk fails too = 0.0017%
degraded unnoticed  7 days + 7.4 h resync: chance the other disk fails too = 0.0400%
degraded unnoticed 21 days + 7.4 h resync: chance the other disk fails too = 0.1167%

3. What to notice

4. Advanced: every step as one Bash script

The same Linux steps, made into a real script you can keep and run again. It uses the Bash features a production script needs: functions (one per step), an array of step names, arguments to choose steps, a case for options, exit codes recorded for each step, and a trap that prints a summary even when you stop it with Ctrl+C. Make a folder for this lesson (mkdir -p ~/labs/lvm-and-raid-in-practice && cd ~/labs/lvm-and-raid-in-practice) and save this as lab.sh.

#!/usr/bin/env bash
# The Linux steps of "LVM and RAID in Practice: Grow, Snapshot, Replace a Disk", as one script (save it as lab.sh).
#
#   ./lab.sh          run every step, in order
#   ./lab.sh 2 4      run only steps 2 and 4
#   ./lab.sh --list   list the steps
#
# The steps share one shell, so a later step can use what an earlier one set up (a folder,
# a variable, a container): run them all in order the first time. Your own scripts should
# start with "set -euo pipefail"; this one runs teaching commands, and some of them fail on
# purpose, so it records each step's exit code instead of stopping at the first failure.

STEPS=(
  'Two practice disks, a volume group, and a logical volume with a file system.'
  'Add the second disk and grow the volume and file system online.'
  'A snapshot: write data and watch its Data% grow.'
  'A RAID 1 mirror, a failed member, and a replacement; then clean up everything.'
)

step_1() {
for i in 1 2; do truncate -s 600M lv$i.img; done
A=$(sudo losetup --find --show lv1.img); B=$(sudo losetup --find --show lv2.img)
sudo pvcreate -q "$A"; sudo vgcreate -q vg_lab "$A"; sudo lvcreate -q -L 400M -n data vg_lab
sudo mkfs.ext4 -q /dev/vg_lab/data; sudo mkdir -p /mnt/lvlab; sudo mount /dev/vg_lab/data /mnt/lvlab; df -h /mnt/lvlab
}

step_2() {
sudo pvcreate -q "$B"; sudo vgextend -q vg_lab "$B"; sudo vgs vg_lab
sudo lvextend -q -r -L +500M vg_lab/data; df -h /mnt/lvlab
}

step_3() {
sudo lvcreate -q -s -L 100M -n snap vg_lab/data
sudo dd if=/dev/urandom of=/mnt/lvlab/blob bs=1M count=40 status=none; sync
sudo lvs -o lv_name,origin,data_percent vg_lab; sudo lvremove -qy vg_lab/snap
}

step_4() {
for i in 1 2 3; do truncate -s 200M md$i.img; done
M1=$(sudo losetup --find --show md1.img); M2=$(sudo losetup --find --show md2.img); M3=$(sudo losetup --find --show md3.img)
sudo mdadm --create /dev/md50 --level=1 --raid-devices=2 --run "$M1" "$M2"; cat /proc/mdstat
sudo mdadm /dev/md50 --fail "$M2" --remove "$M2"; cat /proc/mdstat
sudo mdadm /dev/md50 --add "$M3"; sleep 4; cat /proc/mdstat
sudo mdadm --stop /dev/md50; sudo umount /mnt/lvlab; sudo vgremove -qy vg_lab
for f in lv?.img md?.img; do losetup -j "$f" | cut -d: -f1 | xargs -r sudo losetup -d; done; rm lv?.img md?.img
}

# print a step that has to be run by hand, instead of running it
by_hand() {
  echo "  (run this one yourself: $1)"
  sed 's/^/    /'
}

RESULTS=()
run_step() {
  local n=$1 start=$SECONDS code
  printf '\n== step %d of %d: %s\n' "$n" "${#STEPS[@]}" "${STEPS[n-1]}"
  "step_$n"
  code=$?
  RESULTS+=("step $n: exit code $code, $((SECONDS - start)) s")
}

summary() {
  echo
  echo "== summary"
  local r
  for r in "${RESULTS[@]}"; do echo "  $r"; done
}

case "${1:-}" in
  -h|--help) sed -n '2,6p' "$0"; exit 0 ;;
  --list) for i in "${!STEPS[@]}"; do echo "$((i + 1)). ${STEPS[i]}"; done; exit 0 ;;
esac

[ $# -eq 0 ] && set -- $(seq 1 "${#STEPS[@]}")
for n in "$@"; do
  if ! [[ $n =~ ^[0-9]+$ ]] || (( n < 1 || n > ${#STEPS[@]} )); then
    echo "there is no step '$n'; try --list" >&2
    exit 2
  fi
done
trap summary EXIT
trap 'echo; echo "stopped with Ctrl+C"; exit 130' INT
for n in "$@"; do run_step "$n"; done

Then make it executable and run it:

chmod +x lab.sh
./lab.sh --list     # the steps
./lab.sh            # every step, then a summary of exit codes and times
./lab.sh 2 3        # only steps 2 and 3

5. Learn the basics behind it

New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.

If you remember nothing else

Design exercise

Design storage for a self-hosted PostgreSQL server with 400 GB of data growing 5 GB a week, on physical hardware.

Clarifying questions to ask

Which RAID level and how many disks? How will you grow the volume? How do you get a rollback point before major upgrades? Who is told when a disk fails, and how fast must it be replaced?

Rough sizing

Say 4 TB disks, a 150 MB/s resync, upgrades that rewrite about 50 GB, and a 4-hour replacement target.

Shape of the answer

RAID 10 on four disks under LVM, with 30 percent of the VG kept free; lvextend -r for growth; a 100 GB snapshot before upgrades with an alert on Data%; mdmonitor and SMART alerts paging on-call, tested quarterly; nightly off-host backups with point-in-time recovery, restore-tested monthly.

Trade-offs to name

RAID 10 gives fast rebuilds and good write speed at half the raw capacity; RAID 6 gives more capacity and long, risky rebuilds. Free space kept in the VG costs money every day and is what makes snapshots and emergency growth possible.

Saved on this device, in this browser.
Next in this series · Lesson 18
Swap and Virtual Memory Tuning

When a server runs short of memory, Linux has three moves: drop file cache, push idle pages to swap, or kill a process with the OOM killer. Which one happens, and to which process, is decided by settings an administrator…

Go to Lesson 18 →

Or browse the full course from the Lessons index.