187  Communication Models for IoT

187.1 Learning Objectives

By the end of this chapter, you will be able to:

  • Compare Communication Patterns: Distinguish between request-response, publish-subscribe, and event-driven architectures
  • Select Appropriate Models: Choose the right communication model based on IoT application requirements
  • Implement Synchronous vs Asynchronous: Design systems using blocking and non-blocking communication patterns
  • Apply Push and Pull Strategies: Determine when to push data to consumers versus when consumers should pull data
  • Design Message Flows: Create efficient message routing patterns for multi-device IoT systems
  • Evaluate Trade-offs: Analyze latency, bandwidth, reliability, and scalability implications of each model

187.2 Prerequisites

Before diving into this chapter, you should be familiar with:

  • Networking Basics: Understanding TCP/IP, UDP, and basic network protocols provides foundation for communication models
  • IoT Protocols Overview: Knowledge of MQTT, CoAP, HTTP, and WebSocket helps contextualize when each communication model is used
  • Communication and Protocol Bridging: Understanding gateway functions and protocol translation complements communication model selection

Think of communication models like different ways people can talk to each other:

Request-Response: Like asking a question and waiting for an answer. You call customer service, ask β€œWhat’s my balance?”, and they tell you. You can’t do anything else until they respond.

Publish-Subscribe: Like subscribing to a newsletter. Many people can subscribe, and whenever the newsletter is published, everyone gets a copy automatically. The publisher doesn’t need to know who’s reading.

Event-Driven: Like setting your phone to vibrate when you get a text. You don’t constantly check your phone - it notifies you when something happens.

Model Real-World Analogy
Request-Response Asking a librarian for a specific book
Publish-Subscribe Subscribing to a YouTube channel
Push Getting a text message notification
Pull Refreshing your email to check for new messages
NoteKey Takeaway

In one sentence: The choice of communication model fundamentally shapes your IoT system’s latency, scalability, battery life, and resilience - there is no β€œbest” model, only the best fit for your requirements.

Remember this rule: Use request-response for queries and commands needing confirmation, pub-sub for streaming sensor data to multiple consumers, and event-driven for battery-constrained devices that need to sleep between activities.

187.3 Request-Response Pattern

15 min

Intermediate

The request-response pattern is the most intuitive communication model, where a client sends a request and waits for a response from the server. This synchronous interaction ensures the client knows the outcome of each operation.

187.3.1 How Request-Response Works

%%{init: {'theme': 'base', 'themeVariables': { 'primaryColor': '#2C3E50', 'primaryTextColor': '#fff', 'primaryBorderColor': '#16A085', 'lineColor': '#16A085', 'secondaryColor': '#E67E22', 'tertiaryColor': '#7F8C8D'}}}%%
sequenceDiagram
    participant C as Client/Device
    participant S as Server/Cloud

    C->>S: Request (GET temperature)
    Note right of S: Process request
    S-->>C: Response (25.5 C)

    C->>S: Request (SET thermostat=22)
    Note right of S: Execute command
    S-->>C: Response (OK, applied)

    C->>S: Request (GET status)
    S-->>C: Response (Error: timeout)
    Note left of C: Handle error

187.3.2 Characteristics

Aspect Request-Response Behavior
Timing Synchronous - client blocks until response
Coupling Tight - client must know server address
Delivery Confirmed - response indicates success/failure
Scalability Limited - server handles one request at a time per connection
Use Cases Configuration, queries, commands requiring confirmation

187.3.3 IoT Applications

Best suited for: - Reading device configuration parameters - Sending commands that require acknowledgment (e.g., β€œturn off heater”) - Querying current sensor values on demand - REST API interactions with cloud platforms

Protocols using request-response: - HTTP/HTTPS (GET, POST, PUT, DELETE) - CoAP (with CON messages) - Modbus (master-slave polling)

187.3.4 Limitations in IoT

While intuitive, request-response has drawbacks for IoT:

  1. Polling overhead: To detect changes, clients must repeatedly poll, wasting bandwidth
  2. Latency: Real-time updates require frequent polling, increasing load
  3. Scalability: Each client connection consumes server resources
  4. Battery drain: Constant polling keeps radios active, draining batteries

187.4 Publish-Subscribe Pattern

20 min

Intermediate

The publish-subscribe (pub/sub) pattern decouples message producers from consumers through an intermediary broker. Publishers send messages to topics without knowing who will receive them, and subscribers receive messages from topics they’re interested in.

187.4.1 How Pub/Sub Works

%%{init: {'theme': 'base', 'themeVariables': { 'primaryColor': '#2C3E50', 'primaryTextColor': '#fff', 'primaryBorderColor': '#16A085', 'lineColor': '#16A085', 'secondaryColor': '#E67E22', 'tertiaryColor': '#7F8C8D'}}}%%
graph TB
    subgraph Publishers
        P1[Temp Sensor]
        P2[Humidity Sensor]
        P3[Motion Sensor]
    end

    subgraph Broker["Message Broker"]
        T1[sensors/temp]
        T2[sensors/humidity]
        T3[sensors/motion]
    end

    subgraph Subscribers
        S1[Dashboard]
        S2[Alert System]
        S3[Data Logger]
    end

    P1 -->|publish| T1
    P2 -->|publish| T2
    P3 -->|publish| T3

    T1 -->|subscribe| S1
    T1 -->|subscribe| S3
    T2 -->|subscribe| S1
    T2 -->|subscribe| S3
    T3 -->|subscribe| S2

    style Broker fill:#E67E22,stroke:#2C3E50,color:#fff
    style Publishers fill:#16A085,stroke:#2C3E50,color:#fff
    style Subscribers fill:#2C3E50,stroke:#16A085,color:#fff

187.4.2 Key Benefits for IoT

Benefit Explanation
Decoupling Publishers and subscribers don’t need to know about each other
Scalability Adding new subscribers doesn’t affect publishers
Real-time Messages delivered immediately upon publication
Efficiency No polling - data sent only when values change
Fan-out One message can reach multiple subscribers

187.4.3 Topic Hierarchies

MQTT and similar protocols support hierarchical topics with wildcards:

sensors/building1/floor2/room203/temperature
sensors/building1/floor2/+/temperature     # + matches single level
sensors/building1/#                         # # matches all remaining levels

187.4.4 Quality of Service (QoS) Levels

MQTT defines three QoS levels that trade reliability for overhead:

QoS Name Guarantee Overhead Use Case
0 At-most-once May lose messages Lowest Frequent sensor telemetry
1 At-least-once Delivered, may duplicate Medium Commands, alerts
2 Exactly-once One and only one delivery Highest Financial transactions, critical commands

187.5 Push vs Pull Communication

15 min

Foundational

The distinction between push and pull communication determines who initiates data transfer and when data flows through the system.

187.5.1 Push Model

In push communication, the data source initiates transmission when new data is available:

%%{init: {'theme': 'base', 'themeVariables': { 'primaryColor': '#2C3E50', 'primaryTextColor': '#fff', 'primaryBorderColor': '#16A085', 'lineColor': '#16A085', 'secondaryColor': '#E67E22', 'tertiaryColor': '#7F8C8D'}}}%%
sequenceDiagram
    participant S as Sensor
    participant C as Cloud

    Note over S: Temperature changes
    S->>C: Push: temp=26.5C

    Note over S: 5 minutes later...
    Note over S: Temperature stable
    Note over S: No transmission needed

    Note over S: Temperature changes
    S->>C: Push: temp=27.1C

Characteristics: - Source decides when to send (event-driven) - Efficient - no data sent when unchanged - Real-time - immediate notification - Source must maintain connection or wake periodically

187.5.2 Pull Model

In pull communication, the consumer requests data when needed:

%%{init: {'theme': 'base', 'themeVariables': { 'primaryColor': '#2C3E50', 'primaryTextColor': '#fff', 'primaryBorderColor': '#16A085', 'lineColor': '#16A085', 'secondaryColor': '#E67E22', 'tertiaryColor': '#7F8C8D'}}}%%
sequenceDiagram
    participant C as Consumer/App
    participant S as Sensor/Server

    C->>S: Request: get temperature
    S-->>C: Response: 26.5C

    Note over C: Wait 1 minute

    C->>S: Request: get temperature
    S-->>C: Response: 26.5C (unchanged)

    Note over C: Wait 1 minute

    C->>S: Request: get temperature
    S-->>C: Response: 27.1C

Characteristics: - Consumer decides when to request - May miss events between polls - Polling overhead even when data unchanged - Source can sleep between requests (for battery devices)

187.5.3 Comparison Table

Factor Push Pull
Latency Low (immediate) Variable (depends on poll interval)
Bandwidth Efficient (only when changed) Wasteful if data rarely changes
Battery Radio active on source events Radio wakes on poll schedule
Missed Events None (if connection maintained) Possible between polls
Server Load Varies with event rate Predictable (poll rate)
Best For Streaming, alerts, sparse events On-demand queries, batch processing

187.6 Event-Driven Architecture

20 min

Advanced

Event-driven architecture (EDA) structures systems around the production, detection, and reaction to events. Unlike request-response where the caller waits for completion, event-driven systems decouple producers from consumers through asynchronous event channels.

187.6.1 Event-Driven Components

%%{init: {'theme': 'base', 'themeVariables': { 'primaryColor': '#2C3E50', 'primaryTextColor': '#fff', 'primaryBorderColor': '#16A085', 'lineColor': '#16A085', 'secondaryColor': '#E67E22', 'tertiaryColor': '#7F8C8D'}}}%%
graph LR
    subgraph Producers["Event Producers"]
        S1[Motion Sensor]
        S2[Door Contact]
        S3[Temp Sensor]
    end

    subgraph Bus["Event Bus/Stream"]
        E1[MotionDetected]
        E2[DoorOpened]
        E3[TempThreshold]
    end

    subgraph Consumers["Event Consumers"]
        C1[Alert Service]
        C2[Logging Service]
        C3[Automation Engine]
    end

    S1 -->|emit| E1
    S2 -->|emit| E2
    S3 -->|emit| E3

    E1 --> C1
    E1 --> C2
    E2 --> C1
    E2 --> C3
    E3 --> C3

    style Bus fill:#E67E22,stroke:#2C3E50,color:#fff

187.6.2 Event Types in IoT

Event Type Description Example
State Change Value crosses threshold Temperature exceeds 30C
Condition Complex multi-sensor state β€œRoom occupied AND lights off”
Command Action request β€œActivate sprinkler zone 3”
Notification Informational alert β€œBattery below 20%”
Audit Historical record β€œUser John unlocked door at 14:32”

187.6.3 Complex Event Processing (CEP)

CEP systems analyze event streams to detect patterns across multiple events:

Pattern Types: - Sequence: Event A followed by Event B within 5 minutes - Aggregation: Average temperature across 10 sensors exceeds threshold - Absence: No heartbeat received for 60 seconds (device offline) - Correlation: Door opened without prior authentication

187.7 Synchronous vs Asynchronous Communication

15 min

Intermediate

The distinction between synchronous and asynchronous communication determines whether the sender waits for completion before proceeding.

187.7.1 Synchronous Communication

%%{init: {'theme': 'base', 'themeVariables': { 'primaryColor': '#2C3E50', 'primaryTextColor': '#fff', 'primaryBorderColor': '#16A085', 'lineColor': '#16A085', 'secondaryColor': '#E67E22', 'tertiaryColor': '#7F8C8D'}}}%%
sequenceDiagram
    participant D as Device
    participant C as Cloud API

    D->>C: Send reading (blocking)
    Note over D: WAITING...<br/>Cannot do other work
    C-->>D: Response received
    Note over D: Continue execution
    D->>C: Next operation (blocking)
    Note over D: WAITING...
    C-->>D: Response received

Characteristics: - Caller blocks until operation completes - Simple control flow (sequential execution) - Timeout handling required - Latency adds up for multiple operations

187.7.2 Asynchronous Communication

%%{init: {'theme': 'base', 'themeVariables': { 'primaryColor': '#2C3E50', 'primaryTextColor': '#fff', 'primaryBorderColor': '#16A085', 'lineColor': '#16A085', 'secondaryColor': '#E67E22', 'tertiaryColor': '#7F8C8D'}}}%%
sequenceDiagram
    participant D as Device
    participant Q as Message Queue
    participant C as Cloud Processor

    D->>Q: Send reading (non-blocking)
    Note over D: Continue immediately
    D->>Q: Send another reading
    Note over D: Reading sensors...
    Q->>C: Deliver when ready
    C->>Q: Acknowledge
    Q->>C: Deliver second message

Characteristics: - Caller continues immediately after sending - Complex control flow (callbacks, promises, event loops) - Built-in buffering handles burst traffic - Decouples sender from receiver timing

187.7.3 Comparison for IoT

Aspect Synchronous Asynchronous
Code Complexity Simple (linear flow) Complex (callbacks/async-await)
Error Handling Immediate (exception at call site) Delayed (callback or later check)
Resource Usage Thread blocked during wait Thread free during wait
Latency Sensitivity High impact (blocking time) Low impact (background processing)
Reliability Fail immediately if unavailable Queue for retry when available
Debugging Easy stack traces Harder async trace correlation

187.8 Message Patterns for IoT

20 min

Advanced

Different IoT scenarios require different message patterns. Understanding these patterns helps design efficient, scalable communication.

187.8.1 One-to-One (Point-to-Point)

Direct communication between two endpoints:

Sensor --> Gateway
Device --> Cloud API
Controller --> Actuator

Use cases: Direct commands, configuration updates, device-to-gateway links

187.8.2 One-to-Many (Broadcast/Multicast)

Single message delivered to multiple recipients:

%%{init: {'theme': 'base', 'themeVariables': { 'primaryColor': '#2C3E50', 'primaryTextColor': '#fff', 'primaryBorderColor': '#16A085', 'lineColor': '#16A085', 'secondaryColor': '#E67E22', 'tertiaryColor': '#7F8C8D'}}}%%
graph TD
    CMD[Firmware Update Command] --> D1[Device 1]
    CMD --> D2[Device 2]
    CMD --> D3[Device 3]
    CMD --> D4[Device 4]
    CMD --> D5[Device ...]

    style CMD fill:#E67E22,stroke:#2C3E50,color:#fff

Use cases: Firmware updates, configuration broadcasts, time synchronization

187.8.3 Many-to-One (Aggregation)

Multiple sources sending to single destination:

%%{init: {'theme': 'base', 'themeVariables': { 'primaryColor': '#2C3E50', 'primaryTextColor': '#fff', 'primaryBorderColor': '#16A085', 'lineColor': '#16A085', 'secondaryColor': '#E67E22', 'tertiaryColor': '#7F8C8D'}}}%%
graph TD
    S1[Sensor 1] --> GW[Gateway/Aggregator]
    S2[Sensor 2] --> GW
    S3[Sensor 3] --> GW
    S4[Sensor N] --> GW
    GW --> Cloud[Cloud Platform]

    style GW fill:#E67E22,stroke:#2C3E50,color:#fff

Use cases: Sensor data collection, log aggregation, fleet telemetry

187.8.4 Request-Reply Pattern

For commands requiring responses, implement request-reply over pub/sub:

Device publishes: commands/device123/request  {id: "req-456", action: "reboot"}
Server publishes: commands/device123/response {id: "req-456", status: "accepted"}

187.8.5 Event Sourcing Pattern

Store all state changes as a sequence of events:

[Event 1] ThermostatCreated {id: "t1", setpoint: 20}
[Event 2] SetpointChanged {id: "t1", old: 20, new: 22}
[Event 3] ModeChanged {id: "t1", mode: "cooling"}
[Event 4] SetpointChanged {id: "t1", old: 22, new: 21}

Benefits: Complete audit trail, replay capability, debugging, time-travel queries

187.9 Communication Model Selection Guide

10 min

Intermediate

Use this decision framework to select appropriate communication models:

%%{init: {'theme': 'base', 'themeVariables': { 'primaryColor': '#2C3E50', 'primaryTextColor': '#fff', 'primaryBorderColor': '#16A085', 'lineColor': '#16A085', 'secondaryColor': '#E67E22', 'tertiaryColor': '#7F8C8D'}}}%%
flowchart TD
    START[Select Communication Model] --> Q1{Need immediate<br/>confirmation?}

    Q1 -->|Yes| Q2{Multiple consumers?}
    Q1 -->|No| Q3{Data streaming<br/>or events?}

    Q2 -->|No| RR[Request-Response<br/>HTTP/CoAP]
    Q2 -->|Yes| HYBRID[Pub-Sub + Request<br/>for critical ops]

    Q3 -->|Yes| Q4{Need historical<br/>replay?}
    Q3 -->|No| POLL[Poll-based<br/>Request-Response]

    Q4 -->|Yes| ES[Event Sourcing<br/>Kafka/EventStore]
    Q4 -->|No| PS[Publish-Subscribe<br/>MQTT/AMQP]

    style START fill:#2C3E50,stroke:#16A085,color:#fff
    style RR fill:#16A085,stroke:#2C3E50,color:#fff
    style PS fill:#16A085,stroke:#2C3E50,color:#fff
    style ES fill:#E67E22,stroke:#2C3E50,color:#fff
    style HYBRID fill:#E67E22,stroke:#2C3E50,color:#fff

187.9.1 Quick Reference Table

Scenario Recommended Model Protocol Examples
Device configuration Request-Response HTTP, CoAP
Sensor telemetry streaming Pub-Sub (async) MQTT, AMQP
Commands with confirmation Request-Response HTTP, CoAP CON
Alerts to multiple systems Pub-Sub broadcast MQTT retained
Battery-constrained events Push (event-driven) MQTT QoS 0/1
Audit trail requirements Event Sourcing Kafka, EventStore
Unreliable networks Async with queue MQTT + local buffer
Real-time dashboards Pub-Sub + WebSocket MQTT over WS

187.10 Summary and Key Takeaways

187.10.1 Core Concepts

  1. Request-Response: Synchronous, confirmed delivery, good for commands and queries
  2. Publish-Subscribe: Decoupled, scalable, efficient for streaming and multi-consumer scenarios
  3. Push vs Pull: Push for efficiency and real-time; pull for control and on-demand access
  4. Event-Driven: Reactive, loosely coupled, enables complex event processing
  5. Sync vs Async: Sync for simplicity; async for resilience and efficiency

187.10.2 Design Principles

  • Match communication model to data flow requirements
  • Use async messaging for unreliable networks
  • Implement retained messages for critical state
  • Consider battery impact of polling vs push
  • Design for eventual consistency in distributed systems

187.11 What’s Next

After understanding communication models, explore: