Low Level Design: Smart Home System

Home Hub Architecture

The home hub is the central controller for all smart home devices in a physical residence. Deployed as a dedicated hardware device (purpose-built or running on a Raspberry Pi 4 or equivalent), it connects to IoT devices via short-range wireless protocols (Zigbee, Z-Wave, Thread, WiFi) and to the internet via the home’s router. The hub exposes a local HTTP/WebSocket API on the LAN for direct app control and runs a local automation engine for low-latency rule execution.

The hub architecture has two processing planes. The local plane handles device command/control, state persistence, and automation execution entirely within the home network. Commands issued from the local app reach devices in under 100ms regardless of internet connectivity. The cloud plane handles remote access (when the user is away from home), long-term history storage, cross-home automation, and voice assistant integration. The hub maintains a persistent outbound connection to the cloud (MQTT over TLS or WebSocket) for bidirectional relay.

On internet outage, the hub continues to operate fully for local app control and scheduled automations. Cloud-dependent features (remote access, voice assistants) degrade gracefully with an offline indicator. The hub buffers state change events during outages and replays them to the cloud on reconnection to maintain audit trail consistency.

Device Registry

The hub maintains a local SQLite database with a devices table: device_id (UUID generated at pairing), name (user-defined), type (light, switch, thermostat, lock, sensor, plug, camera), protocol (zigbee, zwave, matter, wifi), capabilities (JSON array of capability identifiers), current_state (JSON object of capability → current value), room_id, manufacturer, model, firmware_version, paired_at, last_seen.

Capabilities are typed interfaces. Examples: on_off ({value: bool}), brightness ({value: int 0-100}), color_temperature ({value_kelvin: int}), hue_saturation ({hue: float, saturation: float}), temperature_sensor ({value_celsius: float}), lock ({locked: bool, last_changed_by: string}), motion_sensor ({motion_detected: bool, last_triggered: timestamp}).

The current_state JSON is updated on every state report from the device and on successful command execution. For high-frequency sensors (temperature, power consumption), state is written to a separate time-series table rather than overwriting the current_state column, keeping the devices table lightweight. The hub syncs the full device registry to the cloud on startup and on any change, enabling remote clients to know the full device list and current states without querying the hub directly.

Device Control Protocol

Matter (formerly Project CHIP) is the unified smart home standard backed by Apple, Google, Amazon, and Samsung. It runs over WiFi, Thread (a low-power mesh protocol), and Ethernet. Matter devices expose a cluster-based attribute model: each device has a set of clusters (analogous to capability interfaces), each cluster has attributes (readable state), commands (writable actions), and events (state change notifications).

The hub acts as a Matter controller. To set a device capability: the hub sends a Matter WriteAttribute or InvokeCommand to the device’s IP address (WiFi) or via the Thread border router. Example: turn on a light by invoking the On command on the On/Off cluster. The hub subscribes to attribute changes via Matter’s subscription mechanism (similar to CoAP observe): the device pushes state change reports to the hub without polling. Report interval is configurable: minimum 1 second, maximum 60 seconds, with immediate reporting on change.

For legacy protocols (Zigbee, Z-Wave), the hub runs protocol-specific coordinators. Zigbee devices communicate via a Zigbee coordinator chip on the hub; the hub’s software translates between Zigbee cluster library commands and the internal capability model. Z-Wave uses a similar translation layer. This abstraction means the automation engine and app API deal only with the unified capability model, not protocol specifics.

Automation Rules Engine

Automation rules are the intelligence layer of the smart home. Each rule has: a set of triggers, an optional set of conditions, and a list of actions. Triggers are events that cause the rule to be evaluated: a device state changes (e.g., motion sensor detects motion), a schedule fires (e.g., every day at 7am), a location event occurs (user arrives home, user leaves home), or sunrise/sunset (computed from configured home coordinates and date).

Conditions are evaluated at the moment the trigger fires to determine if actions should execute. They form an AND/OR tree of checks: device state comparisons (thermostat_temperature < 68), time range checks (between 10pm and 6am), day-of-week checks, and presence checks (any household member home). If all conditions pass, actions execute in sequence.

Actions include: set device state (turn on/off, set brightness, lock/unlock), send notification (push to user’s phone), activate a scene (see next section), wait N seconds (for sequenced lighting effects), and run another automation (for reusable automation subroutines). Actions that modify device state trigger the normal device command path, which may in turn fire more triggers—cycles are prevented by tracking the automation invocation chain and skipping rules already in the current chain.

Rules are stored in JSON in the hub’s local database and synced to the cloud. The evaluation engine runs in a dedicated thread on the hub, listening to the internal event bus for device state changes and schedule events. Rule evaluation latency from trigger event to action execution is typically under 50ms for local rules, keeping automations feeling instantaneous.

Scene Management

A scene is a named snapshot of desired device states, typically covering multiple devices in a room or the whole home. Example: "Movie Night" scene sets living room lights to 20% warm white, closes smart blinds, and turns on the TV input. Scenes are stored as a list of (device_id, capability, target_value) tuples in the scenes table on both hub and cloud.

Activating a scene sends all constituent device commands in parallel (not sequentially) to minimize the time between the first and last device reaching its target state. The hub tracks acknowledgment from each device and reports partial success if some devices fail to respond. A scene can have a transition duration for lights (fade over N seconds) which is passed as a parameter in the Matter command.

Scene activation can be triggered by app, voice command, automation rule, or physical button (a smart button assigned to a scene). The hub stores the last 10 activated scenes for quick recall and displays them on the app’s home screen. Users can save the current state of all room devices as a new scene with a single tap ("capture current state"), making scene creation intuitive without manual configuration of each device.

Voice Assistant Integration

Integration with Alexa, Google Home, and Apple Home follows a cloud-to-cloud model. The user links their smart home account to their voice assistant account via OAuth. When the user speaks a command ("Alexa, turn off the kitchen lights"), the voice assistant’s cloud service parses the intent and makes an HTTPS call to the smart home cloud API using the user’s OAuth token.

The smart home cloud API receives the command, looks up the target device and hub for the user, and relays the command to the hub via its persistent MQTT connection. The hub executes the command locally and sends a state update back. The cloud API returns the result to the voice assistant cloud, which synthesizes a verbal confirmation ("OK, kitchen lights are off"). The full round trip typically takes 500ms-1.5 seconds.

Apple HomeKit uses a different architecture: HomeKit’s local control path communicates directly with the hub over the LAN using HomeKit Accessory Protocol (HAP) when the phone is on the same network, bypassing the cloud entirely for sub-100ms response. Remote access via Siri routes through an Apple Home Hub (HomePod or Apple TV) which acts as a bridge, maintaining a persistent connection to Apple’s iCloud relay.

Device discovery is handled by each platform’s "smart home skill" or "action": on account link, the smart home cloud API returns the full device inventory with capability metadata, allowing Alexa/Google/Apple to build their own device models. On device add or remove, the smart home system sends a proactive discovery update to keep the voice assistant’s model in sync.

Security Considerations

All communication between the hub and cloud uses TLS 1.3. The hub authenticates to the cloud using a client certificate issued at manufacture time and rotatable via a secure provisioning API. User app-to-cloud communication uses short-lived JWT tokens with refresh tokens stored in the device’s secure enclave.

Device onboarding (pairing a new device) uses Matter’s onboarding QR code flow: the device’s QR code encodes a discriminator and passcode. The hub scans the code (or the user enters the 8-digit code manually), performs a PASE (Password Authenticated Session Establishment) handshake to set up a secure channel, then commissions the device with operational credentials. This prevents rogue devices from being added to the home network without physical access.

Zigbee and Z-Wave devices use network-layer encryption with a network key distributed by the hub coordinator. The network key is generated fresh per home and stored in the hub’s secure storage. Devices joining the Zigbee network receive the key via an encrypted join process. The key can be rotated by the hub, though this requires rejoining all devices.

Remote access is gated by cloud authentication. Even if an attacker knows a hub’s cloud identifier, they cannot issue commands without a valid user token. The hub rejects commands that don’t arrive via its authenticated cloud connection. Local LAN access is restricted by the home router’s firewall—no inbound ports are opened; the hub always initiates outbound connections.

Energy Monitoring

Smart plugs with energy monitoring and smart meters report power consumption in real time: watts (instantaneous) and kWh (cumulative). The hub collects these readings via the Matter Electrical Measurement cluster or Z-Wave meter command class and stores them in a local time-series table: energy_readings with columns device_id, timestamp, watts, kwh_cumulative. Readings are downsampled for storage: raw 1-minute data retained for 7 days, hourly aggregates for 1 year, daily aggregates indefinitely.

The cloud aggregates energy data across all devices for a home and provides a per-device consumption breakdown via the app. A background job computes daily kWh per device and stores it in a daily_energy table. The app displays a treemap of consumption share per device, flagging devices that exceed their historical average by more than 20% as anomalies.

Integration with utility APIs (where available, e.g., Green Button standard in the US) allows the system to fetch time-of-use electricity pricing schedules. The automation engine can use this data to shift discretionary loads (EV charging, dishwasher, water heater) to off-peak hours via scheduled automations, and can display estimated monthly cost based on current consumption patterns and rate schedules.

{ “$schema”: “https://schema.org”, “@context”: “https://schema.org”, “@type”: “FAQPage”, “mainEntity”: [ { “@type”: “Question”, “name”: “What are the trade-offs between a local hub and a cloud-only architecture for a smart home system?”, “acceptedAnswer”: { “@type”: “Answer”, “text”: “A local hub (e.g., Raspberry Pi or dedicated appliance) processes device commands and automation rules on the LAN, providing sub-100ms latency, continued operation during internet outages, and reduced cloud costs. Its drawbacks are hardware maintenance, limited compute for complex ML workloads, and harder remote access setup. A cloud-only architecture offers zero on-premise hardware, easy remote access, and elastic compute, but introduces 200–800ms round-trip latency, full dependency on internet connectivity, and ongoing subscription costs. A hybrid design is best: the local hub handles time-critical automations and local device control while the cloud handles remote access, voice AI, firmware OTA, and cross-home analytics.” } }, { “@type”: “Question”, “name”: “What is the Matter protocol and what advantages does it offer over proprietary smart home protocols?”, “acceptedAnswer”: { “@type”: “Answer”, “text”: “Matter is an open-source, IP-based smart home standard developed by the CSA (Connectivity Standards Alliance), supported by Apple, Google, Amazon, and Samsung. It runs over Wi-Fi and Thread (a low-power mesh protocol) and uses IPv6 end-to-end. Advantages over proprietary protocols: devices from any Matter-certified manufacturer work with any Matter controller without a proprietary bridge, eliminating ecosystem lock-in. The protocol is locally operable (no cloud dependency for basic control), uses certificate-based device attestation for security, and supports multi-admin so a single device can be controlled by multiple ecosystems simultaneously. This reduces fragmentation compared to Zigbee, Z-Wave, and vendor-specific protocols like Philips Hue’s original bridge API.” } }, { “@type”: “Question”, “name”: “How do you design an automation rules engine with local execution for a smart home system?”, “acceptedAnswer”: { “@type”: “Answer”, “text”: “Represent automation rules as event-condition-action (ECA) triples serialized as JSON and synced to the local hub. The rules engine on the hub subscribes to a local MQTT or Matter event bus. On each device state change event, evaluate matching rules: check trigger (e.g., motion sensor active), evaluate conditions (time window, other device states) using a simple expression evaluator, and dispatch actions (turn on light, lock door) to device drivers. Use a dependency graph to order rule evaluation and prevent cycles. Persist rule state (e.g., ‘light was already on’) locally in SQLite. Sync rule changes from the cloud config service on reconnect. Execution never requires a cloud round-trip.” } }, { “@type”: “Question”, “name”: “How do you integrate a voice assistant into a smart home system via cloud smart home APIs?”, “acceptedAnswer”: { “@type”: “Answer”, “text”: “Implement a smart home cloud-to-cloud (C2C) integration: expose an OAuth 2.0 authorization endpoint so users link their account. Register your device schema with the voice platform (Google Home Graph API, Amazon Alexa Smart Home Skill, or Apple HomeKit via HAP). When the voice assistant receives a command, it calls your fulfillment webhook with an intent payload (e.g., action.devices.EXECUTE for Google). Your webhook translates the intent to a device command, sends it to the local hub via a persistent MQTT connection or server-sent events tunnel, and returns a sync response. Maintain a device state cache in the cloud for QUERY intents to avoid round-tripping the hub on every state poll. Handle hub-offline gracefully by returning cached state with a stale flag.” } }, { “@type”: “Question”, “name”: “How do you secure IoT devices and implement network isolation in a smart home system?”, “acceptedAnswer”: { “@type”: “Answer”, “text”: “Segment IoT devices onto a dedicated VLAN or Wi-Fi SSID with firewall rules blocking lateral movement to the main LAN and disallowing inbound internet connections. All cloud communication is outbound-only from the hub (HTTPS/MQTT over TLS). Use per-device X.509 certificates provisioned at manufacturing (Matter’s device attestation) for mutual TLS to the cloud broker. Rotate credentials via OTA without re-pairing. On the hub, run device drivers in sandboxed processes with minimal OS privileges. Disable UPnP. Apply automatic firmware updates for security patches. Monitor anomalous traffic (unexpected outbound IPs, high byte counts) via the hub’s network monitor and alert the user. Revoke compromised device certificates without affecting the rest of the fleet.” } } ] }
Scroll to Top