☀️Siang

Cheatsheet MQTT & HTTP: Referensi Cepat Protokol IoT dan Web

Referensi cepat protokol MQTT, HTTP, CoAP, dan WebSocket untuk developer IoT dan web.

Cheatsheet ini menyediakan referensi cepat dan praktis untuk empat protokol komunikasi yang paling banyak digunakan dalam pengembangan IoT dan web modern: MQTT, HTTP/REST, WebSocket, dan CoAP. Setiap bagian dilengkapi dengan contoh kode langsung yang bisa Anda copy-paste, tabel referensi, serta penjelasan singkat kapan harus menggunakan protokol tertentu. Cocok untuk developer IoT yang bekerja dengan sensor dan microcontroller, backend developer yang membangun REST API, maupun siapa saja yang ingin memahami cara komunikasi antar-sistem berjalan di dunia nyata.

📡 MQTT Quick Reference

MQTT (Message Queuing Telemetry Transport) adalah protokol messaging ringan berbasis publish/subscribe yang dirancang untuk komunikasi mesin-ke-mesin (M2M) dan IoT. Broker MQTT bertengah antara publisher (pengirim) dan subscriber (penerima), sehingga kedua belah pihak tidak perlu saling mengenal. Keunggulan utama MQTT adalah overhead header yang sangat kecil (hanya 2 byte minimum), dukungan QoS tiga level, dan retained messages yang menyimpan pesan terakhir pada sebuah topic.

QoSNamaDeskripsiGunakan
0At most onceFire and forget, no ackSensor data, telemetry
1At least onceAcknowledged, may duplicateCommands, notifications
2Exactly once4-step handshakeBilling, critical data
# Mosquitto CLI
mosquitto_pub -h broker.com -t "topic" -m "message"
mosquitto_sub -h broker.com -t "topic/#" -v
mosquitto_pub -t "cmd/led" -m '{"state":"on"}' -q 1 -r

# Topic patterns
sensor/temperature/livingroom  # Specific
sensor/+/livingroom            # Single level wildcard
sensor/#                       # Multi level wildcard

🌐 HTTP Status Codes

HTTP (Hypertext Transfer Protocol) adalah protokol standar untuk komunikasi web. Setiap response dari server menyertakan status code yang menunjukkan hasil request. Memahami status code sangat penting untuk debugging API dan menulis error handling yang tepat. Status code dibagi dalam 5 kategori: 1xx (informational), 2xx (success), 3xx (redirect), 4xx (client error), dan 5xx (server error).

CodeNamaGunakan
200OKSuccess
201CreatedResource created
204No ContentDelete success
301Moved PermanentlyRedirect
400Bad RequestInvalid input
401UnauthorizedNeed auth
403ForbiddenNo permission
404Not FoundResource missing
429Too Many RequestsRate limited
500Internal Server ErrorServer error

🔗 REST API Patterns

GET    /api/users          # List all users
GET    /api/users/123       # Get user 123
POST   /api/users           # Create user
PUT    /api/users/123       # Update user 123
PATCH  /api/users/123       # Partial update
DELETE /api/users/123       # Delete user 123

# Headers
Content-Type: application/json
Authorization: Bearer <token>
Accept: application/json

📡 WebSocket

// Client
const ws = new WebSocket("wss://api.example.com/ws");
ws.onopen = () => ws.send(JSON.stringify({type: "subscribe", topic: "sensor"}));
ws.onmessage = (e) => console.log(JSON.parse(e.data));
ws.onclose = () => console.log("Disconnected");

// Headers (handshake)
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13

📡 CoAP (Constrained Application Protocol)

CoAP adalah protokol ringan berbasis UDP yang dirancang khusus untuk perangkat IoT dengan resource terbatas. Berbeda dengan HTTP, CoAP menggunakan format biner yang jauh lebih efisien dan mendukung multicast.

# CoAP methods (mirrors HTTP)
GET    /sensors/temperature    # Read resource
POST   /sensors                # Create resource
PUT    /sensors/1              # Update resource
DELETE /sensors/1              # Delete resource

# CoAP response codes
2.01 Created
2.05 Content
4.00 Bad Request
4.04 Not Found

# Using libcoap CLI
coap-client -m get coap://sensor.local/sensors/temp
coap-client -m put -e '{"led":"on"}' coap://sensor.local/actuators/led

# Observe (subscribe to changes, like MQTT)
coap-client -s 10 coap://sensor.local/sensors/temp

🔄 Perbandingan Protokol

FiturMQTTHTTPWebSocketCoAP
TransportTCPTCPTCPUDP
ModelPublish/SubscribeRequest/ResponseFull DuplexRequest/Response
OverheadSangat rendahTinggiSedangSangat rendah
Real-timeYa (push)Tidak (polling)Ya (bidirectional)Ya (observe)
Ukuran payload256 MBTidak terbatas64 KB frame~1 KB optimal
Use caseIoT sensorWeb APIChat, live dataEmbedded IoT

💡 Tips & Best Practices

🔒 Keamanan MQTT: Selalu gunakan TLS (port 8883) untuk koneksi MQTT di production. Gunakan username/password atau client certificate untuk autentikasi. Jangan pernah mengirim data sensitif tanpa enkripsi.

📋 Topic Design: Buat hierarki topic yang konsisten dan terstruktur. Gunakan format org/device-type/device-id/metric untuk memudahkan filtering dan akses control. Hindari topic yang terlalu dalam (maksimal 5 level).

🔄 QoS Selection: Gunakan QoS 0 untuk data telemetri biasa yang toleran hilang, QoS 1 untuk command dan notifikasi, dan QoS 2 hanya untuk data kritis seperti transaksi pembayaran karena overhead-nya 4x lipat.

🌐 REST API Design: Gunakan noun (bukan verb) untuk endpoint: /api/users bukan /api/getUsers. Gunakan HTTP method yang tepat: GET untuk read, POST untuk create, PUT untuk full update, PATCH untuk partial update, DELETE untuk hapus.

🔌 WebSocket vs Polling: Jika aplikasi membutuhkan update real-time dari server (chat, notifikasi, live dashboard), gunakan WebSocket. Untuk data yang jarang berubah (setiap 30 detik+), long-polling atau SSE (Server-Sent Events) mungkin lebih sederhana dan cukup.

📊 Rate Limiting: Selalu implementasikan rate limiting di API Anda. Return header X-RateLimit-Limit, X-RateLimit-Remaining, dan X-RateLimit-Reset agar client tahu batasan mereka.

📌 Kapan Menggunakan?

SkenarioProtokol TerbaikAlasan
Sensor suhu kirim data tiap 5 detikMQTT QoS 0Overhead rendah, pub/sub cocok untuk telemetry
Mobile app ambil data userHTTP RESTRequest/response, caching, universal support
Dashboard monitoring real-timeWebSocketFull duplex, push data tanpa polling
ESP32 kirim data ke gatewayCoAPSangat ringan, hemat bandwidth dan memory
Chat aplikasiWebSocketLatency rendah, bidirectional communication
Microservice communicationHTTP/gRPCStandar industri, tooling lengkap
Smart home controlMQTT QoS 1Reliable delivery, retained messages
🔍 Zoom
100%
🎨 Tema