Digital Twin

Smart City Digital Twin: Traffic, Lighting and Environment over MQTT

How city digital twins combine a geographic model with live traffic, street lighting and environmental sensor data published over MQTT, including topic design, code and a pilot checklist.

Smart city digital twin map showing districts colored by air quality with live traffic flow and street lighting status overlays
Run this on your own MQTT brokerGet a private, managed MQTT broker on the Free plan and start from ready-made code samples.
Try it free Code samples No card required

A smart city digital twin is a live geographic model of a city or district that combines maps and 3D city models with real-time sensor data on traffic, street lighting and the environment. This article explains what city twins are used for, how to structure sensor data on MQTT so many departments and vendors can share it, and how to run a small pilot that proves the concept.

What a Smart City Digital Twin Is

Cities already have plenty of data: traffic counters, street lighting controllers, air quality stations, parking sensors, weather stations and utility meters. The problem is that each system usually belongs to a different department and vendor, with its own dashboard. Nobody sees how they interact.

A city twin layers this data onto a shared spatial model, typically a GIS map or a 3D city model built from open standards such as CityGML. Planners can then ask cross-cutting questions: does air quality on a street improve when traffic is rerouted? Which lighting segments burn at full power on empty roads at night? Where should the next sensors go?

City twins span a spectrum, from a 2D map with live sensor markers to detailed 3D models with simulation. The live data connection is what makes either one a twin rather than a static model. For the underlying concepts, see the digital twin technology guide.

Core Use Cases

Traffic monitoring

Inductive loops, radar, cameras with on-device counting and Bluetooth or Wi-Fi probes provide vehicle counts, speeds and occupancy. The twin shows congestion as it forms and, with history, reveals recurring patterns and the effect of roadworks or signal timing changes. Privacy matters here: publish aggregated counts and speeds, never identities, plates or raw video.

Street lighting

Networked lighting controllers report lamp status, power, dimming level and faults. In the twin, failed lamps appear on the map immediately instead of waiting for citizen reports, and energy consumption can be compared across districts and dimming schedules.

Environment monitoring

Air quality sensors measure particulate matter (PM2.5, PM10), nitrogen dioxide, ozone, temperature, humidity and noise. Low-cost sensors give dense coverage but need calibration against reference stations. The twin combines both, flags hotspots and correlates them with traffic and weather.

Other layers

Parking occupancy, waste bin fill levels, water network pressure, flood sensors and public transport positions all fit the same pattern. Start with two or three layers and add more once the data platform is proven.

Layer Example sensors Typical publish interval Retain state? Privacy concern
Traffic Loops, radar, edge-counting cameras 1 to 5 minutes aggregated Latest aggregate High, aggregate at the edge
Street lighting Lamp controllers On change, plus hourly energy Yes, lamp status Low
Air quality PM, NO2, O3 sensors 1 to 15 minutes Latest reading Low
Noise Sound level meters 1 minute (levels only) Latest reading Medium, never publish audio
Parking In-ground or camera sensors On change Yes Low if no plates

Why MQTT Fits City Sensor Networks

City sensors are numerous, battery- or mains-powered, spread over wide areas and often connected through cellular, LoRaWAN network servers or municipal fiber. MQTT works well in this environment:

  • Devices and gateways connect outbound, so sensors behind cellular NAT need no inbound ports.
  • Small messages and low overhead suit constrained links and devices.
  • Publish/subscribe decouples vendors: the lighting vendor publishes, while the twin, the open data portal and the energy team subscribe independently.
  • Retained messages give every new consumer the latest state of thousands of sensors instantly.

A cloud MQTT broker suits a city program well: departments and vendors in different locations all reach one TLS endpoint, and the city's IT team avoids running broker infrastructure. Plans matter at city scale. ConnectMQ's free Serverless plan is fine for a pilot with up to 25 connections, paid Serverless supports up to 1,000 connections, and Dedicated or BYOC options give an isolated cluster or a deployment inside the city's own cloud account. Many sensor networks also aggregate through a few gateways or network servers, which keeps connection counts modest.

Topic Design for a City Twin

Structure topics by city, domain, district and device:

connectmq/<city>/<domain>/<district>/<device-id>/<data-type>

connectmq/riverton/air/old-town/aq-017/reading
connectmq/riverton/lighting/old-town/lamp-4411/status
connectmq/riverton/traffic/old-town/loop-23/aggregate
connectmq/riverton/parking/harbor/bay-112/status

Include coordinates in a device metadata topic (retained) rather than in every reading:

{
  "deviceId": "aq-017",
  "lat": 41.0151,
  "lon": 28.9795,
  "mountHeightM": 3.5,
  "sensor": "PM and NO2 low-cost unit",
  "calibratedAgainst": "reference-station-2"
}

The twin subscribes to connectmq/riverton/+/+/+/meta to place devices on the map, then to data topics for live values. Domain-first ordering lets each department subscribe to its own branch with one wildcard. For general patterns, see digital twin MQTT.

Hands-On: Simulated Air Quality Sensors on a Live Map

Try the data flow with the free public MQTT broker at broker.connectmq.com. Use simulated values and a unique prefix; the public area is readable by everyone.

A Python script simulating three air quality sensors with metadata:

import json
import random
import time
import uuid

import paho.mqtt.client as mqtt

RUN = "city-a19c"  # change to your own unique id
BASE = f"connectmq/demo/{RUN}/air/old-town"
SENSORS = {
    "aq-017": (41.0151, 28.9795),
    "aq-018": (41.0122, 28.9760),
    "aq-019": (41.0170, 28.9832),
}

client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, client_id=f"aq-sim-{uuid.uuid4().hex[:6]}")
client.connect("broker.connectmq.com", 1883, keepalive=60)
client.loop_start()

for sid, (lat, lon) in SENSORS.items():
    client.publish(f"{BASE}/{sid}/meta", json.dumps({"deviceId": sid, "lat": lat, "lon": lon}), qos=1, retain=True)

while True:
    rush_hour = time.localtime().tm_hour in (7, 8, 17, 18)
    for sid in SENSORS:
        pm25 = max(0.0, random.gauss(28 if rush_hour else 14, 4))
        no2 = max(0.0, random.gauss(45 if rush_hour else 22, 6))
        reading = {"pm25": round(pm25, 1), "no2": round(no2, 1), "unit": "ug/m3", "ts": int(time.time())}
        client.publish(f"{BASE}/{sid}/reading", json.dumps(reading), qos=1, retain=True)
    time.sleep(10)

A browser map (for example with Leaflet) connects over Secure WebSocket and updates markers:

import mqtt from "mqtt";

const base = "connectmq/demo/city-a19c/air/old-town";
const markers = {};
const client = mqtt.connect("wss://broker.connectmq.com:8084/mqtt", {
  clientId: "city-map-" + Math.random().toString(16).slice(2, 10),
  protocolVersion: 5,
});

client.on("connect", () => client.subscribe([`${base}/+/meta`, `${base}/+/reading`]));

client.on("message", (topic, payload) => {
  const [, , , , , id, kind] = topic.split("/");
  const data = JSON.parse(payload.toString());
  if (kind === "meta" && !markers[id]) {
    markers[id] = L.circleMarker([data.lat, data.lon], { radius: 10 }).addTo(map);
  } else if (kind === "reading" && markers[id]) {
    const color = data.pm25 > 25 ? "#d94040" : data.pm25 > 15 ? "#e0a030" : "#3fa34d";
    markers[id].setStyle({ color, fillColor: color }).bindTooltip(`${id}: PM2.5 ${data.pm25} ${data.unit}`);
  }
});

Here map is your Leaflet map instance. The color thresholds are illustrative; use the limits defined by your local air quality guidelines.

Pilot Checklist

  1. Choose one district and two or three data layers with clear owners.
  2. Agree the topic hierarchy and payload schemas with every vendor before installation.
  3. Require vendors to publish over MQTT with TLS (port 8883), or bridge their APIs with a small adapter.
  4. Issue one credential per vendor system or gateway; ConnectMQ binds client IDs to issued credentials and blocks IPs after repeated failed logins.
  5. Aggregate privacy-sensitive data at the edge; never publish personal data.
  6. Persist history with a subscriber feeding a time-series database for planning analysis.
  7. Configure simple threshold alerts, such as PM2.5 above a limit, in the portal or in your own service.
  8. Publish selected, non-sensitive aggregates to an open data portal through a separate subscriber.

Pitfalls

  • Vendor lock-in through proprietary dashboards. Make MQTT publishing to the city's broker a procurement requirement.
  • Uncalibrated low-cost sensors. Co-locate some with reference stations and publish correction metadata.
  • Inconsistent clocks. Require UTC timestamps from every source.
  • Starting with the 3D model. A 2D map with reliable live data is more useful than a beautiful model with stale data.

City twins share many building blocks with the building digital twin and the energy digital twin.

Launch Your Smart City Pilot on ConnectMQ

ConnectMQ is a fully managed MQTT service with TLS, WebSocket access for browser maps and MQTT 5 support. Create a free Serverless broker at app.connectmq.com, no credit card required, and connect your first district's sensors to a live twin.

Frequently Asked Questions

What is a smart city digital twin?

It is a live digital model of a city or district that combines maps or 3D city models with real-time sensor data on traffic, lighting, environment and other infrastructure.

Why use MQTT for smart city sensors?

MQTT is lightweight, works over outbound connections from cellular and LoRaWAN gateways, and lets many departments subscribe to the same sensor data without separate integrations.

How do city digital twins protect privacy?

By aggregating data at the edge and publishing only counts, levels and measurements, never images, audio, plates or personal identifiers.

Can a city digital twin start small?

Yes. A pilot with one district and two or three data layers on a 2D map is a practical start, and more layers can be added once the data platform works.

Related articles

All articles →

Your private MQTT broker is a few clicks away

Create an account, get your broker credentials and connect your first device — no servers to install, patch or scale.