Back to Blog

Try n8n free for 10 days — no charge until day 11 on select plans

Or skip the trial and start from $4/mo today

n8nIoTMQTTautomationdatabase

Industrial IoT in n8n: Process MQTT Telemetry with Postgres and HTTP

n8nautomation TeamOctober 2, 2026

Deploying production telemetry pipelines requires resilient n8n managed hosting that can ingest continuous telemetry bursts without dropping packets or exhausting process memory. Edge gateways, environmental monitors, and PLC bridges generate high-frequency JSON or raw binary packets every second. While traditional industrial automation relies on isolated SCADA software, modern manufacturing operations require those shop-floor metrics connected to business applications like Postgres databases, ERP systems, and incident alert channels.

Connecting operational technology to web services has historically required dedicated custom middleware written in C++ or Python. In this guide, you will build an event-driven industrial IoT architecture directly inside n8n. We will cover broker authentication, unpacking payload structures, batching high-throughput writes into time-series tables, and triggering instant maintenance alerts when vibration or temperature limits are breached.

Architecting the Shop-Floor to Cloud Pipeline

Industrial telemetry flows from physical machines to operational databases through a decoupled publish-subscribe pattern. Field devices do not open direct HTTP sockets to external web services because transient network drops on factory floors would cause catastrophic data loss. Instead, edge gateways collect serial or fieldbus metrics from PLCs (Programmable Logic Controllers), convert them to MQTT topics, and push them to a central broker such as Mosquitto, EMQX, or HiveMQ.

Your n8n instance acts as an intelligent subscriber and routing layer. The workflow architecture consists of five distinct operational phases:

  • Ingestion: The MQTT Trigger node maintains a persistent connection to your industrial broker, subscribing to wildcards such as factory/line-1/+/telemetry.
  • Normalization: An Edit Fields node flattens nested sensor payloads, verifies schema integrity, and normalizes timestamp formats into ISO 8601 strings.
  • Anomaly Detection: A Switch node evaluates physical threshold metrics such as temperature, bearing vibration, and fluid pressure against operating safety envelopes.
  • Batch Persistence: A Postgres node writes verified records into time-series hyper-tables in micro-batches to avoid saturating database connection pools.
  • Dispatch: Critical machine anomalies branch to an HTTP Request node that fires on-call alerts via webhooks into incident dispatch queues.

Maintaining persistent TCP connections for MQTT subscribers requires sustained container stability. When organizations evaluate how to install n8n for real-time factory operations, they often run into infrastructure constraints that disrupt continuous subscriber listeners.

Configuring the MQTT Trigger in n8n Managed Hosting

To ingest real-time machine metrics, you configure the native MQTT Trigger node to connect directly to your plant's message broker. Unlike polling triggers that query an endpoint on a schedule, the MQTT Trigger node keeps an active socket open and triggers workflow execution the instant a publisher sends a packet.

Set up your broker credentials and topic subscription using the following parameters inside the MQTT node:

  1. Topic Subscription: Specify the topic string with directional wildcards. For example, production/cell_04/sensors/# captures all telemetry streams across temperature, current, and pneumatic sensors within cell four.
  2. Quality of Service (QoS): Set the QoS to 1 (At least once). This guarantees that intermittent network jitter on the factory edge will not discard machine performance frames.
  3. Data Format: Select JSON if your edge gateway outputs structured strings. If your hardware transmits binary arrays or hex streams, select String so a downstream Code node can unpack the buffer.
  4. Keepalive Interval: Set the keepalive parameter to 60 seconds to allow the broker to detect silent client drops without timing out premature connections.

Tip: Always include the MQTT topic name in the node's output properties. The topic path often contains critical metadata like cell ID and sensor type that helps avoid redundant payload properties.

When running high-concurrency event loops, system background threads must remain active without hitting aggressive execution throttling. Using dedicated n8n managed hosting from n8nautomation.cloud ensures your instances receive dedicated CPU cores and stable memory allocations starting at $4/month, preventing the dropped MQTT connections common on generic shared serverless platforms.

Parsing Hex and Binary Payloads with the Code Node

Many legacy industrial field gateways conserve bandwidth over cellular and satellite links by encoding metrics as compact byte arrays rather than verbose JSON documents. A gateway might broadcast a 16-byte payload containing device status, millivolt readings, and temperature offsets encoded in big-endian hex.

When raw payloads arrive in n8n, pass the incoming string through a JavaScript Code node to unpack the raw bytes into human-readable engineering units. The following script parses an 8-byte hex buffer representing machine telemetry:

// Input payload example: "01a403e8003c0001"
const items = $input.all();
const parsedResults = [];

for (const item of items) {
  const rawHex = item.json.message;
  const buffer = Buffer.from(rawHex, 'hex');

  // Unpack fixed-length byte offsets
  const deviceId = buffer.readUInt16BE(0);
  const currentMilliAmps = buffer.readUInt16BE(2);
  const temperatureCelsius = buffer.readInt16BE(4) / 10.0;
  const statusFlags = buffer.readUInt16BE(6);

  parsedResults.push({
    json: {
      deviceId: `DEV-${deviceId}`,
      currentDrawAmps: currentMilliAmps / 1000,
      temperatureCelsius: temperatureCelsius,
      faultStatus: (statusFlags & 0x01) === 1,
      maintenanceRequired: (statusFlags & 0x02) === 2,
      recordedAt: new Date().toISOString(),
      topic: item.json.topic
    }
  });
}

return parsedResults;

This snippet reads raw buffers, computes floating-point conversions, and applies bitwise masks to evaluate machine operational registers. The output produces clean JSON objects ready for database insertion or conditional routing.

Batching Time-Series Sensor Writes in PostgreSQL

Processing edge metrics on an individual row basis quickly overburdens your database. If twenty edge sensors emit readings every 200 milliseconds, inserting each record individually creates hundreds of database transactions per second. This spikes disk I/O, consumes CPU, and locks tables.

To preserve database resources, batch incoming sensor events before writing to disk. You achieve this using the Split In Batches node alongside an Item Lists node:

  1. Aggregate Incoming Items: Collect telemetry records using the Item Lists node with the Aggregate Items operation to bundle independent executions into a single unified array.
  2. Batch Sizing: Route the grouped array into an Item Lists node set to Split Into Batches with a batch size of 250 items. This guarantees that your SQL driver never sends payload arrays larger than your network MTU or Postgres query size limit.
  3. Executing the Insert: Connect the batch output to a Postgres node set to the Execute Query operation.

Run an optimized multi-row insert query that avoids serial table locks:

INSERT INTO machine_telemetry (
  device_id,
  current_draw_amps,
  temperature_celsius,
  fault_status,
  maintenance_required,
  recorded_at
)
SELECT
  device_id,
  current_draw_amps,
  temperature_celsius,
  fault_status,
  maintenance_required,
  recorded_at::timestamptz
FROM json_to_recordset($1::json) AS (
  device_id VARCHAR(32),
  current_draw_amps NUMERIC(6,2),
  temperature_celsius NUMERIC(5,2),
  fault_status BOOLEAN,
  maintenance_required BOOLEAN,
  recorded_at TEXT
);

Passing an entire batch as a single JSON array parameter inside $1 allows Postgres to unpack and commit hundreds of rows in a single disk cycle. This keeps database write latency under five milliseconds even during peak plant operations.

Note: If your PostgreSQL instance uses the TimescaleDB extension, ensure your hyper-table chunk interval aligns with your retention schedule. For telemetry rates exceeding 50,000 metrics per hour, set chunk intervals to 1 day rather than 7 days to maintain index performance in memory.

Optimizing Telemetry Pipelines with n8n Managed Hosting

Factory automation workflows present unique resource demands compared to traditional marketing or CRM tasks. Telemetry pipelines maintain unbroken data ingestion. When teams experiment with a self hosted n8n deployment on unmanaged virtual private servers, they regularly encounter hidden maintenance obstacles:

  • Execution History Overload: Continuous MQTT workflows generate tens of thousands of execution logs daily. Without automated execution pruning, your internal SQLite or PostgreSQL database fills available disk space, freezing all active listeners.
  • Connection Leaks: Sudden network interruptions between plant routers and unmanaged cloud servers can leave zombie TCP sockets lingering. Without automated process supervision, workflows stop receiving messages silently.
  • Memory Accumulation: Processing continuous binary buffers in Node.js requires strict garbage collection controls. Sub-optimal configuration leads to silent container restarts that drop telemetry during critical production windows.

Running high-volume edge pipelines on reliable n8n hosting solves these infrastructure bottlenecks. At n8nautomation.cloud, our infrastructure is engineered to run open-source n8n Community Edition instances with automated backups, 24/7 uptime monitoring, and active execution maintenance. When diagnosing intricate field issues, technical operators can view live n8n logs directly within the management dashboard, making it straightforward to inspect broker disconnections or malformed payload rejections without logging into raw terminal sessions.

If you have existing prototypes running on a local workstation, our built-in migration tool transfers your workflows in seconds. You simply input the API keys and URLs for both installations, and your workflow structures migrate automatically while keeping your security credentials isolated.

Building an Automated Incident Dispatch Branch

Collecting time-series data provides long-term analytics, but physical equipment failures require immediate floor response. To prevent spindle burnouts or hydraulic pump seizures, build an active alerting branch off your normalized telemetry stream.

Insert a Switch node immediately following the Code parsing node. Configure routing rules that inspect real-time tolerances:

  1. Rule 1 (Critical Thermal Limit): Check if {{ $json.temperatureCelsius }} is greater than 85.0.
  2. Rule 2 (Over-Current Event): Check if {{ $json.currentDrawAmps }} is greater than 32.5.
  3. Rule 3 (Internal Fault Flag): Check if {{ $json.faultStatus }} equals true.

When an incoming packet satisfies any critical rule, the workflow routes execution to an HTTP Request node configured to broadcast an incident to your operations center:

POST https://api.pagerduty.com/v2/enqueue
Headers:
  Authorization: Token token=YOUR_API_KEY
  Content-Type: application/json

Payload:
{
  "routing_key": "PLANT_FLOOR_SERVICE_KEY",
  "event_action": "trigger",
  "dedup_key": "motor-cell-04-thermal",
  "payload": {
    "summary": "Thermal alert on machine DEV-104: 89.2°C recorded",
    "severity": "critical",
    "source": "edge-gateway-cell-04",
    "custom_details": {
      "temperature": 89.2,
      "currentDraw": 31.4,
      "operatingEnvelopeMax": 85.0
    }
  }
}

By defining a static dedup_key based on machine identity and fault type, your incident management system aggregates repeat telemetry spikes into a single incident. This prevents on-call engineers from receiving hundreds of duplicate notifications while the motor cools down.

Managing Operational Scale Without Overhead

Industrial systems operate continuously across holidays, shifts, and system updates. Building an edge-to-cloud bridge using low cost n8n hosting allows engineering teams to implement production-grade integrations without the overhead of operating complex custom microservices. Whether you are reading binary Modbus frames from machining centers or aggregating ambient temperature sensors across a cold-storage warehouse, n8n provides the visual visibility and programmatic control needed to handle physical telemetry.

Instead of wrestling with server maintenance, SSL certificate renewals, or database cleanup scripts on self-managed infrastructure, you can launch a dedicated instance with custom domains and automated backups on best n8n hosting platforms designed specifically for continuous automation.

Ready to automate with n8n?

Get affordable managed n8n hosting with 24/7 support.