↓ Skip to main content
  1. Engineering Notes & Articles/

OTA (Over-The-Air) Firmware Updates: Safe Deployment, Partition Tables, and Rollback

Practical IoT Engineering - This article is part of a series.
Part 7: This Article

Flashing updated firmware onto a prototype microcontroller via a USB cable takes ten seconds on a workbench. Once fifty or five hundred nodes are sealed inside weatherproof enclosures on factory ceilings, agricultural fields, or rooftop utility cabinets, physically visiting every device with a laptop and serial programmer is operationally impossible.

Without a reliable Over-The-Air (OTA) update mechanism, every bug fix, sensor calibration adjustment, or TLS root certificate rotation becomes an expensive field service dispatch. At the same time, a poorly engineered OTA implementation introduces a severe risk: if power drops mid-download or a newly deployed binary contains a subtle boot-loop bug, the device can become permanently unreachable in the field—a failure known as bricking.

Designing safe OTA firmware updates requires splitting flash memory into redundant execution banks, verifying cryptographic integrity before switching boot targets, and engineering automatic bootloader rollbacks when new firmware fails self-checks.


Anatomy of a Dual-Bank Flash Partition Table
#

A microcontroller cannot safely overwrite the exact flash sectors it is currently executing instructions from. If a router reboots or a solar battery dips halfway through erasing the active firmware, the CPU has no valid instructions left to execute upon restart.

Production IoT microcontrollers solve this using an A/B (Dual-Bank) Partition Layout alongside a dedicated data partition (otadata) that tells the bootloader which bank to boot:

Partition Name Typical Type / Subtype Purpose in OTA Lifecycle
bootloader Bootloader (0x1000) First code executed on reset; reads otadata and jumps to the active app bank.
nvs Data / NVS Stores Wi-Fi credentials, device certificates, and calibration constants across updates.
otadata Data / OTA (8 KB) Tiny state table tracking active bank (ota_0 vs. ota_1) and pending rollback flags.
ota_0 (Slot A) App / OTA_0 First full firmware application slot (e.g., 1.5 MB – 2 MB).
ota_1 (Slot B) App / OTA_1 Second identical firmware application slot for incoming updates.
storage Data / LittleFS Wear-leveled offline telemetry ring buffer preserved across firmware upgrades.

How A/B Bank Switching Works
#

  1. Suppose the node is currently running version v1.0.0 from ota_0.
  2. When an update notification arrives for v1.1.0, the firmware streams the incoming binary into the inactive ota_1 partition while v1.0.0 continues running undisturbed.
  3. Only after every byte is written and verified does the firmware update otadata to mark ota_1 as the next boot target and trigger a controlled software reboot.
  4. Notice that nvs and storage sit outside both application slots—ensuring site Wi-Fi credentials, X.509 private keys, and buffered offline sensor records survive every firmware upgrade intact.

Step-by-Step Safe OTA Lifecycle
#

A production OTA pipeline separates notification (MQTT) from binary transfer (HTTPS) and enforces strict validation at each stage:

  1. Update Trigger via MQTT: The cloud backend publishes a compact JSON manifest to a dedicated command topic (such as rikode/bandung-lab/esp32-env/node-01/cmd/ota) containing the target version, HTTPS binary URL, file size, and expected SHA-256 hash.
  2. Pre-Flight Checks: Before opening an HTTP stream, the edge node verifies three conditions:
    • Target version differs from the currently running firmware version (preventing infinite update loops if a retained MQTT message is re-read).
    • Free space in the inactive OTA partition exceeds the incoming binary size.
    • Supply voltage or battery state-of-charge is safely above a minimum threshold (for example, greater than 3.6 V on a Li-ion cell) so the node will not brown out mid-write.
  3. Chunked HTTPS Streaming: Rather than allocating a 1.5 MB buffer in SRAM—which would exceed the entire RAM of most microcontrollers—the HTTP client downloads the binary over TLS in 4 KB chunks, writing each page sequentially to flash.
  4. Integrity & Cryptographic Signature Verification: Before flipping otadata, the bootloader or OTA library computes a SHA-256 checksum across the newly written flash partition and verifies an ECDSA/RSA cryptographic signature signed by your build server’s private key. If even a single bit flipped during cellular transmission—or if an attacker injected unauthorized firmware—the update is aborted immediately and ota_0 remains untouched.

Automatic Bootloader Rollback: Preventing Bricked Devices
#

Passing a SHA-256 checksum only proves that the binary arrived intact; it does not prove the new firmware works properly in the real environment. A newly compiled binary might pass bench tests yet hit a null-pointer panic when reading a specific field sensor, or fail to connect to the MQTT broker due to a misconfigured endpoint.

Automatic Bootloader Rollback protects against faulty updates using a two-phase commit on boot:

  1. Boot in PENDING_VERIFY State: When the bootloader switches from ota_0 to ota_1 for the first time, it marks ota_1 as pending verification rather than permanently valid.
  2. Self-Diagnostic Health Check: Once v1.1.0 boots, the application runs a startup validation sequence—initializing critical I2C/SPI sensors, connecting to Wi-Fi/cellular, authenticating with the TLS MQTT broker, and publishing a boot diagnostic message.
  3. Confirming Validity (esp_ota_mark_app_valid_cancel_rollback()): Only after the node successfully reaches the MQTT broker and operates cleanly for a defined stability window (such as 30–60 seconds) does the firmware mark ota_1 as permanently valid.
  4. Automatic Fallback on Failure: If the new firmware crashes, triggers a hardware watchdog reset, or fails to reach the broker before a stability timeout expires, the bootloader automatically reverts otadata back to ota_0 on the next reset—restoring v1.0.0 without human intervention.
#include <esp_ota_ops.h>

void validateNewFirmware(bool mqttConnected, bool sensorsHealthy) {
  const esp_partition_t* running = esp_ota_get_running_partition();
  esp_ota_img_states_t otaState;

  if (esp_ota_get_state_partition(running, &otaState) == ESP_OK) {
    if (otaState == ESP_OTA_IMG_PENDING_VERIFY) {
      if (mqttConnected && sensorsHealthy) {
        // Commit new firmware as valid; future reboots stay on this bank
        esp_ota_mark_app_valid_cancel_rollback();
      } else if (millis() > 120000) {
        // Failed to connect or read sensors within 2 minutes -> revert to previous bank
        esp_ota_mark_app_invalid_rollback_and_reboot();
      }
    }
  }
}

Fleet Rollout Strategies: Canary and Staged Deployments
#

Pushing an untested firmware update to 1,000 field devices simultaneously turns a single unnoticed bug into a fleet-wide outage. Cloud IoT platforms manage rollout risk through progressive stages:

  • Ring 0 — Bench & Lab Twin: Internal hardware-in-the-loop devices matching field PCB revisions.
  • Ring 1 — Canary Group (1%–5% of Fleet): A small subset of non-critical field nodes receives the update first and is monitored for 24–48 hours for reset counts, heap drift, and battery draw.
  • Ring 2 — Phased Regional Rollout (25% → 100%): Remaining nodes update in staggered batches, preventing hundreds of cellular or Wi-Fi nodes from saturating your CDN or MQTT broker at the exact same minute.

4 Common OTA Mistakes to Avoid
#

  1. Marking Firmware Valid Immediately on Line 1 of setup(): Calling esp_ota_mark_app_valid_cancel_rollback() before initializing sensors or connecting to the MQTT broker defeats the entire rollback mechanism. If a bug exists in your networking or TLS configuration, the device will lock itself into the broken partition permanently.
  2. Undersizing OTA Partitions in Custom Partition Tables: Leaving default 1 MB app partitions when your firmware—with TLS, BLE, and sensor drivers—already occupies 920 KB leaves almost no headroom for future features. Always size ota_0 and ota_1 with at least 30%–40% growth margin on a 4 MB or 8 MB flash chip.
  3. Subscribing to Retained OTA Command Topics Without Version Checks: If an OTA trigger message is published with Retain = true, a device that upgrades to v1.1.0 and reboots will immediately receive that exact same retained message again. Always compare target_version != CURRENT_FIRMWARE_VERSION (and track applied job IDs in NVS) before starting a download.
  4. Attempting Full-Binary OTA Over Ultra-Low-Bandwidth LoRaWAN: Transmitting a 1.2 MB firmware image over LoRaWAN at 50 bytes per packet would require over 24,000 downlink frames—violating regional ISM duty cycles and draining batteries completely. For LoRa nodes, either limit updates to compact binary patches (delta OTA) or pair the MCU with a short-range BLE interface for local technician updates.

Moving Forward in the Series
#

With dual-bank partitions, signed binaries, automatic rollback, and staged rollouts in place, your edge fleet becomes a living, maintainable software platform capable of evolving safely over years in the field. Now that we have built secure, resilient edge nodes from the silicon up, we need a cloud backend capable of ingesting, storing, and visualizing continuous streams of telemetry without buckling under write load.

In Part 7: IoT Backend & Time-Series Data Pipeline: Brokers, Workers, and Scalable Storage, we cross from embedded firmware into cloud architecture—exploring how to connect MQTT brokers to serverless ingestion workers, store high-frequency metrics efficiently, and build real-time dashboards.

Practical IoT Engineering - This article is part of a series.
Part 7: This Article