Chapters

15 Realtime Protocols: Transport Selection

protocols
realtime
rtp
sip
webrtc
websocket
iot
app-protocols
protocol
debate
mqtt

Start with the story: Realtime protocols matter when “check again later” is not good enough. A camera view, door-station call, live dashboard, or remote control path needs the right split between media transport, signaling, browser streams, and evidence that the live path is healthy.

15.1 Start With the Decision

A live session may begin on HTTP and then leave its request-response pattern. The team must prove which transport owns each hop.

15.2 Route Overview

This is part 3 of 3. Review Realtime Protocols: WebRTC and WebSocket Operations for the preceding evidence.

15.3 Learning Objectives

  • Trace upgrade, signalling, and media paths around HTTP.
  • Select MQTT, CoAP, WebSocket, or WebRTC from evidence.

15.4 Chapter Roadmap

  • Deep Dive: How “Live” Rides On (and Escapes) HTTP
  • Debate: MQTT vs. CoAP Protocol Selection
  • Summary
  • Key Takeaway
  • External References
  • What’s Next

15.5 Deep Dive: How “Live” Rides On (and Escapes) HTTP

The roles above describe what each real-time protocol is for. This layered walkthrough shows the mechanism: how a browser or gateway turns an ordinary HTTP request into a live channel with a single 101 Switching Protocols response, and where WebRTC leaves HTTP behind entirely to carry encrypted media.

Plain HTTP is one-shot: a client asks, a server answers, and the exchange ends. Live IoT views need a channel that stays open so state or media can arrive when it changes. Pick the mechanism by direction and payload, not by whether the feature feels “live.”

MechanismWire modelIoT fit
Server-Sent Events (SSE)Ordinary HTTP response kept open as text/event-stream; server-to-client only; reconnects with Last-Event-IDBrowser alert feeds and status strips that never send commands on the same channel
WebSocketStarts as HTTP GET, upgrades with 101 Switching Protocols, then carries framed full-duplex traffic over one TCP connectionInteractive control and live state where the browser both watches and sends commands
WebRTCUses signaling to set up peer media, then carries encrypted SRTP media over UDP with RTCP feedbackLive camera/audio between capable endpoints; too heavy for a simple sensor reading

For an IoT review, record the direction, payload type, and failure behavior before naming the protocol. A dashboard status feed can stay on SSE and reuse ordinary HTTP infrastructure. A door-lock console that sends commands while receiving state needs WebSocket and explicit authorization for each command frame. A camera call needs WebRTC because codecs, media timing, NAT traversal, and congestion control are the real requirements.

A WebSocket connection is born as a normal HTTP/1.1 request. The client asks the server to switch protocols on the existing TCP connection:

GET /telemetry HTTP/1.1
Host: gw.example
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13

If the server agrees, it does not return 200 OK. It returns 101 Switching Protocols, meaning “I am changing the protocol on this connection as requested”:

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=

Sec-WebSocket-Accept is not random. The server computes base64(SHA-1(Sec-WebSocket-Key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11")), using the fixed GUID defined by RFC 6455. The client checks this value so a cache or proxy cannot fake the upgrade by echoing headers. After that point, the TCP connection no longer carries HTTP; both ends exchange WebSocket frames, with a small header plus payload, in either direction at any time.

The security review still treats the upgraded channel as application traffic. Use wss:// so TLS protects both the handshake and frames. Validate Origin for browser clients. Authenticate before accepting control messages. Close idle or unauthenticated sockets before they become a fleet-wide resource drain, and rate-limit reconnects because persistent channels often fail together after server restarts.

WebRTC is where real-time media stops looking like HTTP. It splits into a signaling plane that sets the call up and a media plane that carries the encrypted stream. WebRTC deliberately does not standardize signaling; you can carry SDP offer/answer over WebSocket, SIP, or another application channel. Media then flows directly or through a relay.

StepMechanismWhat to verify
SignalSDP offer/answer over WebSocket, SIP, or another signaling pathCodecs, keys, and candidate addresses are exchanged with authentication
ConnectICE with STUN and TURNDirect and relayed NAT paths are tested, logged, and authorized
SecureDTLS key exchange for DTLS-SRTPMedia encryption is mandatory and keys are fresh for the session
StreamSRTP plus RTCP, optional SCTP data channelMedia quality, loss, jitter, and fallback behavior are observable
Peer B (browser)Signaling (WebSocket/SIP)Peer A (door station)Peer B (browser)Signaling (WebSocket/SIP)Peer A (door station)Signaling done, media goes peer-to-peerSDP offerSDP offerSDP answerSDP answerICE checks (STUN/TURN)DTLS handshake (derive SRTP keys)SRTP encrypted media + RTCP

This is the right stack for a door station live view, but it is a large one: ICE, STUN/TURN, DTLS, SRTP, and congestion control all run on the endpoint. A coin-cell sensor sending one JSON reading gains nothing from it and cannot afford it. Reserve WebRTC for genuine media between capable endpoints, and keep the signaling channel separate from the media path in both the design and the security review.

For every realtime path, keep three records together: the signaling protocol, the media or event transport, and the fallback path. That prevents a “live” feature from hiding unauthenticated commands, overloaded reconnect storms, or unreviewed TURN relay boundaries.

15.6 Debate: MQTT vs. CoAP Protocol Selection

15.6.1 MQTT vs CoAP

Debate One Failure, Not Two Brand Names

Picture a battery sensor that sends routine readings but must also accept a rare setting change. The best exchange pattern depends on who starts each action, what state is kept, and what a retry can repeat.

CoAP means a compact request-and-response method. MQTT means a topic-based publish-and-listen method. Quality of service means a selected delivery level; QoS is its short name. UDP means independent datagrams with no built-in delivery promise.

Test a lost reading, a lost reply, a repeated command, a sleeping receiver, and a restart. Keep identity, time, unit, and final application state in the comparison. A small byte count or live connection does not prove the system choice.

This runway does not name a universal winner. The debate below compares traffic shape, delivery evidence, stored state, energy, security, and operational ownership for a stated case.

Discussion Prompt

Scenario: You’re designing a smart agriculture system with 500 soil moisture sensors across a 100-hectare farm. Sensors send readings every 15 minutes. Cellular connectivity is available but expensive.

Debate: Should you use MQTT or CoAP?

Team A (MQTT): Argue for persistent connections, QoS guarantees Team B (CoAP): Argue for lower overhead, UDP efficiency

Consider:

  • Power consumption per message
  • Handling intermittent connectivity
  • Cost per MB of cellular data
  • Message delivery guarantees needed
Putting Numbers to It

This debate gets clearer when you quantify monthly traffic for each protocol strategy.

Dmonth=Nmsg/day×Smsg×3010242 MBD_{month}=\frac{N_{msg/day}\times S_{msg}\times 30}{1024^2}\text{ MB}

Worked example: 500 sensors sending every 15 minutes:

Nmsg/day=500×96=48,000N_{msg/day}=500\times 96=48{,}000

Assume:

  • CoAP message size Smsg=20S_{msg}=20 bytes (small UDP payload pattern)
  • MQTT publish size =40=40 bytes plus keepalive traffic (30-byte heartbeat every 60 s)
DCoAP=48,000×20×301024227.5 MB/monthDMQTT,pub=48,000×40×301024254.9 MB/monthDMQTT,keepalive=500×1440×30×3010242618.0 MB/month\begin{aligned} D_{CoAP} &= \frac{48{,}000\times 20\times 30}{1024^2} \approx 27.5\text{ MB/month}\\ D_{MQTT,pub} &= \frac{48{,}000\times 40\times 30}{1024^2} \approx 54.9\text{ MB/month}\\ D_{MQTT,keepalive} &= \frac{500\times 1440\times 30\times 30}{1024^2} \approx 618.0\text{ MB/month} \end{aligned}

Total MQTT traffic is about 672.9672.9 MB/month. At 0.100.10/MB cellular pricing, that is roughly $67.29\text{\textdollar}67.29 vs $2.75\text{\textdollar}2.75 for CoAP-style telemetry, which is a meaningful design trade-off.

15.6.1.1 MQTT vs CoAP Data Cost

Facilitate MQTT vs CoAP Debate

Setup: Study group of 4 students, each assigned a role.

[0-5 min] Context Setting (Facilitator)

Read these points as one connected sequence: start with Scenario: Smart agriculture with 500 soil sensors; then Constraint: Cellular data costs $0.10/MB; then Average message: 20 bytes; then Frequency: Every 15 minutes; and finish with Reliability requirement: 95% delivery.

  • Scenario: Smart agriculture with 500 soil sensors
  • Constraint: Cellular data costs $0.10/MB
  • Average message: 20 bytes
  • Frequency: Every 15 minutes
  • Reliability requirement: 95% delivery

[5-15 min] Position Arguments (5 min each)

Team A (MQTT): Maria presents Read these points as one connected sequence: start with QoS 1 ensures 95% delivery with ACKs; then Persistent connection allows instant alerts; then Broker-based fan-out and retained state simplify downstream integrations; and finish with Math: Using the same assumptions from the calculator above, MQTT publish traffic is about 54.9 MB/month, and a 60-second keepalive adds roughly 618.0 MB/month more. That is much more expensive on cellular, but Maria argues the extra cost may be worth it when real-time alerts and operational simplicity matter.

  • QoS 1 ensures 95% delivery with ACKs
  • Persistent connection allows instant alerts
  • Broker-based fan-out and retained state simplify downstream integrations
  • Math: Using the same assumptions from the calculator above, MQTT publish traffic is about 54.9 MB/month, and a 60-second keepalive adds roughly 618.0 MB/month more. That is much more expensive on cellular, but Maria argues the extra cost may be worth it when real-time alerts and operational simplicity matter.

Team B (CoAP): Jason presents Read these points as one connected sequence: start with Confirmable messages provide reliability; then No persistent connection saves battery; then Smaller request/response exchanges keep routine telemetry lightweight; then Math: 500 sensors × 96 msg/day × 20 bytes × 30 days is about 27.5 MB/month, or $2.75/month at $0.10/MB; and finish with BUT: Sleep mode between messages saves 200mAh/day per sensor = 6 months longer battery life.

  • Confirmable messages provide reliability
  • No persistent connection saves battery
  • Smaller request/response exchanges keep routine telemetry lightweight
  • Math: 500 sensors × 96 msg/day × 20 bytes × 30 days is about 27.5 MB/month, or $2.75/month at $0.10/MB
  • BUT: Sleep mode between messages saves 200mAh/day per sensor = 6 months longer battery life

[15-20 min] Cross-Examination (Facilitator moderates)

Q: “Maria, what happens when cellular drops during 15-min sleep?” A: “MQTT broker stores messages. Device resends on reconnect. Data is never lost.”

Q: “Jason, how do you handle real-time alerts with CoAP’s request-response model?” A: “CoAP Observe extension allows push notifications. Gateway polls sensors every 5 min for urgent alerts.”

[20-25 min] Role Reversal

Read these points as one connected sequence: start with Maria argues FOR CoAP battery savings; then Jason argues FOR MQTT’s simplicity; and finish with Learning: Students see both sides’ merits.

  • Maria argues FOR CoAP battery savings
  • Jason argues FOR MQTT’s simplicity
  • Learning: Students see both sides’ merits

[25-30 min] Facilitator Synthesis “No right answer. Trade-offs:” Read these points as one connected sequence: start with MQTT: Better for real-time alerts, higher data cost; then CoAP: Better for battery life, more complex implementation; and finish with Real projects often use BOTH: CoAP for sensors, MQTT for gateway-to-cloud.

  • MQTT: Better for real-time alerts, higher data cost
  • CoAP: Better for battery life, more complex implementation
  • Real projects often use BOTH: CoAP for sensors, MQTT for gateway-to-cloud

Student Feedback: “Switching sides forced me to see why someone would choose the other protocol. Now I understand it’s about project constraints, not ‘better’ vs ‘worse’.”

Time Breakdown Success: 5 min context + 10 min arguments + 5 min questions + 5 min role-switch + 5 min synthesis = exactly 30 min

15.7 Summary

Realtime application protocols are useful when IoT systems need live media, current state, or interactive operation. RTP carries timed media and RTCP reports quality. SIP sets up sessions. SRTP protects media. RTSP controls media delivery. WebRTC supports secure browser media paths. WebSocket supports persistent browser application channels. A good design separates protocol roles, sets timing and quality expectations, protects signaling and media, and keeps evidence that the path works under delay, loss, fallback, and disconnect conditions.

15.8 Key Takeaway

Realtime protocol decisions should start from latency, directionality, fan-out, ordering, and recovery needs, then prove that the chosen WebSocket, MQTT, CoAP observe, or streaming pattern can be operated securely.

15.9 External References

Read these points as one connected sequence: start with RFC 3550: RTP: Real-time Transport Protocol and RTP Control Protocol; then RFC 3261: SIP: Session Initiation Protocol for establishing, modifying, and terminating sessions; then RFC 3711: SRTP: Secure Real-time Transport Protocol; then RFC 7826: RTSP 2.0: Real-Time Streaming Protocol for setup and control of media delivery; then RFC 6455: WebSocket: WebSocket protocol for full-duplex application communication; then W3C WebRTC: Browser API for realtime communication; and finish with RFC 8445: ICE: Interactive Connectivity Establishment for NAT traversal.

  • RFC 3550: RTP: Real-time Transport Protocol and RTP Control Protocol.
  • RFC 3261: SIP: Session Initiation Protocol for establishing, modifying, and terminating sessions.
  • RFC 3711: SRTP: Secure Real-time Transport Protocol.
  • RFC 7826: RTSP 2.0: Real-Time Streaming Protocol for setup and control of media delivery.
  • RFC 6455: WebSocket: WebSocket protocol for full-duplex application communication.
  • W3C WebRTC: Browser API for realtime communication.
  • RFC 8445: ICE: Interactive Connectivity Establishment for NAT traversal.

15.10 What’s Next

Read these points as one connected sequence: start with Application Protocols Worked Examples: Apply protocol role separation to gateway and media workflows; then Application Protocols Introduction: Review the broader application-protocol route; then Application Protocols Overview: Revisit the protocol-selection lens; then Transport Fundamentals: Review TCP, UDP, latency, jitter, and loss foundations; and finish with IoT Security Fundamentals: Review security thinking for connected device sessions.

15.11 Continue Your Route

This final part closes the route from Deep Dive: How “Live” Rides On (and Escapes) HTTP through What’s Next. Return to Realtime Protocols: WebRTC and WebSocket Operations or continue from the app-protocols module index.