The idea: a copy of the device that is always online

A thermostat on a home network is often offline: the power goes out, the Wi-Fi drops, it sleeps to save battery. An app that talks to it directly fails every time. So the cloud keeps a device shadow (AWS IoT calls it that; Azure IoT Hub calls it a device twin, and some books say digital twin). It is one JSON document per device. The app reads and writes the document. The device syncs with it over MQTT whenever it is connected.

The app sets desired target 22 in the shadow in the cloud. The shadow holds desired target 22, reported target 20, delta target 22 and version 8. The delta goes to the device thermo-1 on update/delta, and the device reports back into reported. A rule copies readings from the shadow into a time-series table
The app writes desired, the device writes reported, and the cloud sends the device only the delta between them.

The page has one device, thermo-1, one cloud (an MQTT broker plus the shadow service), and one app. Each message on the canvas is an MQTT PUBLISH (or CONNECT, SUBSCRIBE…) that appears at its sender and then flies. Each one moves the page's clock by 1 s.

The shadow document

partwho writes itmeaning
state.desiredthe appwhat the app wants the device to do
state.reportedthe devicewhat the device says it is doing and measuring
state.deltathe service computes itthe desired keys whose value differs from reported
versionthe servicegoes up by 1 with every accepted update

At the start, desired is {"target": 20, "mode": "heat"}, reported is {"target": 20, "mode": "heat", "temp": 18.5}, the delta is {} and the version is 7. An update sends only the keys it changes; the service merges them into the document. Keys that are only in reported (like temp) never appear in the delta. A key in desired that reported does not have yet does.

The topics

The page uses the prefix things/thermo-1/shadow/. AWS IoT Device Shadow uses the same topic names under $aws/things/thermo-1/shadow/. Azure IoT Hub uses its own names for a device twin:

whaton the page and on AWSAzure IoT Hub device twin
write desired or reported…/updatedevice: $iothub/twin/PATCH/properties/reported/?$rid=1
the answer…/update/accepted, …/update/rejected$iothub/twin/res/204/?$rid=1&$version=6
tell the device what to change…/update/delta (only the differing keys)$iothub/twin/PATCH/properties/desired/?$version=8 (the change the back end made; the device compares itself)
read the whole document…/get → …/get/accepted$iothub/twin/GET/?$rid=2 → $iothub/twin/res/200/?$rid=2
version fieldversion$version on desired and on reported, ETag on the whole twin

On AWS the app may use the same MQTT topics or an HTTPS call; on Azure the back end changes desired through the service API, not over the device's MQTT connection.

Setting a value while the device is offline

In Demo: app sets 22 while the device is offline, thermo-1 loses power first. The app then publishes {"state": {"desired": {"target": 22}}}. The shadow accepts it at once: version 7 → 8, delta {"target": 22}. The app gets update/accepted and is done; it never waits for the device.

Time runs down with three lifelines: thermo-1, broker plus shadow, app. thermo-1 loses power; after 45 s the broker sends the will status = offline to the app. The app sends update desired target 22; the shadow goes from version 7 to 8 with delta target 22 and answers update/accepted v8; delta v8 is queued in the session. A minute later thermo-1 sends CONNECT Clean Start 0 and gets CONNACK SP=1, then update/delta target 22 v8. The heater goes to 22 °C, thermo-1 sends update reported target 22, the shadow goes to version 9 with an empty delta and answers update/accepted v9
The delta waits in the device's MQTT session; when the device comes back it gets the delta, acts, and reports, and the delta becomes empty.

The delta is published on update/delta. thermo-1 is subscribed to it at QoS 1 with a kept session (Clean Start 0), so the broker stores the message in the session, as in the offline subscriber of MQTT sessions. A minute later thermo-1 reconnects, gets CONNACK with Session Present 1, and then the queued delta. It sets the heater to 22 °C and reports {"reported": {"target": 22}}: version 9, delta {}. The clock ends at 12:01:55 after 10 messages.

The delta holds only what differs

In Demo: the delta holds only what differs, the app sets mode = "eco". Desired is now {"target": 20, "mode": "eco"}, but the delta is only {"mode": "eco"}, because reported already has target 20. The device gets less data and needs no logic to find what changed. Then the app sets target = 20, which reported already has. The update is accepted and the version still goes up (9 → 10), but the delta stays empty, so no update/delta is sent.

A device can apply an old delta. If the app changes desired twice while the device is away, the device may report a value that desired has already moved past. The report is accepted, the delta is still not empty, so the service publishes a new delta, and the device acts again. Desired and reported meet in the end.

Optimistic concurrency with the version

Two writers can clash. An app reads the shadow at version 7, the user thinks, and meanwhile the device reports a reading (version 8). If the app now writes, it acts on old data. So an update may carry "version": N. The service accepts it only if the document is still at N; otherwise it answers update/rejected with {"code": 409, "message": "Version conflict"} and changes nothing. This is optimistic concurrency: no lock is held while the user thinks; a conflict is found at write time.

In Demo: a stale update is rejected by version: the device reports 19.0 °C (version 8); the app sends target 24 with version 7 and gets 409; it reads again with get (version 8), sends target 24 with version 8, and is accepted (version 9). The device gets the delta and reports target 24 (version 10). An update with no version, like the device's own reports, always wins: last writer wins. Why the copies disagree in the first place is the topic of consistency patterns; the shadow is eventually consistent with the device.

Last will and the status topic

The shadow does not know whether the device is online: reported is just the last thing it said. That is the job of the MQTT last will. thermo-1's CONNECT carries a will things/thermo-1/status = offline (QoS 1, retain). After each connect it publishes status = online with retain itself. In Demo: last will vs clean disconnect, it first leaves cleanly: it publishes offline itself and sends DISCONNECT, so the broker drops the will. After a reconnect it loses power: no DISCONNECT, so after 1.5 × Keep Alive (45 s) the broker closes the connection and publishes the will. The packets themselves are on the MQTT page. AWS IoT Core also publishes its own connect and disconnect events on $aws/events/presence/…; Azure IoT Hub sends a will to the device's telemetry stream.

When the session is gone: ask with get

A queued delta lives only as long as the MQTT session. Sessions expire (AWS IoT Core: one hour by default), and a device that connects with Clean Start 1 throws its session away. In Demo: session lost, the device asks with get, the queued delta v8 is dropped with the session, CONNACK says Session Present 0, so thermo-1 subscribes again and publishes to get. The get/accepted answer holds the whole document, delta included, and the device acts on it as before (version 9). The safe habit: after every connect, if the session is not present, subscribe and get. The delta in the document is never lost; only the message announcing it is.

From reported readings to a time-series table

The shadow keeps only the latest value of each key. History goes elsewhere: a rule in the cloud listens to the accepted updates and writes each reading into a time-series table. On the page it is SELECT state.reported.temp, timestamp() FROM 'things/+/shadow/update/accepted', close to the SQL of AWS IoT rules. In Demo: the device reports readings, thermo-1 reports 19.0 °C and 19.5 °C; the table readings gets rows at 12:00:01 and 12:00:03 next to the first row 18.5 °C at 12:00:00, and the shadow ends at version 9.

Shadow vs a direct command

write the shadowcall the device directly (a remote procedure call)
device offlineaccepted; applied when it comes backtimes out or fails
the app learns the resultlater, when reported matches desiredat once, in the reply
good forsettings that should hold: a target temperature, a mode, a firmware versionactions that only make sense now: "reboot", "take a photo"

A direct call has the failure cases of RPC failure semantics: if the reply is lost, the app cannot tell whether the device acted. With a shadow, the app just looks at reported. The shadow is a managed service the provider runs for you, as described in cloud service models, but the state in it is still your data.

See also Bluetooth Low Energy, how a small battery device advertises, connects and pushes sensor values to a phone.

See also CoAP for IoT for how a client reads a sensor directly with GET and Observe over UDP.

See also LoRaWAN class A for a device that can only receive in two short windows after it sends, which is why a cloud copy of its state helps.

What the page leaves out

PUBACK packets of the QoS 1 messages (see MQTT QoS); TLS on port 8883 and X.509 device certificates; the metadata timestamps per key and the clientToken that matches an answer to its request; update/documents (the full before and after documents); named shadows (several per device); deleting a key by setting it to null; the get/rejected and delete topics; Azure's tags and ETag with If-Match on the service side; several apps and devices; message limits and throttling; and how the time-series database stores and compresses rows.

On the mind map

Open the Distributed Systems mind mapDistributedSystemsReplication: copies of data · what reads seeReplicationPartitioning: split data over nodesPartitioningTime and membership: order events, know who is aliveTime and membershipConsensus: agree on one value or logConsensusTransactions: one change across many servicesTransactionsMessaging: send events between systemsMessagingKafka internals: a replicated append-only logKafka internalsRedis internals: one thread, data in memoryRedis internalsKubernetes: reconcile desired stateKubernetesResilience and speed: stay up and fast under loadResilience and speedDelivery semanticsDelivery semanticscommit before or after processingMQTT QoS levelsMQTT QoS levelsQoS 2: PUBREC/PUBREL drop resent copiesCoAP over UDPCoAP over UDPCON resent at 2, 4, 8 s until an ACKIoT Device Shadowdelta = desired keys unlike reportedPush vs pullPush vs pullbroker pushes with prefetch vs pollAMQP in RabbitMQAMQP in RabbitMQexchange routes by binding; ack deletesChange data captureChange data capturetail the WAL, publish each row changeETL and SCD typesETL and SCD typesType 2 = new row, new key, history keptRedis StreamsRedis Streamsconsumer group, PEL until XACKLog vs queueLog vs queuequeue deletes on ack; log keeps offsetsOpen the Distributed Systems mind mapDistributed Systemssend events between systemsMessagingDelivery semanticsDelivery semanticscommit before or after processingMQTT QoS levelsMQTT QoS levelsQoS 2: PUBREC/PUBREL drop resent copiesCoAP over UDPCoAP over UDPCON resent at 2, 4, 8 s until an ACKIoT Device Shadowdelta = desired keys unlike reportedPush vs pullPush vs pullbroker pushes with prefetch vs pollAMQP in RabbitMQAMQP in RabbitMQexchange routes by binding; ack deletesChange data captureChange data capturetail the WAL, publish each row changeETL and SCD typesETL and SCD typesType 2 = new row, new key, history keptRedis StreamsRedis Streamsconsumer group, PEL until XACKLog vs queueLog vs queuequeue deletes on ack; log keeps offsets
This page on the Distributed Systems mind map · 104 pages in 10 branches · open it to see the whole map and test yourself in recall mode.