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.
| QoS | Nama | Deskripsi | Gunakan |
|---|---|---|---|
| 0 | At most once | Fire and forget, no ack | Sensor data, telemetry |
| 1 | At least once | Acknowledged, may duplicate | Commands, notifications |
| 2 | Exactly once | 4-step handshake | Billing, 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).
| Code | Nama | Gunakan |
|---|---|---|
| 200 | OK | Success |
| 201 | Created | Resource created |
| 204 | No Content | Delete success |
| 301 | Moved Permanently | Redirect |
| 400 | Bad Request | Invalid input |
| 401 | Unauthorized | Need auth |
| 403 | Forbidden | No permission |
| 404 | Not Found | Resource missing |
| 429 | Too Many Requests | Rate limited |
| 500 | Internal Server Error | Server 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
| Fitur | MQTT | HTTP | WebSocket | CoAP |
|---|---|---|---|---|
| Transport | TCP | TCP | TCP | UDP |
| Model | Publish/Subscribe | Request/Response | Full Duplex | Request/Response |
| Overhead | Sangat rendah | Tinggi | Sedang | Sangat rendah |
| Real-time | Ya (push) | Tidak (polling) | Ya (bidirectional) | Ya (observe) |
| Ukuran payload | 256 MB | Tidak terbatas | 64 KB frame | ~1 KB optimal |
| Use case | IoT sensor | Web API | Chat, live data | Embedded 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?
| Skenario | Protokol Terbaik | Alasan |
|---|---|---|
| Sensor suhu kirim data tiap 5 detik | MQTT QoS 0 | Overhead rendah, pub/sub cocok untuk telemetry |
| Mobile app ambil data user | HTTP REST | Request/response, caching, universal support |
| Dashboard monitoring real-time | WebSocket | Full duplex, push data tanpa polling |
| ESP32 kirim data ke gateway | CoAP | Sangat ringan, hemat bandwidth dan memory |
| Chat aplikasi | WebSocket | Latency rendah, bidirectional communication |
| Microservice communication | HTTP/gRPC | Standar industri, tooling lengkap |
| Smart home control | MQTT QoS 1 | Reliable delivery, retained messages |