Microservices Architecture
HIL OS can be deployed as a suite of microservices designed for large-scale IoT fleet management. This architecture separates concerns into independently deployable services communicating through MQTT, HTTP, and WebSocket protocols.
Why Microservices for IoT?
The Monolith Problem
A single HIL process works well for prototyping and small deployments. As fleet sizes grow beyond 50 devices, a monolithic approach faces several challenges:
- Coupled scaling: CPU-intensive telemetry processing cannot scale independently from API request handling
- Single point of failure: A crash in the OTA updater takes down device monitoring
- Resource contention: Firmware uploads compete with real-time sensor data for processing time
- Deployment risk: Updating one feature requires restarting the entire system
- Team boundaries: Multiple developers modifying the same codebase creates merge conflicts
The Microservices Solution
Decomposing HIL into services solves these problems:
| Concern | Monolith | Microservices |
|---|---|---|
| Scaling | Vertical only | Horizontal per-service |
| Failure isolation | Total outage | Blast radius contained |
| Deployment | All-or-nothing | Independent per-service |
| Technology | Single language | Polyglot per-service |
| Team structure | Shared codebase | Service ownership |
When to Use Microservices
Microservices are appropriate when:
- Fleet size exceeds 100 devices
- Multiple teams need to develop independently
- Different services have different scaling requirements
- High availability is critical (99.9%+ uptime)
- You need regional deployment (edge + cloud)
For smaller deployments (under 50 devices), the monolithic HIL runtime is simpler and more efficient.
Architecture Overview
The HIL microservices architecture consists of seven core components connected through an MQTT message bus:
Design Principles
-
MQTT as the spine: All device communication flows through MQTT. Services publish and subscribe to topics rather than calling each other directly.
-
Single responsibility: Each service does one thing well. The Gateway handles HTTP routing. The Fleet manager tracks device state. The Telemetry service processes sensor data.
-
Shared-nothing storage: Each service owns its data. Redis for registry and cache. InfluxDB for time series. SQLite for local aggregations. No shared databases.
-
Graceful degradation: If one service goes down, others continue operating. The Fleet manager works even if Telemetry is down. Devices continue sending data through MQTT regardless of service health.
-
Observable by default: Every service exposes health checks, structured logs, and metrics endpoints.
Service Deep Dive
API Gateway (hil-api-gateway)
The API Gateway is the single entry point for all HTTP traffic. It translates RESTful HTTP requests into MQTT commands sent to devices, and routes responses back to clients.
Responsibilities:
- HTTP route handling and request validation
- API key authentication and rate limiting
- HTTP-to-MQTT bridge for device commands
- WebSocket stream for real-time data
- Request/response correlation via unique IDs
Key Topics:
| Topic Pattern | Direction | Description |
|---|---|---|
hil/device/{id}/command | Publish | Send command to device |
hil/device/{id}/response | Subscribe | Receive device response |
hil/device/{id}/status | Subscribe | Device state changes |
hil/device/{id}/telemetry | Subscribe | Real-time sensor data |
hil/events/# | Subscribe | System-wide events |
How Request/Response Works:
When a client sends POST /eval/:deviceId, the Gateway:
- Generates a unique
requestId - Publishes
{ requestId, action, payload }tohil/device/{deviceId}/command - Waits for a matching response on
hil/device/{deviceId}/response - Returns the response to the HTTP client (with 30s timeout)
// Internal flow (simplified)
const requestId = uuidv4();
mqttClient.publish(`hil/device/${deviceId}/command`, JSON.stringify({
requestId,
action: "eval",
payload: { code: "read(D13)" },
timestamp: Date.now()
}));
// Response arrives on subscription
mqttClient.on("message", (topic, payload) => {
const data = JSON.parse(payload);
if (data.requestId === requestId) {
resolve(data); // Send back to HTTP client
}
});
Rate Limiting:
The Gateway enforces per-client rate limiting using a sliding window algorithm:
- Default: 100 requests per 60-second window
- Configurable via
RATE_LIMIT_MAXandRATE_LIMIT_WINDOW_MS - Returns
429 Too Many RequestswithRetry-Afterheader when exceeded
Device Fleet (hil-device-fleet)
The Fleet service maintains a real-time registry of all HIL devices, tracking their online/offline status through MQTT heartbeats.
Responsibilities:
- Device registration and deregistration
- Heartbeat monitoring and offline detection
- Group management (logical device groupings)
- Capability-based device search
- Fleet health dashboard
Heartbeat Protocol:
Every HIL device publishes heartbeats at a configurable interval (default: 10 seconds):
{
"rssi": -45,
"uptime": 3600,
"freeHeap": 28400,
"timestamp": 1699900000000
}
The Fleet service subscribes to hil/device/+/heartbeat and tracks the last heartbeat time for each device. If no heartbeat is received within the timeout window (default: 30 seconds), the device is marked offline.
Auto-Offline Detection:
Device publishes heartbeat → Fleet records timestamp
↓
30 seconds pass with no heartbeat
↓
Fleet marks device as "offline"
↓
Publishes hil/device/{id}/status: { state: "offline" }
Group Management:
Groups allow logical organization of devices:
# Create a group
curl -X POST http://localhost:4001/groups \
-H "Content-Type: application/json" \
-d '{
"groupName": "production-line-1",
"description": "PLCs on manufacturing line 1",
"deviceIds": ["hil-001", "hil-002", "hil-003"],
"tags": ["manufacturing", "critical"]
}'
# Query group devices
curl http://localhost:4001/groups/production-line-1
Fleet Dashboard:
The /dashboard endpoint returns a comprehensive fleet health overview:
{
"fleet": {
"total": 150,
"online": 142,
"offline": 8,
"onlinePercentage": "94.7%"
},
"distribution": {
"byType": { "hil-standard": 120, "hil-pro": 30 },
"byCapability": { "gpio": 150, "i2c": 80, "spi": 45 },
"byFirmware": { "2.1.0": 100, "2.0.5": 50 }
}
}
Telemetry Pipeline (hil-telemetry)
The Telemetry service collects, aggregates, stores, and analyzes sensor data from all devices.
Responsibilities:
- Subscribe to all sensor data topics
- Time-window aggregation (1m, 5m, 1h)
- Anomaly detection with configurable thresholds
- Dual storage: InfluxDB (time series) + SQLite (aggregations)
- Data retention and cleanup
- CSV/JSON export
Data Flow:
Device publishes sensor data
↓
Telemetry receives on hil/device/+/telemetry
↓
┌───────────────────────────────────────┐
│ 1. Store raw reading in SQLite │
│ 2. Write to InfluxDB (time series) │
│ 3. Add to aggregation buffer │
│ 4. Run anomaly detection │
└───────────────────────────────────────┘
↓
Every 10 seconds: flush aggregation buffer
↓
┌───────────────────────────────────────┐
│ Compute min/max/avg for each window │
│ Store in telemetry_aggregations │
└───────────────────────────────────────┘
Anomaly Detection:
The service maintains configurable thresholds for common sensor types:
| Sensor | Min | Max | Severity |
|---|---|---|---|
| Temperature | -40 | 125 | Critical |
| Humidity | 0 | 100 | Warning |
| Voltage | 0 | 60 | Critical |
| Current | -50 | 50 | Warning |
| Pressure | 300 | 1100 | Info |
| RPM | 0 | 20000 | Warning |
| Battery | 0 | 100 | Warning |
| RSSI | -120 | 0 | Info |
When a reading exceeds thresholds, an anomaly is:
- Stored in
anomaly_logtable - Published to
hil/events/anomalyMQTT topic - Published to
hil/device/{id}/anomalyfor device-specific handling
Aggregation Windows:
| Window | Duration | Use Case |
|---|---|---|
| 1 minute | Real-time dashboards | Live monitoring |
| 5 minutes | Short-term trends | Alerting rules |
| 1 hour | Long-term analysis | Historical reports |
Data Retention:
Raw readings older than RETENTION_DAYS (default: 30) are automatically cleaned up hourly. Aggregations are retained longer since they represent summarized data.
OTA Service (hil-ota-service)
The OTA (Over-The-Air) service manages firmware distribution across the device fleet with staged rollouts and automatic rollback.
Responsibilities:
- Firmware upload and storage with SHA-256 checksums
- Version management and tracking
- Staged rollout campaigns (canary → percentage → full)
- Progress tracking per device
- Automatic rollback on failure
- Firmware checksum verification
Staged Rollout Flow:
1. Upload firmware → stored with SHA-256 checksum
↓
2. Create campaign → target devices selected
↓
3. Canary phase → 5% of devices receive update
↓
4. Monitor for failures (configurable threshold: 10%)
↓
┌─── Success ───┐ ┌─── Failure ───┐
↓ │ ↓ │
5. Advance to │ Rollback all │
25% → 50% → │ canary devices │
100% │ │
↓ ↓
6. Campaign complete Campaign rolled back
Firmware Checksum Verification:
Every firmware upload is checksummed with SHA-256. Devices verify the checksum after download:
# Verify a firmware file
curl http://localhost:4003/firmware/{firmwareId}/checksum
# Response
{
"firmwareId": "abc-123",
"storedChecksum": "a1b2c3d4...",
"computedChecksum": "a1b2c3d4...",
"match": true
}
Rollback Mechanism:
Automatic rollback triggers when the failure rate exceeds 10% of completed updates during any stage. Manual rollback can also be triggered:
# Manual rollback
curl -X POST http://localhost:4003/campaigns/{campaignId}/rollback
# Response
{
"success": true,
"campaignId": "...",
"status": "rolled_back",
"rollbackCount": 42
}
MQTT-WebSocket Bridge (hil-mqtt-bridge)
The Bridge service provides bidirectional translation between MQTT and WebSocket protocols, enabling web browsers and mobile apps to communicate with devices in real-time.
Responsibilities:
- Bidirectional MQTT ↔ WebSocket translation
- Topic subscription management per client
- QoS level translation (WS QoS 0/1 → MQTT QoS 0/1/2)
- Connection pooling and heartbeat monitoring
- Max connection enforcement
WebSocket Protocol:
Clients connect to ws://host:80/ws (through nginx) and exchange JSON messages:
// Subscribe to device telemetry
ws.send(JSON.stringify({
type: "subscribe",
topics: ["hil/device/hil-001/telemetry", "hil/device/hil-001/status"],
qos: 1
}));
// Receive messages
ws.onmessage = (event) => {
const msg = JSON.parse(event.data);
if (msg.type === "message") {
console.log(`Topic: ${msg.topic}`, msg.payload);
}
};
// Publish to device
ws.send(JSON.stringify({
type: "publish",
topic: "hil/device/hil-001/command",
payload: { action: "read", pin: 13 },
qos: 1
}));
Message Format Normalization:
All messages flowing through the bridge are normalized to a consistent format:
{
"type": "message",
"topic": "hil/device/hil-001/telemetry",
"payload": { "temperature": 23.5, "humidity": 45 },
"timestamp": 1699900000000,
"size": 42
}
Docker Compose Quick Start
Prerequisites
- Docker Engine 20.10+
- Docker Compose v2+
- 2GB RAM minimum (4GB recommended)
- Ports 80, 1883, 6379, 8086 available
Start All Services
cd microservices/
# Generate secure keys
export API_KEY=$(openssl rand -hex 32)
export JWT_SECRET=$(openssl rand -hex 32)
# Build and start
docker-compose up -d --build
# Watch startup logs
docker-compose logs -f
Verify Installation
# Check all services are healthy
docker-compose ps
# Test API Gateway
curl -H "X-API-Key: $API_KEY" http://localhost/api/gateway/health
# Test Fleet Dashboard
curl http://localhost/api/fleet/dashboard
# Test Telemetry Stats
curl http://localhost/api/telemetry/stats
First Device Registration
# Register a device
curl -X POST http://localhost/api/gateway/devices/register \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
-d '{
"deviceId": "hil-demo-001",
"name": "Demo Sensor",
"type": "sensor-node",
"capabilities": ["gpio", "i2c", "temperature"],
"firmwareVersion": "2.1.0"
}'
# Check it appears in the fleet
curl -H "X-API-Key: $API_KEY" http://localhost/api/gateway/devices
# Execute code on it
curl -X POST http://localhost/api/gateway/eval/hil-demo-001 \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
-d '{"code": "read(A0)", "language": "hil"}'
Service Communication Patterns
Asynchronous MQTT (Primary)
Most inter-service communication uses MQTT pub/sub. Services never call each other directly for device data:
Client → Gateway → MQTT → Device
Device → MQTT → Gateway → Client
Device → MQTT → Telemetry → InfluxDB
Device → MQTT → Fleet → Redis
Advantages:
- Decoupled producers and consumers
- Natural backpressure (MQTT queues messages)
- Survives service restarts (QoS 1/2)
- Fan-out to multiple consumers
Synchronous HTTP (Fleet Queries)
The OTA service calls the Fleet service via HTTP when creating campaigns without explicit device targets:
OTA Service → HTTP GET → Fleet Service → Device list
This is the only synchronous inter-service call. It uses fetch() with a 5-second timeout.
WebSocket (Client Streaming)
Real-time data flows from MQTT through the Bridge to WebSocket clients:
Device → MQTT → Bridge → WebSocket → Browser
The Bridge maintains persistent connections and translates protocols transparently.
Deployment Scenarios
Smart Home (50 Devices)
A smart home deployment with 50 IoT devices:
# docker-compose.override.yml for smart home
services:
hil-api-gateway:
deploy:
resources:
limits: { memory: 256M, cpus: "0.5" }
hil-device-fleet:
deploy:
resources:
limits: { memory: 256M, cpus: "0.25" }
hil-telemetry:
deploy:
resources:
limits: { memory: 256M, cpus: "0.5" }
hil-ota-service:
deploy:
resources:
limits: { memory: 128M, cpus: "0.25" }
hil-mqtt-bridge:
deploy:
resources:
limits: { memory: 128M, cpus: "0.25" }
Expected resource usage:
- Total RAM: ~1.5GB
- Total CPU: ~2 cores
- MQTT messages/sec: ~50 (1 per device per second)
- Redis memory: ~50MB
Agriculture (500 Sensors)
An agricultural deployment with 500 soil/weather sensors:
# Scale telemetry and fleet for high sensor count
services:
hil-device-fleet:
deploy:
replicas: 2
resources:
limits: { memory: 512M, cpus: "1.0" }
hil-telemetry:
deploy:
replicas: 3
resources:
limits: { memory: 1G, cpus: "2.0" }
redis:
command: >
redis-server --appendonly yes
--maxmemory 1gb
--maxmemory-policy allkeys-lru
Key considerations:
- Telemetry pipeline needs 3 replicas for 500 sensors at 1 reading/second
- InfluxDB storage: ~2GB/day at 500 readings/second
- Retention policy: 7 days raw, forever aggregated
- MQTT topic partitioning by field zone
Industrial (1000 PLCs)
An industrial deployment with 1000 PLCs on a manufacturing floor:
services:
hil-api-gateway:
deploy:
replicas: 3
environment:
RATE_LIMIT_MAX: 500
hil-device-fleet:
deploy:
replicas: 2
environment:
HEARTBEAT_TIMEOUT_MS: 10000
FLEET_SCAN_INTERVAL_MS: 5000
hil-telemetry:
deploy:
replicas: 5
environment:
AGGREGATION_WINDOWS: "10,60,300"
RETENTION_DAYS: 90
hil-ota-service:
deploy:
replicas: 2
environment:
CANARY_PERCENT: 2
ROLLOUT_STAGES: "2,10,25,50,75,100"
redis:
command: >
redis-server --appendonly yes
--maxmemory 4gb
--maxmemory-policy volatile-lru
influxdb:
volumes:
- influxdb-data:/var/lib/influxdb2
deploy:
resources:
limits: { memory: 4G, cpus: "4.0" }
Key considerations:
- Shorter heartbeat timeouts for critical industrial equipment
- Aggressive telemetry aggregation (10-second windows)
- Lower canary percentage for safety-critical rollouts
- 90-day data retention for compliance
- Dedicated Redis with 4GB memory
Kubernetes Production Deployment
Helm Chart Structure
# hil-platform/values.yaml
replicaCount:
apiGateway: 3
deviceFleet: 2
telemetry: 5
otaService: 2
mqttBridge: 3
resources:
apiGateway:
requests: { cpu: 250m, memory: 256Mi }
limits: { cpu: 1000m, memory: 512Mi }
telemetry:
requests: { cpu: 500m, memory: 512Mi }
limits: { cpu: 2000m, memory: 1Gi }
autoscaling:
enabled: true
minReplicas: 2
maxReplicas: 10
targetCPUUtilization: 70
targetMemoryUtilization: 80
Horizontal Pod Autoscaling
# k8s/hpa.yaml
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: hil-telemetry-hpa
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: hil-telemetry
minReplicas: 3
maxReplicas: 15
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70
- type: Resource
resource:
name: memory
target:
type: Utilization
averageUtilization: 80
MQTT Topic Partitioning
For large-scale Kubernetes deployments, partition MQTT topics across broker instances:
Zone A devices → mosquitto-a:1883
Zone B devices → mosquitto-b:1883
Zone C devices → mosquitto-c:1883
Each telemetry replica subscribes to a specific zone
# Partitioned telemetry deployment
apiVersion: apps/v1
kind: Deployment
metadata:
name: hil-telemetry-zone-a
spec:
replicas: 3
template:
spec:
containers:
- name: telemetry
env:
- name: MQTT_BROKER
value: "mqtt://mosquitto-a:1883"
- name: TOPIC_FILTER
value: "hil/device/zone-a/+/telemetry"
Monitoring
Prometheus + Grafana Stack
Add monitoring with Prometheus scraping /health and custom metrics endpoints:
# docker-compose.monitoring.yml
services:
prometheus:
image: prom/prometheus:latest
ports: ["9090:9090"]
volumes:
- ./monitoring/prometheus.yml:/etc/prometheus/prometheus.yml
networks: [hil-net]
grafana:
image: grafana/grafana:latest
ports: ["3000:3000"]
environment:
GF_SECURITY_ADMIN_PASSWORD: ${GRAFANA_PASSWORD:-admin}
volumes:
- grafana-data:/var/lib/grafana
networks: [hil-net]
Key Metrics to Monitor
| Metric | Service | Alert Threshold |
|---|---|---|
mqtt_connected_clients | Mosquitto | < expected count |
device_online_percentage | Fleet | < 90% |
telemetry_processing_rate | Telemetry | < 100 msg/sec |
anomaly_detection_rate | Telemetry | > 10/sec |
ota_failure_rate | OTA | > 5% |
ws_active_connections | Bridge | > max * 0.9 |
http_request_latency_p99 | Gateway | > 500ms |
redis_memory_usage | Redis | > 80% |
Structured Logging
All services emit structured JSON logs:
{
"service": "hil-telemetry",
"level": "info",
"message": "Anomaly detected",
"deviceId": "hil-001",
"sensor": "temperature",
"value": 135.2,
"threshold": 125,
"severity": "critical",
"timestamp": "2024-11-14T12:00:00.000Z"
}
Security
API Key Authentication
All API endpoints require an X-API-Key header:
curl -H "X-API-Key: your-256-bit-key" http://localhost/api/gateway/devices
Generate a secure key:
export API_KEY=$(openssl rand -hex 32)
JWT Token Support
For multi-tenant deployments, extend the Gateway with JWT validation:
// Add to gateway middleware
const jwt = require("jsonwebtoken");
function jwtAuth(req, res, next) {
const token = req.headers.authorization?.replace("Bearer ", "");
if (!token) return res.status(401).json({ error: "No token provided" });
try {
const decoded = jwt.verify(token, JWT_SECRET);
req.user = decoded;
next();
} catch {
return res.status(401).json({ error: "Invalid token" });
}
}
mTLS Between Services
For zero-trust networking, configure mutual TLS between all services:
# In docker-compose.yml, mount certificates
services:
hil-api-gateway:
volumes:
- ./certs/ca.crt:/app/certs/ca.crt:ro
- ./certs/gateway.crt:/app/certs/server.crt:ro
- ./certs/gateway.key:/app/certs/server.key:ro
environment:
TLS_CA: /app/certs/ca.crt
TLS_CERT: /app/certs/server.crt
TLS_KEY: /app/certs/server.key
MQTT Authentication
Configure Mosquitto with password authentication:
# Create password file
docker exec hil-mosquitto mosquitto_passwd -c /mosquitto/config/password.txt admin
docker exec hil-mosquitto mosquitto_passwd -b /mosquitto/config/password.txt device-pass
Network Isolation
Docker Compose isolates the internal network. Only nginx exposes ports externally. Services communicate on the hil-net bridge network and cannot be reached from outside Docker.
Scaling Guide
Horizontal Scaling Rules
| Service | Scale When | Max Replica Guidance |
|---|---|---|
| API Gateway | CPU > 70%, p99 latency > 500ms | 2-5 replicas |
| Device Fleet | > 500 devices, CPU > 60% | 1-3 replicas |
| Telemetry | Ingest rate > capacity, CPU > 70% | 3-15 replicas |
| OTA Service | Active campaign + high device count | 1-3 replicas |
| MQTT Bridge | WS connections > 80% max | 2-5 replicas |
Scaling MQTT
Mosquitto is the bottleneck for message throughput. Options:
- Vertical scaling: Increase Mosquitto resources (easiest)
- Clustering: Use MQTT brokers with shared subscriptions
- Topic partitioning: Split devices across broker instances
- Alternative brokers: Consider EMQX or VerneMQ for > 10K devices
Scaling Redis
For large device fleets (> 1000 devices):
- Use Redis Cluster with sharding
- Configure
maxmemoryappropriately - Use
allkeys-lrueviction for cache workloads - Monitor with
redis-cli INFO memory
Scaling InfluxDB
For high telemetry throughput:
- Use InfluxDB Enterprise or Cloud for clustering
- Configure continuous queries for downsampled data
- Set appropriate shard group durations
- Use separate retention policies per data type
References
- Newman, S. (2021). Building Microservices: Designing Fine-Grained Systems (2nd ed.). O'Reilly Media.
- Richardson, C. (2018). Microservices Patterns: With Examples in Java. Manning Publications.
- Burns, B., & Beda, J. (2024). Kubernetes: Up and Running (3rd ed.). O'Reilly Media.
- Hohpe, G., & Woolf, B. (2003). Enterprise Integration Patterns. Addison-Wesley.
- Ford, N., & Richards, M. (2020). Release It! Design and Deploy Production-Ready Software (2nd ed.). Pragmatic Bookshelf.
- Antanies, J. (2022). IoT with MQTT: A Practical Guide to the Message Queuing Telemetry Transport Protocol. Packt Publishing.
- Vasquez, M. (2023). The IoT Handbook: Build IoT Solutions with MQTT, Raspberry Pi, and Node-RED. Apress.
- Richardson, C., & others (2023). Microservices: Pattern by Example. microservices.io.
- Mosquitto Project (2024). Eclipse Mosquitto v2.0 Documentation. https://mosquitto.org/documentation/
- InfluxData (2024). InfluxDB v2.7 Documentation. https://docs.influxdata.com/influxdb/v2.7/