Digital twin technology connects a physical asset to a virtual model that stays in sync with it, so you can see, analyze and eventually predict what the real thing is doing. This guide explains the concepts and types of digital twins, a reference architecture that works, and how to feed a live 3D model with real-time data over MQTT, with code you can run today.
What Is a Digital Twin, Really?
A digital twin is a virtual representation of a specific physical object, process or system that is continuously updated with data from its real counterpart. The three words that matter in that definition are specific, continuously and updated.
- Specific: a twin represents pump number 3 on line 2, not "a pump" in general. A generic CAD model is a design, not a twin.
- Continuously: the link to the physical asset is permanent, not a one-time import.
- Updated: data flows from the asset into the model automatically, typically in near real time.
That distinction matters because the term is often stretched to cover any 3D visualization or any simulation. A detailed simulation of a conveyor that runs on assumed inputs is valuable, but it becomes a twin only when it is driven by the actual conveyor's speed, load and fault states. The digital twin vs simulation article explores that boundary in depth.
The concept is not new. Engineers have long kept physical replicas or detailed models of critical systems to reason about them. What changed is cost: cheap sensors, ubiquitous connectivity, lightweight messaging protocols and browser-based 3D rendering make it practical to give ordinary equipment a living virtual counterpart.
Digital Twin Technology Levels: Model, Shadow, Twin
A useful way to classify digital twin technology is by the direction of data flow between the physical and digital sides.
| Level | Data flow | What it does | Typical example |
|---|---|---|---|
| Digital model | None automatic | Static representation, manually updated | CAD model, plant layout drawing |
| Digital shadow | Physical to digital | Mirrors live state for monitoring and analysis | 3D line view showing machine states and temperatures |
| Digital twin | Physical to digital and back | Mirrors state and can send commands or setpoints | Twin that adjusts a pump setpoint after an operator approves it |
Most successful projects start as digital shadows, because one-way data is easier to secure and validate. The bidirectional step comes later and needs careful controls. Digital twin vs digital shadow covers why that progression is the safe default.
Types of Digital Twins
Twins are also classified by scope. Each scope answers different questions and needs different data.
- Component twin: a single part such as a bearing, motor or valve. Useful for condition monitoring of critical components.
- Asset twin: a complete machine made of components, such as a CNC machine or a robot arm, combining their data into one view.
- System or unit twin: several assets working together, such as a production line, an HVAC system or a packaging cell. This is where bottlenecks and interactions become visible.
- Process twin: an entire process or facility, combining equipment data with production orders, quality and energy. This level supports planning and optimization decisions.
The scopes nest naturally, which is another reason to start small: an asset twin built correctly becomes a building block of a line twin later. For more detail and examples of each scope, read types of digital twins.
Where Digital Twins Deliver Value
The value of a twin comes from shortening the distance between "something is happening" and "the right person understands it". Common applications include:
- Remote monitoring: an engineer can see the state of a line in another building or another country without walking to it or reading raw tags.
- Predictive maintenance: combining vibration, temperature and run hours in the context of the asset makes degradation patterns easier to spot. See digital twin for predictive maintenance.
- Training and onboarding: new operators learn the equipment on a twin that behaves like the real thing, without risk.
- Commissioning and what-if analysis: testing a control change or layout change virtually before applying it.
- Energy optimization: visualizing where energy goes, linked to actual production.
- Buildings and infrastructure: occupancy, HVAC and energy in one spatial model, as in a building digital twin.
For manufacturing specifically, the factory digital twin use case shows how these applications combine on a real shop floor.
A Reference Digital Twin Architecture
Whatever tools you choose, a working twin has five building blocks. Getting the boundaries right between them is what makes a twin maintainable.
1. Physical assets and sensors
Machines, PLCs, sensors and meters produce the raw signals: states, temperatures, speeds, counts, alarms. Older equipment may need retrofit sensors.
2. Edge connectivity
Gateways read native protocols such as Modbus, OPC UA or vendor interfaces, convert values into engineering units and publish them as messages. Microcontrollers such as the ESP32 can publish directly for simple sensors.
3. Real-time messaging backbone
This is where MQTT shines. Every asset publishes to a topic, and every consumer, including the twin, subscribes. A broker decouples the twin from the devices: the 3D model does not need to know how to talk to a PLC, and the PLC does not need to know the twin exists. Two MQTT features fit twins especially well:
- Retained messages store the last value of each state topic, so when a twin opens it immediately shows the current state instead of waiting for the next update. Digital twin state with retained MQTT messages is a full tutorial on this pattern.
- Last Will messages let the broker announce that a device went offline, so the twin can show stale assets clearly instead of displaying frozen numbers as if they were live.
The broker is critical infrastructure for the twin, so many teams choose a hosted MQTT broker rather than operating one themselves.
4. Twin model and state
The twin itself holds the asset hierarchy, the current state of each asset, and relationships between assets. It can be as simple as a JSON object keyed by topic or as formal as a model described in DTDL or the Asset Administration Shell. The digital twin architecture guide compares these approaches.
5. Applications and visualization
Dashboards, 3D scenes, analytics and alerting consume the twin state. A browser-based 3D view built with Three.js or Babylon.js is now a realistic option for most teams, as shown in building a Three.js digital twin.
Real-Time Data: Designing Topics for a Twin
The topic structure determines how easily the twin can find its data. Following the ISA-95 hierarchy keeps it predictable:
acme/plant1/machining/line1/cnc1/state (retained) {"state":"RUNNING"}
acme/plant1/machining/line1/cnc1/telemetry {"spindleTempC":41.2,"rpm":8000}
acme/plant1/utilities/tanks/tank1/level (retained) {"levelPct":63.5}
acme/plant1/utilities/pumps/pump1/command {"setpointRpm":1450}
Each 3D object in the scene maps to one path in this tree, so binding is a lookup rather than custom code per device. ConnectMQ recognizes ISA-95 and Unified Namespace topics and groups devices by those levels in its portal, which makes it easy to check that every asset the twin expects is actually publishing. If part of your plant uses Sparkplug B, ConnectMQ can decode it and republish into ISA-95 topics, so the twin subscribes to one consistent namespace.
Latency is rarely the bottleneck. For visualization, updates once or twice per second per asset feel live to a human. What matters more is consistency: the twin should show the timestamp of each value and mark data as stale when updates stop. Real-time digital twin latency explains where delay actually comes from.
Hands-On: Build a Live 3D Twin Fed by MQTT
The following example builds a minimal twin of a storage tank. A Python script plays the role of the physical tank and publishes its level, and a browser page renders a 3D tank whose fill height follows the data in real time. Both connect to the free public area of broker.connectmq.com.
Step 1: Simulate the physical asset
pip install "paho-mqtt>=2.0"
import json
import math
import sys
import time
import uuid
import paho.mqtt.client as mqtt
TWIN_ID = sys.argv[1] if len(sys.argv) > 1 else uuid.uuid4().hex[:8]
BASE = f"connectmq/demo/{TWIN_ID}/plant1/tank1"
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, client_id=f"tank-sim-{TWIN_ID}")
client.will_set(f"{BASE}/status", "offline", qos=1, retain=True)
client.connect("broker.connectmq.com", 1883, keepalive=30)
client.loop_start()
client.publish(f"{BASE}/status", "online", qos=1, retain=True)
print(f"Twin ID: {TWIN_ID} topic: {BASE}/level")
t = 0.0
while True:
level = 50 + 40 * math.sin(t / 20) # slowly fills and drains between 10 and 90 percent
payload = {"levelPct": round(level, 1), "ts": int(time.time() * 1000)}
client.publish(f"{BASE}/level", json.dumps(payload), qos=1, retain=True)
t += 1
time.sleep(1)
Run it with python tank_sim.py and note the twin ID it prints. The level topic is retained, so the twin will show the latest value the moment it connects.
Step 2: Render the twin in the browser
Create a project with a bundler such as Vite (npm create vite@latest twin -- --template vanilla), install the libraries with npm install three mqtt, and replace main.js with the code below. Set TWIN_ID to the value printed by the simulator.
import * as THREE from "three";
import mqtt from "mqtt";
const TWIN_ID = "replace-with-your-twin-id";
const BASE = `connectmq/demo/${TWIN_ID}/plant1/tank1`;
// Scene setup
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x1e2329);
const camera = new THREE.PerspectiveCamera(50, innerWidth / innerHeight, 0.1, 100);
camera.position.set(4, 3, 6);
camera.lookAt(0, 1, 0);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);
scene.add(new THREE.AmbientLight(0xffffff, 0.6));
const sun = new THREE.DirectionalLight(0xffffff, 1.2);
sun.position.set(5, 8, 5);
scene.add(sun);
// Tank shell (transparent) and liquid (scaled by level)
const HEIGHT = 2;
const shell = new THREE.Mesh(
new THREE.CylinderGeometry(1, 1, HEIGHT, 48, 1, true),
new THREE.MeshStandardMaterial({ color: 0x9aa4ae, transparent: true, opacity: 0.25, side: THREE.DoubleSide })
);
shell.position.y = HEIGHT / 2;
scene.add(shell);
const liquidGeometry = new THREE.CylinderGeometry(0.95, 0.95, HEIGHT, 48);
liquidGeometry.translate(0, HEIGHT / 2, 0); // pivot at the bottom so scaling fills upward
const liquid = new THREE.Mesh(liquidGeometry, new THREE.MeshStandardMaterial({ color: 0x2f80ed }));
scene.add(liquid);
let targetLevel = 0;
let online = false;
// MQTT connection over secure WebSocket
const client = mqtt.connect("wss://broker.connectmq.com:8084/mqtt", {
clientId: `twin-viewer-${Math.random().toString(16).slice(2, 10)}`,
protocolVersion: 5,
});
client.on("connect", () => {
client.subscribe(`${BASE}/#`, { qos: 1 });
});
client.on("message", (topic, payload) => {
if (topic.endsWith("/level")) {
const data = JSON.parse(payload.toString());
targetLevel = Math.min(Math.max(data.levelPct / 100, 0.001), 1);
} else if (topic.endsWith("/status")) {
online = payload.toString() === "online";
liquid.material.color.set(online ? 0x2f80ed : 0x6b7280); // grey when the asset is offline
}
});
// Smoothly animate toward the latest reported level
function animate() {
liquid.scale.y += (targetLevel - liquid.scale.y) * 0.1;
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
animate();
addEventListener("resize", () => {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
});
Start the dev server with npm run dev and open the page. The liquid rises and falls with the simulated tank. Stop the Python script with a hard kill and, once the keepalive expires, the broker publishes the Last Will and the liquid turns grey, which is exactly the stale-data signal a real twin needs.
The same pattern scales to a whole line: one subscription per asset path, one lookup table from topic to 3D object. Binding IoT data to a 3D model covers that mapping for imported GLTF models with many parts. ConnectMQ's own 3D digital twin web demo uses this approach to animate a factory with a CNC machine, robot arm, furnace, tank, conveyor and pump over secure WebSocket.
Remember that the public area of this free public MQTT broker is readable by everyone and limits topics to eight levels, so use it only for simulated data like this. Real plant data belongs on a private broker with credentials.
A Practical Roadmap for Your First Digital Twin
Use this checklist to move from idea to a twin people actually use:
- Choose one asset with a real question attached. "Why does this pump trip every few weeks?" is better than "twin the whole plant".
- Decide the level. Start as a digital shadow; add commands only after the monitoring view is trusted.
- List the signals the twin needs and confirm each one can be read reliably.
- Define topics and payloads following ISA-95, with retained state and a status topic per asset.
- Prototype with simulated data on a public test broker to build the visualization in parallel with the device work.
- Connect real devices to a private broker over TLS with per-device credentials.
- Add context: thresholds, units, maintenance history and stale-data indication.
- Measure usage. If operators and engineers do not open the twin, find out what question it fails to answer.
The how to build a digital twin guide expands each step, and the digital twin maturity model helps you plan what comes after the first success.
Common Pitfalls to Avoid
- Starting with the 3D model. A beautiful scene with unreliable data loses trust fast. Get the data pipeline right first.
- Point-to-point device connections. A twin that polls each device directly does not scale and creates a second integration for every consumer.
- Hiding staleness. Always show when a value was last updated and mark offline assets.
- Bidirectional control too early. Commands from a twin need authorization, confirmation and limits. Keep safety functions in the PLC, never in the twin.
- Locking into one vendor's model format before you know your requirements. Compare options in open-source digital twin tools.
Run Your Digital Twin on ConnectMQ
A digital twin is only as good as its live data feed. Create a free account at app.connectmq.com on the Serverless plan, no credit card required, create a broker and use the generated username, password and client ID for your devices and your twin viewer. Browsers connect over secure WebSocket on port 8084 at path /mqtt, and devices use TLS on port 8883. When you need more connections or an isolated environment, move to a cloud MQTT broker plan without changing your topics or code.
Frequently Asked Questions
What is the difference between a digital twin and a 3D model?
A 3D model is a static representation. It becomes part of a digital twin only when it is linked to a specific physical asset and continuously updated with that asset's live data.
Why is MQTT a good fit for digital twin technology?
MQTT decouples devices from the twin through publish/subscribe, retained messages give the twin the current state instantly when it opens, and Last Will messages reveal offline assets. It is lightweight enough for microcontrollers and works in browsers over WebSocket.
Do I need a commercial platform to build a digital twin?
No. Many effective twins are built from open components: an MQTT broker, a small state model and a browser-based 3D library such as Three.js. Commercial platforms add modeling and integration features that matter mainly at larger scale.
Can a digital twin control the physical asset?
It can, if it sends commands back through the messaging layer, but this should come after the monitoring view is proven. Commands need authorization and confirmation, and safety-critical logic must remain in the PLC or controller.
Can I test the 3D example without an account?
Yes. The example uses the public area of broker.connectmq.com, which accepts anonymous connections with any unique non-empty client ID. Use only simulated or non-sensitive data there, since the public area is readable by everyone.



