Ace Cloud Interviews
Home/AWS Tutorial/IoT Events
📡

AWS Internet of Things

IoT Events

Detect and respond to events from IoT sensors and applications

AWS IoT Events is a managed service for detecting and responding to events from IoT sensors and applications by modeling device states as finite state machines. Instead of writing complex rule chains or Lambda functions to detect conditions like "temperature was high for more than 5 minutes," you define a detector model with states and transitions driven by input conditions. Cloud engineers use it to build reliable event-driven IoT automation without managing the stateful logic infrastructure.

How IoT Events Works: Inputs, Detector Models, and States

IoT Events has three core concepts: Inputs (data arriving from IoT Core or other sources), Detector Models (finite state machine definitions), and Detector Instances (one running state machine per unique device or key value). This separation lets a single model handle an entire fleet.

ConceptDescriptionAnalogy
InputA named schema for incoming data; messages are routed to an Input and the payload is validated against the schemaLike an SQS queue schema or Kinesis stream definition
Detector ModelA finite state machine definition: states, transitions, conditions, and actionsLike a CloudFormation template - it is the blueprint, not the running instance
Detector InstanceA running instance of the detector model, keyed by a device ID or other attribute; each device gets its own instanceLike a running EC2 instance of an AMI - one model, many instances
StateA named condition the detector can be in (e.g., Normal, Warning, Alarm)Like a traffic light - Red, Yellow, Green
Transition eventA condition on incoming data that causes a state changeLike a guard clause - "if temperature > 80 for 300 seconds, enter Warning state"
ActionWhat happens when entering/exiting a state or during a transition - can trigger SNS, SQS, Lambda, IoT Core republish, IoT Jobs, or set timersLike a CloudWatch Alarm action

When a message arrives, IoT Events routes it to the matching Detector Instance (by the key expression you define) and evaluates transition conditions. This is fundamentally different from stateless IoT Core rules - IoT Events maintains state between messages.

Building a Detector Model: States, Transitions, and Actions

A detector model is defined in JSON. Each state contains onEnter, onInput, and onExit blocks with events (condition + actions). Transitions move the instance from one state to another when a condition evaluates to true.

bash
# Example: Temperature alarm detector model
# States: Normal -> Warning -> Alarm, with reset transitions back to Normal

# Create the input schema first
aws iotevents create-input \
  --input-name "TemperatureInput" \
  --input-definition '{
    "attributes": [
      {"jsonPath": "deviceId"},
      {"jsonPath": "temperature"},
      {"jsonPath": "status"}
    ]
  }'

# Create the detector model (abbreviated - full model is larger)
aws iotevents create-detector-model \
  --detector-model-name "TemperatureAlarm" \
  --detector-model-definition '{
    "states": [
      {
        "stateName": "Normal",
        "onInput": {
          "events": [],
          "transitionEvents": [{
            "eventName": "ToWarning",
            "condition": "$input.TemperatureInput.temperature > 75",
            "actions": [],
            "nextState": "Warning"
          }]
        },
        "onEnter": {"events": []},
        "onExit": {"events": []}
      },
      {
        "stateName": "Warning",
        "onEnter": {
          "events": [{
            "eventName": "SetWarningTimer",
            "condition": "true",
            "actions": [{"setTimer": {"timerName": "WarningTimer", "seconds": 300}}]
          }]
        },
        "onInput": {
          "transitionEvents": [
            {
              "eventName": "ToAlarm",
              "condition": "timeout(\"WarningTimer\") && $input.TemperatureInput.temperature > 75",
              "actions": [{"sns": {"targetArn": "arn:aws:sns:us-east-1:123456789:TempAlerts"}}],
              "nextState": "Alarm"
            },
            {
              "eventName": "BackToNormal",
              "condition": "$input.TemperatureInput.temperature <= 70",
              "actions": [{"clearTimer": {"timerName": "WarningTimer"}}],
              "nextState": "Normal"
            }
          ]
        }
      }
    ],
    "initialStateName": "Normal"
  }' \
  --key "deviceId" \
  --role-arn "arn:aws:iam::123456789:role/iotevents-role"
💡

The key attribute (--key "deviceId") is what causes IoT Events to create a separate Detector Instance per device. Without the key, all messages from all devices share one state machine instance, which would cause false transitions when one device's temperature affects another device's state.

Timers and Conditions: Stateful Time-Based Logic

Timers are one of the most powerful IoT Events features. They allow time-based state transitions that would require complex Lambda logic to implement otherwise. Timers are set, reset, and cleared within state actions.

Timer OperationWhen to UseExample
setTimer(name, seconds)Start a countdown when entering a warning stateSet a 5-minute timer when temperature enters Warning - if timer fires and still warm, go to Alarm
resetTimer(name)Restart the countdown each time a condition is still activeReset the timer each time a heartbeat arrives - if timer fires (no heartbeat), device is offline
clearTimer(name)Cancel the timer when the condition resolvesClear the warning timer when temperature returns to normal - prevents false Alarm transitions
timeout("timerName") in conditionUse as a condition in a transition - fires when timer expiresCombine with current state check: "timeout(\"WatchdogTimer\") AND $input.Status.heartbeat == false"
Condition FeatureSyntax ExampleNotes
Input attribute reference$input.InputName.jsonPathUse the exact jsonPath from the Input schema
AND conditioncondA && condBBoth must be true for transition
OR conditioncondA || condBEither must be true for transition
Timer expirytimeout("timerName")True once, then false until timer is reset
Variable comparison$variable.myVar > 10Variables are set by setVariable action and persist in the detector instance
⚠️

IoT Events conditions are evaluated as JavaScript-like expressions but there is no loop or iteration support. For complex conditions involving aggregates (e.g., "5 out of 10 sensors are hot"), pre-aggregate using Lambda or IoT Analytics before sending to IoT Events, then check the aggregate value in the condition.

Alarm Actions: What IoT Events Can Trigger

Actions execute when entering or exiting a state or during a transition. Multiple actions can be defined for a single event.

Action TypeWhat It DoesUse Case
SNSPublish a message to an SNS topicAlert operations team via email/SMS when alarm state is entered
SQSSend a message to an SQS queueTrigger a downstream processing workflow for incident management
LambdaInvoke a Lambda function with event contextComplex remediation - restart a process, update a database, call an external API
IoT Core republishPublish a message back to an IoT Core MQTT topicTrigger IoT Core rules or send a command back to the device
IoT JobsCreate an IoT Job targeting the deviceAutomatically push a diagnostic script or config change to a misbehaving device
IoT SiteWiseSend data to an IoT SiteWise asset propertyUpdate equipment status in SiteWise for dashboard visualization
FirehoseWrite event data to Kinesis Data FirehoseArchive all state transition events for audit and analytics
setVariableSet an internal variable in the detector instanceCount failure events, store last known good temperature for delta calculations
setTimer / resetTimer / clearTimerManage countdown timersCore mechanism for time-based state logic

IoT Events vs IoT Core Rules: When to Use Each

Both IoT Core Rules and IoT Events can trigger actions based on device data. The key difference is statefulness: rules are stateless (evaluate one message at a time) while IoT Events is stateful (conditions can span multiple messages over time).

ScenarioUse IoT Core RulesUse IoT Events
Route telemetry to S3/DynamoDB/KinesisYes - simple routing with no state neededNo - overkill for stateless routing
Alert when temperature > 80 in one messageYes - WHERE clause in rule SQLPossible but unnecessary for single-message conditions
Alert when temperature > 80 for more than 5 minutesNo - rules are stateless, no memory of previous messagesYes - use timer-based state transition
Alert when device stops sending heartbeats for 10 minutesNo - requires state tracking of last message timeYes - use a watchdog timer that resets on each heartbeat message
Alert when 3 consecutive readings exceed a thresholdNo - no counter state availableYes - use setVariable to count consecutive violations
Complex multi-condition across multiple devicesLimited - cannot correlate across multiple devices nativelyYes - one detector model with multiple inputs, key on fleet-level identifier
💡

The decision rule: if your alert condition requires memory of more than one message, use IoT Events. If it can be answered by looking at a single message in isolation, a Rule is simpler and cheaper.

Pricing Model

DimensionPriceNotes
Messages evaluated$0.10 per 1,000 messages evaluatedCharged for each message sent to a Detector Instance; does not matter how many states it touches
Detector instance state changesIncluded in message evaluation costNo additional charge for transitions
Detector instance storage$0.000025 per detector instance per hourApproximately $0.018 per device per month for continuously running instances
💡

Cost optimization: delete Detector Instances for decommissioned devices using the DeleteDetector API. Inactive instances that have not received messages for 90 days are automatically deleted, but proactively cleaning up reduces costs immediately.

🎯

Interview Focus Points

  • 1Explain the difference between IoT Core Rules and IoT Events - give a scenario where only IoT Events is the right choice.
  • 2What is a Detector Instance and how does the key attribute control how many instances are created?
  • 3How do you implement a watchdog timer in IoT Events to detect when a device stops sending heartbeats?
  • 4Walk me through the state machine design for a factory machine that should alert if vibration stays above threshold for more than 2 minutes.
  • 5How does IoT Events maintain state between messages and what happens to that state when a device is offline?
  • 6Can IoT Events correlate events across multiple devices in the same fleet? How?
  • 7What are IoT Events timers and how do setTimer, resetTimer, and clearTimer work together in a real alarm scenario?
  • 8How would you handle a requirement to send a different alert on the first alarm versus subsequent repeated alarms without clearing?