Flash wear levelling for settings and logs in firmware
Flash wear levelling explained for firmware teams: how to store settings and logs so they survive years of writes and sudden power loss.

Most connected devices write something to flash long after they leave the factory: settings, calibration offsets, counters, a fault log, the state of an OTA update. Done naively, those writes wear out a single sector in months, or corrupt it the first time a battery is pulled mid-write. Flash wear levelling is how firmware spreads that load and survives power loss, and it is worth deciding on before the first field unit ships.
This post is for firmware engineers and the product people who sign off on lifetime requirements. We cover how flash actually wears, how to estimate whether your design is at risk, and the storage patterns we reach for on ESP32 and STM32 projects.
How NOR flash wears and why it bites late
NOR flash can only change bits from 1 to 0 when programming. Getting them back to 1 requires erasing a whole block, and each erase stresses the cells a little. After enough cycles, cells start to hold charge poorly, bits flip on read, and erases or programs fail outright.
Typical endurance figures are worth knowing by heart:
- External SPI NOR (the kind that sits next to an ESP32): usually rated around 100,000 erase cycles per sector, with 4 KB as the smallest erasable unit.
- Internal MCU flash: often lower. Many STM32 parts are rated around 10,000 cycles, with page sizes of 2 KB or more depending on the family.
- Data retention: commonly specified as 10–20 years, but it falls as a sector approaches its rated cycle count and at higher temperatures.
Nothing looks wrong on the bench. A prototype that saves its settings once a minute will run happily for weeks. In the field, that same design can kill its settings sector in a couple of months, by which point there are hundreds of units out there.
Estimating your write budget before choosing a scheme
Do the arithmetic first. You need three numbers: how often you write, how big each write is, and how long the product must last. Then compare that with what the flash can absorb.
Take a simple example. A device stores a 32-byte state record every minute, overwriting it in place in one 4 KB sector rated for 100,000 cycles. Every write is an erase, so the sector is gone after 100,000 minutes, which is roughly 70 days.
Now append records to a log spread across sixteen 4 KB sectors instead. Each sector holds 128 records, so the region takes 2,048 writes before any sector is erased a second time. The same 100,000 cycles now cover around 200 million writes, which at one per minute is far beyond any product lifetime. Real implementations add overhead for headers and garbage collection, so derate generously, but the gap is several orders of magnitude.
A few things quietly inflate the write rate and are worth hunting for:
- Counters or timestamps saved on every event rather than batched.
- Wi-Fi or BLE stacks that persist connection state on every reconnect.
- Debug logging left enabled to flash in production builds.
- Retry loops that rewrite the same value after a failed network call.
Flash wear levelling patterns that work in firmware
Almost every robust scheme is some form of log-structured storage. Instead of overwriting a value in place, you append a new version, mark the old one as superseded, and reclaim space later by copying live data into a fresh sector and erasing the old one. Wear spreads across every sector in the region, and an interrupted write leaves the previous version intact.
Key-value stores
For settings, credentials and small counters, a key-value store is usually the right tool. On ESP32, ESP-IDF ships its NVS library, which is log-structured, spreads writes across its partition and is designed to tolerate power loss. On STM32, ST publishes EEPROM emulation reference code that alternates between flash pages and works well for a handful of variables.
File systems
When you need files, such as logs, certificates or downloaded assets, LittleFS is our default on bare flash. It does dynamic wear levelling and is built to survive power loss at any point. FAT on raw NOR flash is a poor choice: it rewrites the same allocation table sectors constantly and was not designed to be power-loss safe.
Ring buffers for logs
For fault and event logs, a simple circular buffer of fixed-size records across a dedicated region is often enough. Give each record a sequence number and a CRC, and on boot scan for the highest valid sequence number.
| Data type | Typical approach | Main risk if done naively |
|---|---|---|
| Settings, credentials | Key-value store (NVS, EEPROM emulation) | Corruption on power loss |
| Calibration | Write-once region, plus a CRC | Accidental erase during OTA |
| Event and fault logs | Ring buffer or LittleFS | Sector wear-out |
| Frequent counters | RAM, flushed on a schedule or brown-out | Sector wear-out |
Surviving power loss mid-write
Wear is the slow failure; power loss is the fast one. A 4 KB sector erase on typical SPI NOR takes tens of milliseconds and can run to a few hundred in the worst case. A battery connector bouncing during a drop, or a user unplugging the device, can easily land inside that window.
The rules we follow are simple:
- Never erase the only copy. Write the new version somewhere else first, then invalidate the old one.
- Make every record self-validating. A length, a sequence number and a CRC let boot code reject half-written data.
- Commit last. Write a small commit marker only after the payload is fully programmed and verified.
- Watch the supply. Use the brown-out detector to block new erases when the rail is sagging, and size bulk capacitance so an in-flight write can finish.
Internal MCU flash adds one more trap. On many STM32 families, flash is programmed in 64-bit double words protected by ECC, so you cannot program the same location twice without an erase. Check the programming granularity in the reference manual before porting a library written for byte-programmable flash.
Partitioning flash with OTA and calibration in mind
Storage decisions interact with your update scheme. A dual-bank OTA layout takes a large share of flash, and the space left for data partitions decides how much wear levelling headroom you have. We size data regions with at least several times the live data volume, so garbage collection is rare and each sector sees few erases.
Keep factory calibration and device identity in their own region that normal firmware never erases, and make sure an OTA image cannot overwrite it. A new data format in an update also needs a migration path: version your records, and teach new firmware to read the old layout before it writes the new one. Our post on secure OTA updates for small fleets covers the update side of that layout in more detail.
Testing storage before it reaches the field
Storage bugs rarely show up in functional tests, so they need their own plan. On prototypes we run:
- Power-cut cycling: a relay or programmable supply drops power at random points during writes, thousands of times, and the device must boot with consistent data every time.
- Accelerated wear: run the storage code against a small region at a high write rate and confirm garbage collection behaves and erase counts stay even.
- Full-partition behaviour: fill the store and check that writes fail cleanly rather than corrupting existing keys.
- Upgrade and downgrade: flash old and new firmware alternately and confirm records survive both directions.
Pair this with a watchdog that can recover a device stuck in a storage loop; our notes on firmware watchdog design explain how we approach that.
What we would do on a new device
Before writing storage code for a new connected product, we would work through this list:
- List every piece of data that persists, with its size and expected write rate.
- Multiply out the lifetime writes and compare them with the rated cycles of the actual flash part.
- Keep fast-changing values in RAM and flush them on a schedule or on brown-out warning.
- Use a proven log-structured store or LittleFS rather than writing one from scratch.
- Separate calibration and identity from everything OTA can touch.
- Add power-cut cycling to the prototype test plan, not the production one.
All of this is far cheaper to settle in the architecture than to discover through devices that forget their settings.