25  HTTP and WebSocket over Wi-Fi

iot
wi-fi
implementation
Keywords

Wi-Fi HTTP WebSocket, IoT HTTP API review, IoT WebSocket review, Wi-Fi service path evidence, ESP32 HTTP WebSocket implementation

25.1 In 60 Seconds

This chapter reviews HTTP and WebSocket communication for Wi-Fi IoT devices. HTTP is a request-response pattern: a client asks for a resource or sends a command, and the device or service replies. WebSocket is a persistent bidirectional channel: either side can send messages after the connection is established.

The review question is not “Which protocol is faster?” in the abstract. The review question is: “Which communication pattern matches the device requirement, and what evidence proves that it works under normal, failed, and recovered conditions?” Use HTTP for bounded request-response workflows. Use WebSocket when the application genuinely needs a live bidirectional channel and can support connection state, keepalive, reconnect, and backpressure.

25.2 Learning Objectives

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

  • define an HTTP or WebSocket service contract for a Wi-Fi IoT device
  • separate network connection success from application communication success
  • choose HTTP, WebSocket, or another application pattern based on evidence rather than slogans
  • review request-response, streaming, command, and diagnostic paths
  • identify failure behavior for timeouts, retries, disconnects, stale data, and service overload
  • record security, observability, and support evidence for the selected communication pattern
Quick Check: Wi-Fi Application Traffic

25.3 Communication Review Route

Use Figure 25.1 to keep HTTP and WebSocket review decisions in order.

Wi-Fi HTTP and WebSocket communication review route covering requirement, service contract, HTTP path, WebSocket path, failure behavior, security boundary, and decision.
Figure 25.1: Wi-Fi HTTP and WebSocket communication review route

The route has seven checkpoints:

  • requirement: define the data, command, timing, and ownership need
  • contract: write the endpoint, message, state, and error behavior expected by clients
  • HTTP path: prove request, response, status, payload, timeout, and retry behavior
  • WebSocket path: prove connect, message, keepalive, disconnect, reconnect, and flow-control behavior
  • failure: record stale data, service outage, network loss, malformed message, and overload handling
  • boundary: check identity, authorization, transport protection, and exposure of device controls
  • decision: choose the pattern, state limits, and identify the next implementation review

25.4 Communication Evidence Record

Use Figure 25.2 to keep the evidence complete.

Wi-Fi HTTP and WebSocket evidence record connecting service contract, message shape, response evidence, stream evidence, failure evidence, security evidence, observability, and review decision.
Figure 25.2: Wi-Fi HTTP and WebSocket evidence record

A useful record contains:

  • service contract under review
  • device role and service owner
  • message shape and allowed operations
  • HTTP status or response behavior
  • WebSocket connection and message behavior
  • timeout, retry, reconnect, and backpressure behavior
  • security and authorization boundary
  • logs, metrics, user-visible state, and support action
  • decision, limits, owner, and retest trigger

25.5 Start With The Service Contract

The protocol choice should follow the service contract. A service contract describes what the device and client are allowed to exchange.

Record:

  • who initiates communication
  • what data or command is exchanged
  • how fresh the data must be
  • whether the exchange is occasional, bursty, continuous, or command driven
  • how the client knows the result was accepted
  • what the device does when the service is unreachable
  • what is logged for support
  • which operations require authorization

Without this contract, HTTP and WebSocket comparisons become guesswork.

25.6 HTTP Request-Response Path

HTTP fits workflows where each exchange has a clear request and a clear response.

Good HTTP candidates include:

  • reading the latest device state on demand
  • sending a configuration change and receiving an acceptance or rejection result
  • submitting telemetry at a bounded interval
  • requesting a diagnostic snapshot
  • checking whether an update is available
  • serving a local setup or support page during an intentional support window

Review evidence should include:

  • endpoint purpose and allowed method
  • request payload shape when a payload is required
  • response payload shape
  • status behavior for success, invalid request, unauthorized request, missing resource, busy service, and service failure
  • timeout behavior
  • retry policy and duplicate-command protection
  • size limits for request and response bodies
  • logs that identify the request without exposing secrets

Avoid treating HTTP as only a code sample. The review needs the contract, failure behavior, and support signal.

25.7 WebSocket Bidirectional Path

WebSocket fits workflows where a persistent channel is justified.

Good WebSocket candidates include:

  • live dashboards that need push updates while the page is open
  • operator tools that need near-live device state and command feedback
  • setup or commissioning tools that exchange a sequence of short messages
  • local control panels where the device and client both send events
  • diagnostic sessions that should not create a new HTTP request for every update

Review evidence should include:

  • when the connection is opened and closed
  • which side may send each message type
  • message schema and versioning
  • keepalive or health-check behavior
  • disconnect detection
  • reconnect behavior
  • stale data behavior
  • backpressure behavior when messages arrive faster than they can be processed
  • limit on concurrent clients or sessions
  • authorization and session expiry behavior

Do not choose WebSocket only because it sounds newer. A persistent channel adds state that must be observed and supported.

25.8 Protocol Selection

Choose HTTP when:

  • the client asks for data or sends a command occasionally
  • each request can stand alone
  • cache, proxy, logs, and ordinary web tooling help the workflow
  • failure can be reported through a clear response
  • the device should avoid maintaining a long-lived client session

Choose WebSocket when:

  • the client needs a live channel while it is actively monitoring or controlling the device
  • either side must send events without waiting for the next poll
  • a connected or disconnected state is meaningful to the user
  • the implementation can handle keepalive, reconnect, stale data, and backpressure
  • the service owner can support long-lived sessions

Choose another application pattern when:

  • the system is primarily publish-subscribe
  • devices must send telemetry to a broker that decouples producers from consumers
  • the device is deeply sleep oriented and cannot hold a live channel
  • the service boundary requires a gateway or message broker

The best answer often combines patterns. A device might use HTTP for setup and diagnostics, WebSocket for an active local control session, and a brokered messaging pattern for fleet telemetry.

25.9 Failure And Recovery

Every communication path needs failure evidence.

For HTTP, test:

  • timeout before connection
  • timeout while waiting for response
  • invalid payload
  • unauthorized request
  • service busy or unavailable
  • repeated retry after failure
  • duplicate command after retry

For WebSocket, test:

  • failed open
  • authentication failure
  • idle timeout
  • network loss
  • server restart
  • malformed message
  • slow client
  • reconnect after device restart

Record what the user, operator, or support workflow sees. A communication path that fails silently is not ready.

25.10 Security And Exposure

HTTP and WebSocket often expose device controls more directly than lower-level Wi-Fi join behavior. The review must include the boundary.

Check:

  • which endpoint or message can change device state
  • whether commands require identity and authorization
  • whether transport protection is used when secrets, credentials, or commands cross the network
  • whether setup endpoints are disabled outside setup or support mode
  • whether logs avoid exposing credentials, tokens, and personal data
  • whether cross-origin browser access is intentionally allowed or denied
  • whether local control remains bounded to the intended network or support workflow

This chapter does not replace a full security review, but it should catch obvious exposure mistakes before a device reaches a larger lab.

25.11 Observability And Support

The communication review should leave evidence that support teams can use.

Useful records include:

  • last successful request or message time
  • last failed request or message type
  • last disconnect or timeout reason
  • current service state
  • stale data indication
  • retry or reconnect state
  • user-visible status
  • log correlation value that does not expose secrets
  • owner for service-side and device-side issues

Without observability, a working demo can become an unfixable field issue.

25.12 Worked Review: Local Sensor API

Scenario:

  • A room sensor exposes local HTTP endpoints for latest readings and status.

Evidence route:

  • Requirement: read current state on demand and show whether data is fresh.
  • Contract: define read-only endpoints and response shape.
  • HTTP: record success, missing endpoint, invalid method, stale reading, timeout, and service unavailable behavior.
  • Boundary: allow read access only where the network design permits it.
  • Observability: log the last successful request and stale-data state.

Review decision:

  • HTTP is a good fit if each request stands alone and stale-data behavior is explicit.

25.13 Worked Review: Active Control Dashboard

Scenario:

  • A browser dashboard opens during a maintenance session and needs live state plus command feedback.

Evidence route:

  • Requirement: show live state while the dashboard is open and report command acceptance.
  • Contract: define state messages, command messages, errors, and close behavior.
  • WebSocket: record open, authorized session, messages, disconnect, reconnect, stale state, and slow-client behavior.
  • HTTP: keep setup or static page delivery separate from the live channel.
  • Boundary: close the channel when the session ends or authorization expires.

Review decision:

  • WebSocket is a candidate only if connection state, reconnect, stale data, and command authorization are all observable.

25.14 Worked Review: Device Telemetry Upload

Scenario:

  • A powered device sends periodic telemetry to a service and receives rare configuration changes.

Evidence route:

  • Requirement: telemetry accepted, configuration changes acknowledged, and failures visible.
  • Contract: define telemetry payload, acceptance response, retry behavior, and duplicate handling.
  • HTTP: test post success, service unavailable, retry, duplicate payload, and response processing.
  • Alternative: consider a brokered messaging pattern if many consumers need the same data or devices must be decoupled from dashboards.
  • Observability: record last accepted telemetry and last failed upload.

Review decision:

  • HTTP may be enough if upload timing is bounded and command needs are rare. WebSocket is unnecessary unless a live bidirectional session is part of the requirement.

25.15 Knowledge Check: Protocol Fit

25.16 Knowledge Check: HTTP Evidence

25.17 Match Evidence To Communication Area

25.18 Order The Communication Review

25.19 Common Mistakes

Choosing from slogans:

  • Problem: the decision is made from “HTTP is simple” or “WebSocket is real time” without a service contract.
  • Repair: write the contract first, then choose the communication pattern.

Treating Wi-Fi connection as application success:

  • Problem: the device joins Wi-Fi, but the endpoint or live channel was not tested.
  • Repair: record service-path evidence separately from Wi-Fi join evidence.

Ignoring duplicate commands:

  • Problem: an HTTP command is retried after a timeout and may apply twice.
  • Repair: define duplicate handling and verify the final device state.

Leaving WebSocket state invisible:

  • Problem: the channel disconnects or stalls, but the dashboard still appears current.
  • Repair: show stale state, disconnect state, reconnect state, and command acceptance clearly.

Exposing setup or control endpoints too broadly:

  • Problem: local endpoints remain available outside the intended setup, support, or control workflow.
  • Repair: bound setup mode, require authorization for state changes, and log access without secrets.

Overclaiming power or bandwidth:

  • Problem: a generic overhead comparison is used as proof for this device.
  • Repair: measure the actual traffic pattern, radio state, sleep behavior, and service lifecycle in the power review.

25.20 Final Checklist

Before accepting the communication implementation, confirm that the record includes:

  • service requirement and owner
  • protocol choice and reason
  • endpoint or message contract
  • normal success evidence
  • failure and retry evidence
  • stale-data behavior
  • disconnect and reconnect behavior where relevant
  • duplicate-command handling
  • security and authorization boundary
  • observable user or support state
  • limits of the review
  • decision, owner, and retest trigger

25.21 Request/Response Versus a Persistent Channel

Over Wi-Fi, an IoT device usually talks to a server two ways. HTTP is request/response: the device opens or reuses a connection, sends a request, gets a reply, and can let the exchange finish. It is simple to inspect and works well when each operation has a bounded result. WebSocket upgrades a single HTTP connection into a persistent, full-duplex channel so either side can send at any time. That is useful when the server must push commands, a dashboard needs live state, or a setup session exchanges several small messages while the user is present. CoAP vs MQTT: Communication Pattern Comparison, REQUEST-RESPONSE, CoAP, Sensor, CoAP Client, Gateway, CoAP Server, GET /temperature, 2.05 Content: 22.5°C

Both HTTP and WebSocket ride on TCP, which rides on the 802.11 link. That layering is why Wi-Fi behavior such as retries, airtime contention, roaming delay, and power-save timing shows up as application latency even though the application code never mentions radios. A “connected” Wi-Fi state proves association and IP reachability; it does not prove that an endpoint accepts a command, that a live channel is authorized, or that stale data is shown safely.

For review, start with the message pattern rather than the library name. Request/response needs endpoint, method, status, payload, timeout, retry, duplicate handling, and support logs. A stream/session needs open, authentication, message types, keepalive, disconnect detection, reconnect, stale-state display, backpressure, and close behavior. If the requirement is telemetry fan-out, queueing, or gateway translation, HTTP and WebSocket may only be part of the path. The release record should say which pattern is being accepted and what evidence would force the decision to change.

Pick by pattern: HTTP for bounded request/response; WebSocket for a justified live session. Then prove the Wi-Fi, TCP, application, security, and support states separately.

25.21.1 Overview Knowledge Check

25.22 Keep-Alive and the WebSocket Upgrade

Setting up a connection is expensive over Wi-Fi: a TCP three-way handshake plus, for HTTPS, a TLS handshake, with several round trips that can each be delayed by contention or link-layer retries. HTTP keep-alive (default in HTTP/1.1) reuses one TCP connection for many requests, so a device polling every few seconds pays the handshake once instead of every time. A reviewer should still check the idle timeout on both ends, because a gateway, browser, reverse proxy, or firmware stack may close the connection earlier than the application expects.

A WebSocket starts life as an HTTP request with Upgrade: websocket; the server answers 101 Switching Protocols, and from then on the same TCP connection carries lightweight WebSocket frames in both directions with no HTTP headers per message. That can cut overhead for frequent small updates, but the trade is state. The implementation now needs a session owner, authorization lifetime, ping or heartbeat policy, close codes, reconnect limits, stale-data marking, and a rule for messages that arrive faster than the device or browser can process them.

For HTTP commands, the practical hazard is not only the timeout; it is what happens when a client retries after the timeout. Use request IDs, idempotent operations where possible, or an explicit duplicate-command rule so the same actuator command does not apply twice. For WebSocket commands, use message IDs and acknowledgments so the dashboard can tell the difference between “sent”, “accepted”, “rejected”, and “connection lost before the server saw it”. In both patterns, logs should correlate the exchange without printing tokens, passwords, or personal data.

Worked example. A thermostat reports every 5 seconds and must receive setpoint changes promptly. With HTTP polling it opens or reuses a connection, sends headers, and can only learn of a setpoint change on its next poll, adding up to 5 seconds of latency plus repeated header bytes. Switching to WebSocket, it holds one upgraded connection: reports flow up as small frames and setpoint changes are pushed down quickly. The release evidence is not just lower latency; it is the observed keepalive, authorization expiry, reconnect path, stale-state display, command acknowledgment, and support log after an access point restart.

25.22.1 Practitioner Knowledge Check

25.23 How 802.11 Retries and Aggregation Shape TCP

TCP assumes lost packets may mean congestion and slows down when loss is visible end to end. Over the air, though, the 802.11 MAC acknowledges and retransmits every frame at the link layer, so a single fumbled frame is usually recovered by the radio before TCP ever notices. That prevents TCP from needlessly shrinking its congestion window after an ordinary RF glitch. The cost is variable delay: retries, backoff, and rate adaptation add jitter that surfaces as uneven HTTP response time or WebSocket message latency.

Throughput over Wi-Fi also depends on frame aggregation. Since 802.11n, the MAC can bundle many subframes into one A-MPDU covered by a single block acknowledgment, amortizing fixed per-frame overhead such as preamble, backoff, interframe spacing, and ACK time across a large batch. This is what lets TCP reach high throughput on Wi-Fi, but it favors steady bulk flows. A device sending one tiny JSON frame at a time gains little from aggregation and still pays contention and wakeup costs.

The application protocol changes how those radio mechanics are felt. HTTP polling produces bursts: request headers, optional body, response headers, body, then quiet. WebSocket produces a long session with smaller frames, so it can reduce repeated headers but may keep the radio or access point state active for longer. TLS record sizing, Nagle behavior, delayed ACKs, proxy buffering, and firmware socket buffers can all turn a “small message” design into delayed delivery. A good test measures not only throughput but message age, jitter, reconnect time, and the number of bytes sent while the device is idle.

Worked example. A camera streaming over TCP gets excellent throughput because its steady byte stream fills large A-MPDUs recovered by block-ack. A sensor sending a 20-byte reading every second gets no aggregation benefit. If it also holds a WebSocket open under Wi-Fi power save, each server push may wait for the device’s next scheduled wake. The remedy is application-aware: batch small messages where the freshness budget allows it, tune keepalive and power-save timing to the required push latency, and record the resulting stale-data and reconnect behavior as release evidence.

25.23.1 Under-the-Hood Knowledge Check

25.24 Summary

HTTP and WebSocket are application communication patterns, not just library choices. HTTP works well for bounded request-response workflows. WebSocket works well for justified live bidirectional sessions, but only when state, disconnects, reconnects, stale data, backpressure, and authorization are reviewed.

The right choice comes from the service contract and evidence. Keep Wi-Fi join, application reachability, normal behavior, failure behavior, security boundary, and support visibility separate in the record.

25.25 Key Takeaway

Wi-Fi HTTP & WebSocket should leave deployment evidence for association, throughput, latency, security setup, power behavior, failure recovery, and tested device constraints.

25.26 What’s Next

Use Wi-Fi Implementation: ESP32 Basics if the station join and usable-service path still need review.

Use Wi-Fi Power Optimization when communication behavior must be tied to the device power cycle.

Use Wi-Fi Security and Provisioning when authorization, setup mode, credentials, or local control exposure are the main risk.

Use Wi-Fi Comprehensive Lab when HTTP or WebSocket behavior is ready for a broader implementation lab.

Use Wi-Fi for IoT: Implementations to compare this chapter with other implementation patterns.