← All tutorials
IoT Γ— Agents

IoT Γ— Agents β€” a fridge that restocks itself

An IoT hub is great at getting signals off physical devices and into the cloud reliably and securely. An agent is great at deciding what to do about a signal. Wire them together and a device event can trigger reasoning and real-world action β€” like a fridge noticing it's low on milk and ordering more.

The example we'll build. A smart fridge detects the milk shelf is nearly empty and publishes an event to AWS IoT Core. A rule routes it to a Strands agent running on Bedrock AgentCore, which checks inventory, price and budget, places the smallest sensible grocery order, and tells the fridge and the owner it's done β€” with spend limits and human approval as guardrails.
πŸ₯› sensorβ†’ AWS IoT Coreβ†’ ruleβ†’ agent reasonsβ†’ order + notify

This is the "sense β†’ decide β†’ act" loop that underlies most useful IoT-plus-AI systems: predictive maintenance, energy optimization, and here, autonomous replenishment. The fridge is a friendly stand-in for any device that should trigger an intelligent response.

Foundations  Two halves: the hub and the agent

The integration works because each side does a job the other shouldn't. Keeping that split clean is the whole design.

The nervous system

IoT hub (AWS IoT Core)

Securely connects millions of devices, ingests telemetry over MQTT, tracks each device's state, and routes events to the cloud. It moves signals; it doesn't reason.

The brain

Agent (Strands + AgentCore)

Receives an event and decides: gather context via tools, weigh options, act, or ask a human. It reasons; it doesn't talk to devices directly.

Why not put the logic on the device? Devices are constrained, hard to update, and shouldn't hold cloud/grocery credentials. Keep the fridge dumb (sense & report) and put the changing business logic β€” budgets, vendors, approval rules β€” in the agent, where it's easy to change and audit.

The hub  What AWS IoT Core provides

Four primitives do almost all the work in this example:

Device Gateway & MQTT broker pub/sub messaging

Solves A managed, always-on broker devices publish to and subscribe from over MQTT (topics like fridge/kitchen-01/inventory) β€” scaling to huge fleets without you running a message broker.

X.509 certificates & IoT policies per-device identity

Solves Every device gets its own certificate and a scoped policy, so a fridge can only publish to its own topics. This is what makes device-triggered actions trustworthy.

Device Shadow last-known state, even offline

Solves A JSON document of each device's reported and desired state. The cloud can read the fridge's last state when it's asleep, and set a desired value (e.g. "milk ordered") the device syncs on reconnect.

Rules Engine SQL routing to AWS services

Solves A SQL-like rule evaluates every incoming message and routes matches to targets (Lambda, EventBridge, DynamoDB, SNS…). This is the bridge from "a message arrived" to "invoke the agent" β€” with a condition, so only genuinely low stock wakes the brain.

The bridge  The integration pattern

Five stages connect the sensor to a placed order. The same shape works for any "device event β†’ intelligent action" system.

1 Sense→ 2 Ingest & route→ 3 Reason→ 4 Act→ 5 Close the loop
   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   MQTT     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ AWS IoT Core ───────────────────┐
   β”‚  Fridge  │──publish──▢ β”‚  Device Gateway β†’ Rules Engine (SELECT … WHERE     β”‚
   β”‚ (sensor) β”‚  telemetry  β”‚  level_pct < 10)  β†’  Lambda / EventBridge target    β”‚
   β””β”€β”€β”€β”€β–²β”€β”€β”€β”€β”€β”˜             β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
        β”‚ desired: "ordered"                            β”‚ invoke
        β”‚ (Device Shadow)                               β–Ό
   β”Œβ”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”        β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ Bedrock AgentCore Runtime ────────┐
   β”‚  notify_user (SNS) │◀──act──│  Strands agent  +  Memory (budget, past buys)  β”‚
   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜        β”‚  tools: inventory Β· price Β· budget Β· order     β”‚
                                 β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                                         β–Ό place_order
                                                 β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                                                 β”‚  Grocery API  β”‚
                                                 β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
#StageWhat happens
1SenseA weight/vision sensor sees the milk shelf drop below threshold; the fridge publishes an MQTT event (and updates its Device Shadow).
2Ingest & routeIoT Core authenticates the device, and a Rules Engine rule with WHERE level_pct < 10 forwards only low-stock events to a Lambda that invokes the agent.
3ReasonThe Strands agent on AgentCore checks on-hand inventory, gets a live price, and confirms the purchase fits the monthly budget.
4ActIt places the smallest sensible order via the grocery tool β€” or requests human approval if over the spend limit β€” and notifies the owner over SNS.
5Close the loopIt writes the purchase to memory and sets the fridge's Device Shadow desired state to "milk: ordered" so the door display updates.

The example  Smart-fridge walkthrough

Follow one carton of milk through the system.

Step 1 The fridge notices

A load cell under the milk shelf reads 5% of a full carton. Rather than decide anything, the fridge just reports a fact to its own topic: { "item": "milk", "level_pct": 5 }. Dumb device, single responsibility.

Step 2 IoT Core filters & forwards

Most messages are normal levels and are ignored. This one matches the rule's level_pct < 10 condition, so IoT Core hands it to the trigger Lambda β€” which turns the raw event into a natural-language task and invokes the agent.

Step 3 The agent reasons

The agent calls get_inventory("milk") (none in the pantry), check_price("milk") ($3.49), then within_budget(3.49) (true). Small, in-budget, needed β€” it proceeds.

Step 4 It acts β€” safely

place_order("milk", 1) submits to the grocery partner; notify_user(...) pushes "Ordered 1Γ— milk ($3.49) β€” arriving tomorrow." Had it been a $120 case of steaks, the agent would have called request_approval instead and waited.

Step 5 The loop closes

The agent records the spend in AgentCore Memory (so next week's budget math is right) and sets the Device Shadow desired state to milk: ordered; the fridge's screen shows "milk on the way," and won't re-trigger for the same carton.

Hands-on  The code, end to end

Five files, one per stage. Switch tabs; hit Copy to grab any snippet. (APIs evolve fast β€” treat these as a faithful sketch and confirm names against current docs.)

smart-fridge/
# fridge_device.py β€” runs ON the fridge (AWS IoT Device SDK v2).
# Its ONLY job: sense and report. No business logic, no credentials to shops.
import json
from awscrt import mqtt
from awsiot import mqtt_connection_builder

conn = mqtt_connection_builder.mtls_from_path(
    endpoint="xxxx-ats.iot.us-east-1.amazonaws.com",
    cert_filepath="fridge.cert.pem",          # this device's X.509 identity
    pri_key_filepath="fridge.private.key",
    ca_filepath="AmazonRootCA1.pem",
    client_id="fridge-kitchen-01",
)
conn.connect().result()

# A load cell says the milk shelf is nearly empty β€” just report the fact.
event = {"deviceId": "fridge-kitchen-01", "item": "milk", "level_pct": 5}
conn.publish(
    topic="fridge/kitchen-01/inventory",
    payload=json.dumps(event),
    qos=mqtt.QoS.AT_LEAST_ONCE,
)
Read it as the pipeline. fridge_device.py reports β†’ iot_rule.sql filters β†’ restock_trigger.py adapts β†’ agent.py decides β†’ app.py hosts it. Each file maps to exactly one stage from section 3.

Do not skip  Guardrails & safety

An agent that spends real money from a device trigger is exactly where things go wrong. Four guardrails are non-negotiable.

πŸ” Idempotency β€” don't order 20 milks

Risk A low sensor can fire every minute until the shelf is refilled, re-invoking the agent each time.

Fix Dedupe on (deviceId, item, day) with a short-TTL record in DynamoDB or AgentCore Memory; if an open order exists for the item, the agent no-ops. Set the Shadow to ordered so the device stops re-alerting.

πŸ’Έ Spend limits & human-in-the-loop

Risk A bad price feed or hallucinated quantity drains the grocery budget.

Fix Hard budget cap in within_budget; anything over a threshold routes to request_approval and waits for the owner. The agent can suggest, but a human confirms big spends.

πŸ” Least privilege & scoped credentials

Risk A compromised fridge could publish as other devices or reach systems it shouldn't.

Fix The device's IoT policy is scoped to its own topics (e.g. fridge/${iot:Connection.Thing.ThingName}/*). The agent β€” not the device β€” holds the grocery credential, via AgentCore Identity, so device compromise can't place orders directly.

🧯 Fail safe, not fail open

Risk The price API is down, so the agent guesses and orders blindly.

Fix If a required tool fails, the agent notifies the user and stops β€” it never orders on missing data. Every action is traced (AgentCore observability) for audit.

Rule of thumb. Device triggers are untrusted input. Validate them, make actions idempotent, cap the blast radius (spend limits), and keep a human in the loop for anything expensive or irreversible.

Who does what β€” recap

StageAWS pieceRole in the fridge example
SenseDevice + IoT Device SDK (MQTT)Fridge publishes level_pct; updates its Shadow
AuthenticateX.509 cert + IoT policyPer-fridge identity, scoped to its own topics
Ingest & routeIoT Core Rules EngineWHERE level_pct < 10 β†’ invoke trigger
AdaptLambda (or EventBridge)Turns the raw event into a task, invokes the agent
ReasonStrands agent on AgentCoreCheck inventory Β· price Β· budget Β· decide
RememberAgentCore MemoryMonthly spend, open orders, preferences
ActTools β†’ Grocery API, SNSPlace order (or ask approval), notify owner
Close loopDevice Shadow (desired)Sets milk: ordered; fridge display updates
Portable pattern. Swap the fridge for an HVAC unit and "order milk" for "schedule maintenance," or the Strands+AgentCore agent for a Google ADK agent β€” the IoT-hub-to-agent bridge is unchanged. The hub moves signals; the agent makes decisions.

Knowledge check

Six questions on the integration. Pick an answer for each, then check your score.

1. What decides β€” based on a condition β€” that a low-milk message should wake the agent?

2. What holds the fridge's last-known state and a "desired" value even while it's offline?

3. Why should business logic (budgets, vendors, approvals) live in the agent, not on the fridge?

4. A low sensor fires every minute until refilled. Which guardrail prevents 20 duplicate orders?

5. The order would exceed the spend limit. What should the agent do?

6. Where does the Strands agent run so it gets scaling, session isolation and memory without extra plumbing?

Next steps

πŸ“‘ AWS IoT Core

Developer guide β€” MQTT, Device Shadow, and the Rules Engine.

🟠 Strands Agents

The SDK used for the fridge brain β€” tools and the model-driven loop.

πŸ—οΈ Bedrock AgentCore

Runtime, Memory, Identity β€” where the agent is hosted safely.

🧰 ADK comparison

Agent Development Kits β€” pick a different brain (Google ADK, LangGraph) for the same bridge.

☁️ AWS services guide

The field guide β€” Lambda, SNS, DynamoDB and the rest, in context.