Chapters

6 Modern HTTP: Implementation and Deployment

app-protocols
http
modern

Inspect Figure 6.1 to find the layer where each HTTP version changes how concurrent work reacts to delay or packet loss.

Comparison of HTTP/1.1, HTTP/2, and HTTP/3 protocol stacks showing changes in framing, security/transport, and loss boundaries.
Figure 6.1: HTTP/1.1, HTTP/2, and HTTP/3 preserve HTTP application semantics while changing framing, transport, and loss boundaries underneath.

Begin at the common HTTP semantics in Figure 6.1, then move downward to framing. HTTP/1.1 uses textual messages, whereas HTTP/2 shares one TCP connection among multiplexed streams. Both still inherit TCP’s ordered byte delivery, so a lost segment can hold later bytes and delay unrelated HTTP/2 streams. The HTTP/3 column replaces that transport with QUIC over UDP and integrates TLS 1.3. Independent QUIC streams can keep moving when another stream loses data. That mechanism is the reason mobile loss and roaming may justify HTTP/3 despite its larger implementation footprint.

6.1 Start With the Situation

This section: Start With the Situation — The team has selected a protocol from measured constraints, but the choice is only useful when libraries, memory, server settings, staged rollout, and recovery checks implement it faithfully.

The team has selected a protocol from measured constraints, but the choice is only useful when libraries, memory, server settings, staged rollout, and recovery checks implement it faithfully.

6.2 Overview

This section: Overview — This route turns a protocol selection into implementation settings, comparison evidence, deployment stages, and pitfall checks.

This route turns a protocol selection into implementation settings, comparison evidence, deployment stages, and pitfall checks.

This is part 2 of 2. Review Modern HTTP: HTTP/2, HTTP/3, and Selection when you need the first route.

6.3 Learning Objectives

This section: Learning Objectives

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

  • configure modern HTTP connection and gateway settings
  • validate library, memory, and server support for the selected protocol
  • plan a staged deployment with explicit trade-offs and recovery checks

6.4 Chapter Roadmap

This section: Chapter Roadmap — Follow the original sections below in order.

Follow the original sections below in order. They begin at the reviewed split boundary and keep every worked example, figure, check, and supporting banner with the section that owns it.

6.5 Implementation Considerations

This section: Implementation Considerations

6.5.1 Library Support (as of 2026)

PlatformHTTP/2HTTP/3Notes
ESP32 (ESP-IDF)Partial (nghttp2)LimitedMemory-constrained
Linux/Raspberry PiFull (libcurl, nghttp2)Full (quiche, ngtcp2)Recommended platform
Azure IoT SDKYesPreviewCloud-native support
AWS IoTYes (MQTT over WebSocket/HTTP/2)RoadmapPrefer MQTT
Nordic nRF9160LimitedNoFocus on LwM2M/CoAP

6.5.2 Memory Requirements

These are typical client footprints, not protocol minima; measure the secured library and buffers on the target device. RFC 9113 starts the HPACK dynamic table at 4,096 bytes and permits negotiated limits.

HTTP/1.1 minimal: ~8 KB RAM (no TLS)
HTTP/2: typically ~32 KB+ (TLS, HPACK, stream state)

HTTP/3: typically ~64 KB+ (QUIC + crypto state)
- <32 KB: CoAP or MQTT
- 32–128 KB: HTTP/2 for gateways
- >128 KB: HTTP/3 where mobile/lossy links justify it

6.5.3 Server Configuration

# nginx HTTP/2 config for IoT backend
http2_max_concurrent_streams 128;  # Many IoT clients
http2_recv_buffer_size 256k;       # Handle burst uploads
keepalive_timeout 3600s;           # Long-lived IoT connections
ssl_protocols TLSv1.3;             # Require TLS 1.3 for IoT security

# QUIC/HTTP/3 (nginx 1.25+)
listen 443 quic reuseport;
http3 on;
quic_retry on;                     # Mitigate amplification attacks

6.5.4 Real-World Case Study: Fleet Tracking System

The following diagram illustrates a real-world fleet tracking architecture using HTTP/3 for mobile assets:

Key Benefits Demonstrated:

Read these points as one connected sequence: start with Connection Migration: Trucks seamlessly switch between cell towers without dropping connection; then 0-RTT Resumption: Vehicles waking from sleep send GPS data immediately; and finish with Independent Streams: Real-time telemetry and firmware updates don’t interfere with each other.

  • Connection Migration: Trucks seamlessly switch between cell towers without dropping connection
  • 0-RTT Resumption: Vehicles waking from sleep send GPS data immediately
  • Independent Streams: Real-time telemetry and firmware updates don’t interfere with each other

6.5.5 Python HTTP/2 Gateway Example

Read the example in two passes. The long-lived httpx.Client enables HTTP/2 and caps keep-alive and total connections, establishing the reuse policy. Inside upload_sensor_batch, each client.post(...) becomes a task and asyncio.gather waits for all responses, allowing the requests to be multiplexed rather than sent serially. In production, keep the returned status and error evidence for every reading; concurrency improves transport use but does not prove that each upload was accepted.

# Python example: HTTP/2 with connection reuse for gateway
import httpx
import asyncio

# Create reusable HTTP/2 client
client = httpx.Client(
    http2=True,
    timeout=30.0,
    limits=httpx.Limits(
        max_keepalive_connections=5,
        max_connections=10,
        keepalive_expiry=3600  # 1 hour for IoT
    )
)

# Batch sensor readings efficiently
async def upload_sensor_batch(readings: list[dict]):
    """Upload multiple sensor readings in parallel over single HTTP/2 connection"""
    async with httpx.AsyncClient(http2=True) as client:
        tasks = [
            client.post(f"/api/v1/sensors/{r['device_id']}/data", json=r)
            for r in readings
        ]
        responses = await asyncio.gather(*tasks)
        # All 50 requests share single connection, multiplexed
        return responses
Broker Bex, Messaging and broker domain expertCheckpoint: implementation contract

You now know:

  • A production HTTP/2 gateway needs a reusable client session, bounded connection pools, and long-lived keep-alive rather than one request per connection.
  • Server settings such as http2_max_concurrent_streams 128, http2_recv_buffer_size 256k, and keepalive_timeout 3600s make the gateway pattern explicit.
  • Fleet tracking is the case where HTTP/3 features such as connection migration, 0-RTT resumption, and independent streams are easiest to justify.

With implementation knobs named, the comparison tables below put modern HTTP back into the wider IoT protocol landscape.


6.6 Protocol Comparison Summary

This section: Protocol Comparison Summary

ProtocolBest ForOverheadLatencyReliability
CoAPConstrained devices, 6LoWPANVery lowLowCON/NON; application outcome separate
MQTTEvent streams, pub-subLowLowQoS 0/1/2
HTTP/1.1Simple prototyping, debuggingHighMediumTCP
HTTP/2Gateways, cloud APIs, bulk uploadsMediumMediumTCP + multiplexing
HTTP/3Mobile links and loss-prone networksMediumLow (0-RTT resumption)QUIC streams

6.6.1 Protocol Positioning in the IoT Landscape

The following diagram shows how HTTP/2 and HTTP/3 fit into the broader IoT protocol ecosystem:

The following timeline shows how HTTP has evolved to address IoT requirements:

6.7 Real-World Tradeoffs

This section: Real-World Tradeoffs — Inspect Figure 6.2 to compare both the architecture and its dominant failure mode before reading the numeric table.

When selecting between HTTP versions in production IoT deployments, consider these practical tradeoffs:

Inspect Figure 6.2 to compare both the architecture and its dominant failure mode before reading the numeric table.

HTTP/2 over TCP versus HTTP/3 over QUIC architecture and failure-mode tradeoff: HTTP/2 is easier to deploy, HTTP/3 wins when roaming or packet loss dominates.
Figure 6.2: HTTP/2 vs HTTP/3 Tradeoff Analysis for IoT

Read Figure 6.2 from the protocol stacks into the network events. HTTP/2 multiplexes streams over one TLS-protected TCP connection and benefits from mature deployment paths, but a lost TCP segment can delay every stream behind that byte gap. HTTP/3 moves HTTP semantics onto QUIC, where streams recover independently and the connection can survive an address change, at the cost of a larger and sometimes less widely permitted stack. Those mechanisms explain the deployment metrics and staged strategy that follow.

6.7.1 Quantitative Comparison

MetricHTTP/2HTTP/3Winner For
Connection Setup2–3 RTT (TCP + TLS 1.3/1.2)1 RTT new; 0-RTT resumed (replay-safe data only)HTTP/3: mobile IoT
Memory FootprintTypically ~32 KB+Typically ~64 KB+HTTP/2: constrained gateways
Packet Loss ImpactAll streams blockedIndependent streamsHTTP/3: Lossy networks
Network HandoffConnection dropsSurvives IP changeHTTP/3: Vehicle tracking
Firewall TraversalTCP 443, almost always allowedUDP 443, sometimes blockedHTTP/2: enterprise
Library MaturityExcellentGood (improving)HTTP/2: Production systems
Debug ToolingMature (Chrome, curl)DevelopingHTTP/2: Development phase
Deployment Strategy

Start with HTTP/2 for initial deployments - it offers significant improvements over HTTP/1.1 with excellent tooling and support. Upgrade to HTTP/3 when you have proven the value proposition and your mobile/cellular use cases justify the added complexity.

This section:

Broker Bex, Messaging and broker domain expertCheckpoint: deployment tradeoffs

You now know:

  • HTTP/2 wins when tooling, firewall traversal and a smaller (typically ~32 KB) footprint matter more than handoff.
  • HTTP/3 wins when 0-RTT resumption, independent streams and migration justify its larger footprint.
  • A staged deployment starts with HTTP/2, then upgrades the mobile or lossy slice after measurements prove the complexity is worthwhile.

This section: — The final pitfalls section turns those tradeoffs into the mistakes to avoid during design review.

The final pitfalls section turns those tradeoffs into the mistakes to avoid during design review.


6.8 Common Pitfalls

This section: Common Pitfalls

Avoid These Mistakes

1. Assuming HTTP/3 is Always Better

HTTP/3’s QUIC transport offers significant advantages for mobile and lossy networks, but it’s not universally better:

  • UDP may be blocked by enterprise firewalls
  • HTTP/3 typically needs more RAM than HTTP/2 (QUIC state, crypto and per-stream buffers in user space).
  • Library support is still maturing on embedded platforms
  • For stable networks, HTTP/2 provides similar benefits with wider support

2. Ignoring Memory Constraints

Modern HTTP protocols have significant memory overhead:

  • HTTP/2 HPACK dynamic table size is negotiated and can be configured; count it with TLS and connection buffers
  • HTTP/3 QUIC connection state and QPACK buffers depend on implementation and configured limits
  • Don’t assume gateway-level protocols work on constrained sensors
  • Always verify RAM budget before selecting protocol

3. Opening Multiple HTTP/2 Connections

The whole point of HTTP/2 multiplexing is to use a SINGLE connection:

# WRONG: Creating new connection per request
for sensor in sensors:
    response = httpx.post(url, json=sensor.data)  # New connection each time!

# RIGHT: Reusing single multiplexed connection
async with httpx.AsyncClient(http2=True) as client:
    tasks = [client.post(url, json=s.data) for s in sensors]
    responses = await asyncio.gather(*tasks)  # All share one connection

4. Not Configuring Keep-Alive for IoT

Default HTTP timeouts are too short for IoT:

# nginx - extend for IoT workloads
keepalive_timeout 3600s;  # 1 hour, not default 75s
http2_idle_timeout 600s;  # 10 minutes idle before close

5. Forgetting 0-RTT Replay Attacks

HTTP/3’s 0-RTT is vulnerable to replay attacks. For idempotent operations (GET, sensor readings) this is fine, but for non-idempotent operations (commands, actuator triggers), use 1-RTT or implement replay protection.


6.9 Knowledge Check

This section: Knowledge Check

Test your understanding of Modern HTTP for IoT applications:


Matching Quiz: HTTP/2 and HTTP/3 Concepts

Match each HTTP/2 or HTTP/3 concept to its correct definition or IoT benefit.

Knowledge Check
Label the Diagram
Order the Steps

6.10 Deep Dive: One Connection, Many Streams, No Head-of-Line Block

This section: Deep Dive: One Connection, Many Streams, No Head-of-Line Block — The calculators above quantify the savings.

The calculators above quantify the savings. This layered walkthrough names the single mechanism those numbers come from: each HTTP version is another round in the fight against head-of-line blocking, and HTTP/2’s HPACK and HTTP/3’s QUIC are the specific tools that win it.

HTTP/1.1, HTTP/2, and HTTP/3 can be read as three attempts to reduce head-of-line blocking. HTTP/1.1 keep-alive reuses the TCP connection, but a connection still serves one request at a time, so a slow response blocks requests queued behind it. HTTP/2 fixes that HTTP-layer queue by multiplexing many streams over one TCP connection and shrinking repeated headers with HPACK. The remaining problem is underneath HTTP/2: TCP delivers bytes in strict order, so one lost segment stalls every HTTP/2 stream until retransmission. HTTP/3 moves to QUIC over UDP, where streams are independent and a lost packet stalls only the affected stream.

VersionWhat improvesRemaining constraint
HTTP/1.1Keep-alive avoids repeated connection setupOne active request per connection creates HTTP-layer queueing
HTTP/2Multiplexed streams and HPACK reduce connection and header overheadTCP packet loss blocks all streams on the connection
HTTP/3QUIC streams, 0-RTT resumption, and connection migration help lossy mobile linksHigher memory cost, UDP blocking, and newer tooling

HPACK is the HTTP/2 header-compression mechanism behind much of the gateway benefit. A gateway posting readings sends almost identical headers every request: host, authorization, user-agent, and content-type. HPACK uses a static table for common fields and a per-connection dynamic table for repeated values. The first request sends literal values and inserts them into the dynamic table; later requests reference those fields by index, often shrinking hundreds of header bytes to a few bytes. Short idle timeouts erase that dynamic table, so session reuse and header compression must be tuned together.

HTTP/3 uses QPACK rather than HPACK because QUIC streams can arrive out of order. QPACK keeps the same goal, compact repeated header fields, but avoids letting one blocked header reference stall unrelated streams. That distinction matters when telemetry, commands, and firmware chunks share one connection on a lossy link.

6.10.1 QUIC Streams and Connection Migration

QUIC folds reliable delivery, independent streams, TLS 1.3 encryption, and a connection identity into one transport. The connection identity is a QUIC Connection ID, not the client’s current IP address and port. That is why an HTTP/3 vehicle tracker can move from Wi-Fi to LTE without forcing application work to restart, while HTTP/2 over TCP normally loses the connection when the IP/port tuple changes.

HTTP/3 client

Single QUIC connection

(one Connection ID)

Stream 1: telemetry

Stream 2: firmware chunk

Stream 3: commands

Delivered independently

Lost packet: only Stream 2 waits

Be honest about the cost. QUIC does per-packet crypto in user space, uses more memory than HTTP/2, and depends on UDP being allowed end to end. On a stable managed Ethernet or Wi-Fi link, HTTP/2 can be the pragmatic choice. On a moving cellular asset where packet loss and address changes are normal, HTTP/3 earns its complexity if the device and network can support it.

Test the claim before standardizing on HTTP/3: start an upload on Wi-Fi, roam to cellular mid-stream, and verify that the same logical request survives under one QUIC Connection ID without restarting application work.

6.11 Summary and Key Takeaways

This section: Summary and Key Takeaways

What You Learned

This chapter covered the evolution of HTTP protocols and their applicability to IoT scenarios:

HTTP/2 Benefits:

Read these points as one connected sequence: start with Multiplexing lets concurrent gateway requests share a TCP connection; the 50× figure applies only to the chapter’s sequential baseline; then HPACK compression reduces header overhead by 90%, critical for chatty IoT applications; then Client-requested streaming or normal downloads can deliver firmware; HTTP/2 server push is optional and is not a reliable deployment assumption; and finish with Single TCP connection reduces TLS handshake overhead for persistent connections.

  • Multiplexing lets concurrent gateway requests share a TCP connection; the 50× figure applies only to the chapter’s sequential baseline
  • HPACK compression reduces repeated-header overhead in chatty IoT applications; the percentage depends on the header mix.
  • Client-requested streaming or normal downloads can deliver firmware; HTTP/2 server push is optional and is not a reliable deployment assumption
  • Single TCP connection reduces TLS handshake overhead for persistent connections

HTTP/3 Benefits:

Read these points as one connected sequence: start with 0-RTT resumption: eligible resumed requests can avoid setup waiting; total device power savings require measurement; then Independent streams: No cross-stream transport head-of-line blocking; shared congestion can still slow others; then Connection migration: Can preserve a connection across a supported network handoff for mobile assets; and finish with Connection-level congestion control: QUIC streams share connection capacity; test mixed telemetry and firmware traffic.

  • 0-RTT resumption: eligible resumed requests can avoid setup waiting; total device power savings require measurement
  • Independent streams: No cross-stream transport head-of-line blocking; shared congestion can still slow others
  • Connection migration: Can preserve a connection across a supported network handoff for mobile assets
  • Connection-level congestion control: QUIC streams share connection capacity; test mixed telemetry and firmware traffic

Protocol Selection Decision Tree (rule-of-thumb RAM bins):

Device RAMNetwork TypeRecommended Protocol
< 32KBAnyCoAP or MQTT
32-128KBStable (Wi-Fi/Ethernet)HTTP/2
32-128KBMobile/CellularHTTP/2 (due to RAM)
> 128KBStableHTTP/2
> 128KBMobile/CellularHTTP/3
AnyUDP BlockedHTTP/2 (fallback)

Key Insight: HTTP/2 and HTTP/3 don’t replace MQTT or CoAP for constrained IoT devices, but they significantly improve HTTP performance for gateways, cloud integration, and mobile IoT scenarios where HTTP infrastructure already exists.

Lab Exercise Ideas:

Read these points as one connected sequence: start with HTTP/2 Multiplexing Demo: Use curl --http2 with timing to compare 10 sequential vs. parallel requests; then Header Compression Measurement: Capture HTTP/1.1 vs HTTP/2 traffic with Wireshark to measure header size reduction; and finish with 0-RTT Latency Test: Configure a QUIC server and measure first-request latency for new vs. resumed connections.

  1. HTTP/2 Multiplexing Demo: Use curl --http2 with timing to compare 10 sequential vs. parallel requests
  2. Header Compression Measurement: Capture HTTP/1.1 vs HTTP/2 traffic with Wireshark to measure header size reduction
  3. 0-RTT Latency Test: Configure a QUIC server and measure first-request latency for new vs. resumed connections

Discussion Questions:

Read these points as one connected sequence: start with Why might an enterprise prefer HTTP/2 over HTTP/3 even when UDP is available?; then How does QUIC’s connection migration feature change the design of mobile IoT applications?; and finish with What are the security implications of 0-RTT early data?.

  • Why might an enterprise prefer HTTP/2 over HTTP/3 even when UDP is available?
  • How does QUIC’s connection migration feature change the design of mobile IoT applications?
  • What are the security implications of 0-RTT early data?

Common Student Misconceptions:

Read these points as one connected sequence: start with “HTTP/3 is always faster” - Not true; on stable networks with low loss, HTTP/2 performs similarly; then “HTTP/2 needs multiple connections” - The whole point is single connection with multiplexing; and finish with “Modern HTTP works on any device” - Memory constraints often make it impractical for constrained sensors.

  • “HTTP/3 is always faster” - Not true; on stable networks with low loss, HTTP/2 performs similarly
  • “HTTP/2 needs multiple connections” - The whole point is single connection with multiplexing
  • “Modern HTTP works on any device” - Memory constraints often make it impractical for constrained sensors

Concept Relationships

This section: Concept Relationships

Understanding HTTP/2 and HTTP/3 connects to several other protocol and networking concepts:

Foundation Concepts:

Read these points as one connected sequence: start with HTTP Connection Pitfalls - Problems HTTP/2 and HTTP/3 solve; then Application Protocols Overview - Position in the protocol landscape; then TCP Fundamentals - HTTP/2’s transport layer; and finish with UDP Basics - HTTP/3’s QUIC transport.

Alternative Protocols:

Read these points as one connected sequence: start with MQTT Fundamentals - Compare pub-sub vs HTTP request-response; then CoAP Overview - Lightweight alternative for constrained devices; and finish with WebSocket Fundamentals - Bidirectional alternative to HTTP.

  • MQTT Fundamentals - Compare pub-sub vs HTTP request-response
  • CoAP Overview - Lightweight alternative for constrained devices
  • WebSocket Fundamentals - Bidirectional alternative to HTTP

Related Technologies:

Read these points as one connected sequence: start with TLS/SSL Security - Encryption layer for HTTPS; then CDN Architecture - HTTP/3 benefits for edge delivery; and finish with Mobile IoT - HTTP/3’s 0-RTT for cellular devices.

  • TLS/SSL Security - Encryption layer for HTTPS
  • CDN Architecture - HTTP/3 benefits for edge delivery
  • Mobile IoT - HTTP/3’s 0-RTT for cellular devices

Prerequisites You Should Know:

Read these points as one connected sequence: start with TCP three-way handshake and why it adds latency; then TLS handshake process (2-3 RTT overhead); and finish with Difference between connection-oriented (TCP) and connectionless (UDP) protocols.

  • TCP three-way handshake and why it adds latency
  • TLS handshake process (2-3 RTT overhead)
  • Difference between connection-oriented (TCP) and connectionless (UDP) protocols

What This Enables:

Read these points as one connected sequence: start with gateway connection reuse for concurrent requests; then measure whether eligible 0-RTT resumption reduces mobile setup energy; and finish with protocol selection for stable and mobile networks.

  • Gateway design where a reusable connection carries concurrent requests
  • Mobile IoT optimization where eligible 0-RTT resumption reduces setup waiting; measure total battery impact
  • Protocol selection for different deployment scenarios (stable vs mobile networks)

See Also

This section: See Also — Read these points as one connected sequence: start with RFC 9113: HTTP/2 - Official HTTP/2 specification; then RFC 9114: HTTP/3 - Official HTTP/3 specification; and finish with RFC 9000: QUIC - QUIC transport protocol.

Core HTTP Concepts:

Read these points as one connected sequence: start with HTTP Connection Pitfalls - Common HTTP mistakes in IoT; then IoT API Design Best Practices - REST API design patterns; and finish with Application Protocols Overview - Protocol comparison framework.

Alternative Protocols:

Read these points as one connected sequence: start with MQTT Architecture - Broker-based pub-sub alternative; then CoAP Fundamentals - Constrained device protocol; and finish with AMQP Overview - Enterprise message queuing.

Implementation Guides:

Read these points as one connected sequence: start with Protocol Selection Guide - When to use each protocol; then Gateway Design Patterns - HTTP/2 for gateway scenarios; and finish with Mobile IoT Optimization - HTTP/3 battery benefits.

  • Protocol Selection Guide - When to use each protocol
  • Gateway Design Patterns - HTTP/2 for gateway scenarios
  • Mobile IoT Optimization - HTTP/3 battery benefits

Specifications:

Read these points as one connected sequence: start with RFC 9113: HTTP/2 - Official HTTP/2 specification; then RFC 9114: HTTP/3 - Official HTTP/3 specification; and finish with RFC 9000: QUIC - QUIC transport protocol.

Try It Yourself

This section: Try It Yourself — Read these points as one connected sequence: compare measured elapsed time for the same 50 requests under sequential and parallel HTTP/1.1 and multiplexed HTTP/2; then account for connection reuse and loss behavior.

Experiment 1: HTTP/2 Multiplexing Benchmark

Compare HTTP/1.1 sequential requests versus HTTP/2 parallel streams:

# Install httpx: pip install httpx
import httpx
import time

# HTTP/1.1 sequential
start = time.time()
with httpx.Client() as client:
    for i in range(50):
        client.get("https://httpbin.org/delay/0.1")
http1_time = time.time() - start

# HTTP/2 parallel
start = time.time()
with httpx.Client(http2=True) as client:
    import asyncio
    async def fetch_all():
        async with httpx.AsyncClient(http2=True) as async_client:
            tasks = [async_client.get("https://httpbin.org/delay/0.1") for _ in range(50)]
            await asyncio.gather(*tasks)
    asyncio.run(fetch_all())
http2_time = time.time() - start

print(f"HTTP/1.1: {http1_time:2f}s")
print(f"HTTP/2: {http2_time:2f}s")
print(f"Speedup: {http1_time/http2_time:1f}x")

What to Observe:

Read these points as one connected sequence: compare measured elapsed time for the same 50 requests under sequential and parallel HTTP/1.1 and multiplexed HTTP/2; then account for connection reuse and loss behavior.

  • Compare the chapter’s sequential HTTP/1.1 and concurrent HTTP/2 assumptions; a 10–50× result is a lab scenario, not a general expectation
  • Single TCP connection vs 6-8 parallel connections in HTTP/1.1
  • Lower latency variance with HTTP/2 multiplexing

Experiment 2: HPACK Header Compression

Measure header compression savings:

import httpx

# Capture traffic with Wireshark filtering "http2"
client = httpx.Client(http2=True)

# First request - headers sent in full
r1 = client.get("https://httpbin.org/headers",
                headers={"User-Agent": "IoTDevice/1.0",
                         "Authorization": "Bearer token123..."})

# Subsequent requests - headers compressed via HPACK
for i in range(10):
    r = client.get("https://httpbin.org/headers",
                   headers={"User-Agent": "IoTDevice/1.0",
                            "Authorization": "Bearer token123..."})

What to Observe:

Read these points as one connected sequence: start with an illustrative first request: full headers (~350 bytes); then Assumed subsequent requests: compressed to ~15-30 bytes (90%+ reduction); and finish with Total bandwidth savings over 100 requests.

  • First request: full headers (~350 bytes)
  • In this header-size example, subsequent requests are assumed to compress to ~15-30 bytes (90%+ less than the assumed ~350-byte first request).
  • Total bandwidth savings over 100 requests

Experiment 3: HTTP/3 vs HTTP/2 Latency

Compare connection establishment latency:

# HTTP/2 over TCP
time curl -I --http2 https://cloudflare-quic.com

# HTTP/3 over QUIC (requires curl 7.66+)
time curl -I --http3 https://cloudflare-quic.com

What to Observe:

Read these points as one connected sequence: start with HTTP/2: 2-3 RTT connection setup (TCP + TLS); then HTTP/3: 0-1 RTT with QUIC; and finish with Connection resumption: 0-RTT for HTTP/3.

  • HTTP/2: 2-3 RTT connection setup (TCP + TLS)
  • HTTP/3: 0-1 RTT with QUIC
  • Connection resumption: 0-RTT for HTTP/3

Challenge: Gateway Data Aggregation

Build an IoT gateway that collects from 20 simulated sensors and uploads to a cloud API:

import httpx
import asyncio
import time

async def simulate_sensor(sensor_id):
    """Simulate sensor reading"""
    await asyncio.sleep(0.1)
    return {"sensor_id": sensor_id, "value": 23.5}

async def gateway_http1():
    """HTTP/1.1 approach - sequential uploads"""
    readings = await asyncio.gather(*[simulate_sensor(i) for i in range(20)])
    with httpx.Client() as client:
        for reading in readings:
            client.post("https://httpbin.org/post", json=reading)

async def gateway_http2():
    """HTTP/2 approach - parallel multiplexed uploads"""
    readings = await asyncio.gather(*[simulate_sensor(i) for i in range(20)])
    async with httpx.AsyncClient(http2=True) as client:
        tasks = [client.post("https://httpbin.org/post", json=r) for r in readings]
        await asyncio.gather(*tasks)

# Measure and compare

Expected Results:

Under the stated sequential-versus-concurrent lab assumptions, read these points as one connected sequence: start with HTTP/1.1: ~2-3 seconds (sequential uploads); then HTTP/2: ~200-300 ms (parallel over single connection); and finish with 10x throughput improvement for gateway scenario.

  • HTTP/1.1: ~2-3 seconds (sequential uploads)
  • HTTP/2: ~200-300 ms (parallel over single connection)
  • About 10× less elapsed time under the stated sequential-versus-concurrent lab assumptions

6.12 What’s Next?

This section: What’s Next?

ChapterFocusWhy Read It
IoT API Design Best PracticesREST API design, payload formats, versioning, securityApply HTTP/2 efficiently with well-structured REST APIs and consistent topic naming
HTTP Connection PitfallsCommon HTTP mistakes in IoTUnderstand the problems that HTTP/2 and HTTP/3 were designed to solve
CoAP OverviewConstrained Application Protocol for low-power devicesCompare HTTP/2/3 against CoAP to select the right protocol for constrained sensors
MQTT FundamentalsPub-sub messaging for IoTEvaluate when MQTT’s lightweight broker model outperforms HTTP-based approaches
Cellular IoT FundamentalsLTE-M, NB-IoT, 5G connectivityPair HTTP/3’s 0-RTT battery savings with the right cellular radio technology
Application Protocols OverviewComplete module navigation and protocol comparison frameworkSituate HTTP/2 and HTTP/3 within the broader IoT protocol landscape

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