Chapters

15 Realtime Protocols: Transport Selection

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

Start with the story: A realtime protocol is a set of rules for messages that must arrive soon enough for the job. A camera or door-station call needs media transport for sound and video plus signaling to set up the session. A live dashboard or remote-control path may instead use browser streams of messages, such as SSE or WebSocket. The team also needs evidence that each live path is healthy.

15.1 Start With the Decision

This section: Start With the Decision — A live session may begin on HTTP and then leave its request-response pattern.

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 section: Route Overview — This is part 3 of 3.

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

15.3 Learning Objectives

This section: Learning Objectives

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

15.4 Chapter Roadmap

This section: 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

This section: Deep Dive: How “Live” Rides On (and Escapes) HTTP — The roles above describe what each real-time protocol is for.

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.

Ordinary short HTTP exchanges finish after a response, but HTTP can also keep a response stream open, as SSE does. Live IoT views need an update path 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)HTTP response kept open as text/event-stream; server-to-client only; a browser can send Last-Event-ID after reconnect when IDs were suppliedBrowser alert feeds and status strips that never send commands on the same channel
WebSocketHTTP/1.1 GET + 101 Switching Protocols (HTTP/2/3: extended CONNECT), then framed full-duplex messages over one 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.

In the HTTP/1.1 form of the WebSocket handshake, the client asks the server to switch protocols on the existing TCP connection (RFC 6455). HTTP/2 and HTTP/3 can instead bootstrap WebSocket with extended CONNECT (RFC 8441 and RFC 9220):

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 that the peer performed the WebSocket handshake rather than merely echoing the key; this SHA-1 value is not authentication or encryption. After the HTTP/1.1 upgrade, that connection carries WebSocket frames rather than further HTTP messages, with a small header plus payload in either direction.

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

This section: 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 MiBD_{month}=\frac{N_{msg/day}\times S_{msg}\times 30}{1024^2}\text{ MiB}

Worked example: 500 sensors sending every 15 minutes:

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

Assume illustrative application-byte budgets, excluding lower-layer overhead and retransmissions:

  • CoAP message size Smsg=20S_{msg}=20 bytes
  • MQTT publish size =40=40 bytes plus a 30-byte allowance for each keepalive exchange every 60 s while the connection is idle
DCoAP=48,000×20×3010242≈27.5 MiB/monthDMQTT,pub=48,000×40×3010242≈54.9 MiB/monthDMQTT,keepalive=500×1440×30×3010242≈618.0 MiB/month\begin{aligned} D_{CoAP} &= \frac{48{,}000\times 20\times 30}{1024^2} \approx 27.5\text{ MiB/month}\\ D_{MQTT,pub} &= \frac{48{,}000\times 40\times 30}{1024^2} \approx 54.9\text{ MiB/month}\\ D_{MQTT,keepalive} &= \frac{500\times 1440\times 30\times 30}{1024^2} \approx 618.0\text{ MiB/month} \end{aligned}

Total MQTT traffic in this deliberately keepalive-heavy model is about 672.9672.9 MiB/month. At an illustrative $0.10/MiB, that is about $67.29 versus $2.75 for the CoAP model. Actual billed traffic includes lower-layer framing, security, and carrier policy.

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)

Use the same sensor count, message size, rate, price, and target in both cases.

  • 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 The MQTT case combines delivery behavior and broker fan-out with the traffic estimate; test whether the full path reaches the stated target.

  • QoS 1 supports at-least-once transfer between client and broker; test whether the full path meets the 95% target
  • 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 MiB/month, and a 60-second keepalive adds roughly 618.0 MiB/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 The CoAP case trades a persistent connection for confirmable exchanges; compare its byte estimate with sleep and retry behavior.

  • 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 MiB/month, or $2.75/month at the assumed $0.10/MiB
  • BUT: with no connection to keep alive, the radio can sleep completely between reports, which can extend battery life substantially (measure to quantify).

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

Q: “Maria, what happens when cellular drops during 15-min sleep?” A: “A configured persistent MQTT session can queue eligible messages while a client is away. The device must retry unconfirmed sends and make duplicates safe; no configuration makes data loss impossible.”

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

One side values battery life; the other values the broker. Compare the cost of each choice.

  • 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:” Compare alert delivery with battery cost, then consider a split path from CoAP sensors to an MQTT cloud gateway.

  • 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

This section: Summary — Realtime application protocols are useful when IoT systems need live media, current state, or interactive operation.

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

This section: 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.

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

This section: External References — RTP carries media, SIP sets up sessions, and SRTP protects media.

RTP carries media, SIP sets up sessions, and SRTP protects media. Read each spec for its role.

  • 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

This section: What’s Next — Use the worked cases to test each role.

Use the worked cases to test each role. Then return to the wider protocol guide.

The previous workflow establishes realtime roles; the next chapter applies them to a protocol selection case.

15.11 Continue Your Route

This section: Continue Your Route — This is the last part of this chapter.

This is the last part of this chapter. Return to Realtime Protocols: WebRTC and WebSocket Operations or continue from the Application Protocols Module Guide.

Find help

3 reviewed answers.

Where should I start in a module?

Open the module page from the sidebar to see its chapters in order. Use the module map to return to a topic you need.

Modules and paths

Reviewed

What can I try when a project does not work?

Check the symptom, then work through the diagnostic steps. Keep the error message and the smallest example that reproduces it.

When you are stuck

Reviewed

How do interactive examples work?

Use the interactive guide to check how examples and simulations work before changing your project.

Interactive examples guide

Reviewed