39  Communication Models for IoT

In 60 Seconds

Three communication patterns shape IoT systems: request-response (synchronous, for commands), publish-subscribe (decoupled, for streaming telemetry), and event-driven (reactive, for battery-constrained devices). Most production systems use a hybrid – pub/sub for sensor data with request-response for configuration and commands.

The Sensor Squad had exciting news to share, but they couldn’t agree on HOW to share it!

Request-Response (Sammy’s way): Sammy the Sensor waited for someone to ask, “Hey Sammy, what’s the temperature?” Then Sammy answered. But if nobody asked, nobody knew! And Sammy had to wait around for questions all day.

Publish-Subscribe (Lila the LED’s way): Lila posted updates on a bulletin board topic called “Room Temperature.” Anyone interested just subscribed to that topic and got updates automatically. Max the Microcontroller, the cloud dashboard, and even the heating system all subscribed. Lila didn’t need to know who was reading – she just posted!

Event-Driven (Bella the Battery’s way): Bella was tired and didn’t want to keep talking. “Just wake me up if something IMPORTANT happens!” she said. So Max only buzzed Bella when the temperature crossed a dangerous threshold. Bella slept 99% of the time and her battery lasted for years!

The lesson: There’s no single best way to communicate. Sammy’s way is great when you need a guaranteed answer. Lila’s way is perfect when many listeners need the same data. And Bella’s way saves the most energy when events are rare!

39.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

39.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
Key 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.

39.3 Request-Response Pattern

Time: ~15 min | Level: 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.

39.3.1 How Request-Response Works

Sequence diagram showing request-response pattern where client sends request to server and blocks until receiving a response

39.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

39.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)

39.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

39.4 Publish-Subscribe Pattern

Time: ~20 min | Level: 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.

39.4.1 How Pub/Sub Works

Publish-subscribe architecture with broker mediating between publishers and subscribers via topic-based routing

39.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

39.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

39.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

39.5 Push vs Pull Communication

Time: ~15 min | Level: Foundational

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

39.5.1 Push Model

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

Push communication model where data source initiates transmission to consumer when new data is available

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

39.5.2 Pull Model

In pull communication, the consumer requests data when needed:

Pull communication model where consumer requests data from source on demand at regular intervals

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)

39.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

39.5.4 Interactive: Push vs Pull Battery Life Calculator

39.6 Event-Driven Architecture

Time: ~20 min | Level: 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.

39.6.1 Event-Driven Components

Event-driven architecture showing producers emitting events through event channel to consumer processors

39.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”

39.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

39.7 Synchronous vs Asynchronous Communication

Time: ~15 min | Level: Intermediate

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

39.7.1 Synchronous Communication

Synchronous communication sequence where sender blocks and waits for receiver to complete processing before continuing

Characteristics:

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

39.7.2 Asynchronous Communication

Asynchronous communication where sender continues immediately after sending while message is processed in background

Characteristics:

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

39.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

39.8 Message Patterns for IoT

Time: ~20 min | Level: Advanced

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

39.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

39.8.2 One-to-Many (Broadcast/Multicast)

Single message delivered to multiple recipients:

One-to-many broadcast pattern where single source sends command or update to multiple recipient devices simultaneously

Use cases: Firmware updates, configuration broadcasts, time synchronization

39.8.3 Many-to-One (Aggregation)

Multiple sources sending to single destination:

Many-to-one aggregation pattern where multiple sensors send data to a single collection point or gateway

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

39.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"}

39.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

39.9 Communication Model Selection Guide

Time: ~10 min | Level: Intermediate

Use this decision framework to select appropriate communication models:

Decision flowchart for selecting IoT communication model based on requirements like latency, battery, and consumer count

39.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

Key Concepts

  • Request-Response: A synchronous communication model where a client sends a request and blocks waiting for a server response, suitable for command-and-control IoT scenarios but inefficient for high-frequency sensor data
  • Publish-Subscribe (Pub/Sub): An asynchronous communication pattern where publishers send messages to topics without knowing subscribers, and subscribers receive messages without knowing publishers — the dominant pattern for IoT telemetry
  • Push-Pull: A message distribution model where a producer pushes tasks to a queue and multiple workers pull and process them in parallel, enabling load-balanced IoT data processing without coordination
  • Exclusive Pair: A persistent bidirectional connection between exactly two endpoints (client-server), providing low-overhead communication for WebSocket-based IoT dashboards and device management
  • MQTT Broker: A message routing server that receives published messages and distributes them to all subscribed clients based on topic matching, decoupling IoT devices from data consumers
  • QoS (Quality of Service): MQTT’s delivery guarantee levels: QoS 0 (fire-and-forget), QoS 1 (at least once with acknowledgment), QoS 2 (exactly once with 4-way handshake) — higher QoS uses more bandwidth and power
  • WebSocket: A full-duplex TCP-based protocol that enables persistent bidirectional communication between IoT devices and web applications over standard HTTP ports, bypassing firewall restrictions

Common Pitfalls

Polling a sensor every second via HTTP GET requests creates unnecessary overhead — connection setup, headers, waiting for server response. Use MQTT pub/sub for telemetry; reserve HTTP request-response for configuration changes and command acknowledgments.

Defaulting to QoS 2 (exactly once delivery) for every sensor reading adds 4-message handshake overhead and doubles battery consumption on constrained devices. Use QoS 0 for non-critical telemetry, QoS 1 for alarms, and QoS 2 only for billing or command execution that must not duplicate.

IoT clients that assume their MQTT connection is always alive. Mobile networks drop connections, broker instances restart, and NAT timeouts close idle connections. Implement reconnect logic with exponential backoff and Last Will and Testament (LWT) for disconnect detection.

Using HTTP for some device interactions, MQTT for others, and WebSockets for dashboards without a defined integration layer. Each protocol requires different client libraries, port openings, and authentication. Define a single primary protocol per device capability and use protocol translation at the gateway.

39.10 Summary and Key Takeaways

39.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

39.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

39.11 Worked Example: Communication Model Selection for Smart Factory

Worked Example: Choosing Communication Patterns for a 500-Machine Factory

Scenario: An automotive parts factory has 500 CNC machines, 50 quality inspection stations, and 20 AGVs (automated guided vehicles). The system must handle three data flows: (1) machine telemetry every 5 seconds, (2) quality alerts when a defect is detected, and (3) AGV coordination commands.

Step 1: Characterize Each Data Flow

Data Flow Volume Latency Requirement Reliability Direction
Machine telemetry 500 machines x 12 readings/min = 6,000 msg/min Seconds (OK to batch) Tolerates occasional loss One-to-many (machines to dashboards, analytics, historian)
Quality alerts ~50/day (rare events) <500 ms (stop the line) Must not lose any One-to-many (inspection station to line controller, supervisor phone, quality database)
AGV commands ~200/min during peak <50 ms (collision avoidance) Must be confirmed One-to-one (controller to specific AGV)

Step 2: Match Communication Model to Each Flow

Data Flow Best Model Why Not the Others?
Machine telemetry Publish-subscribe (MQTT QoS 0) Request-response would require 6,000 polls/min. Event-driven would miss gradual trends. Pub/sub lets multiple consumers (dashboard, historian, ML pipeline) subscribe independently.
Quality alerts Event-driven (MQTT QoS 1 with retained) Pub/sub alone risks alert being missed if subscriber is temporarily disconnected. Event-driven pattern with QoS 1 guarantees delivery. Retained message ensures late-joining supervisor app sees last alert status.
AGV commands Request-response (CoAP with confirmable messages) AGV must acknowledge each command (confirmed delivery). Pub/sub would add broker latency (5-15 ms overhead). Direct request-response over CoAP achieves <20 ms round-trip on local network.

Step 3: Bandwidth and Infrastructure Sizing

Parameter Pub/Sub (Telemetry) Event-Driven (Alerts) Request-Response (AGV)
Messages/day 8,640,000 ~50 ~288,000
Avg message size 128 bytes 512 bytes 64 bytes
Daily bandwidth 1.06 GB 25 KB 17.6 MB
MQTT broker sizing 2-core server, 4 GB RAM (handles 10K msg/sec) Same broker (negligible load) Separate CoAP server (latency isolation)

Result: A hybrid architecture using pub/sub for 99.7% of traffic (telemetry), event-driven for 0.001% (quality alerts), and request-response for 0.3% (AGV commands). The MQTT broker handles both telemetry and alerts on a single $200/month server. AGV commands use a separate CoAP endpoint to guarantee sub-50ms latency without being affected by telemetry traffic spikes. Total messaging infrastructure cost: $350/month for a 500-machine factory.

Key insight: No single communication model fits all IoT data flows. The selection depends on latency requirements, reliability needs, and the number of consumers – not on which protocol is “newest” or “most popular.”

39.12 Knowledge Check

39.13 What’s Next

Direction Chapter Description
Next MQTT Fundamentals Deep dive into the most popular IoT pub-sub protocol
Next CoAP Protocol Request-response optimised for constrained devices
Related Stream Processing Message queuing and real-time data processing for IoT
Related Communication and Protocol Bridging Translating between different protocols at gateways