System Design Academy

Saving…

Lesson 6 of 7 in Module 50 of 45 lessons complete

Smart-Home Automation Rules Engine — Part A: Design

Module 5, lesson 6Case study15 min

Definitions

Rule

In plain English
A rule is a user instruction that says when something happens, if checks pass, perform an action.
Think of it like
It is like a standing order at a bank.

Trigger, condition and action

In plain English
A trigger starts a rule, a condition checks whether it should run, and an action performs the requested change.
Think of it like
It is like turning on the porch light when the doorbell rings after ten at night.

The brief

In smart-home, users connect lights, thermostats, locks and sensors. A hallway motion rule after 22:00 sets a light to 30 percent.

What it must do

  • Register devices from different vendors and receive their events.
  • Match one trigger, combine conditions with AND, OR and NOT, then run actions.
  • Load rules from JSON and evaluate them when matching events arrive.
  • Run scenes with several actions and undo successful actions in reverse order.

How well it must do it

  • Protect device control while events are processed concurrently.
  • Add vendor, condition and action types without changing the engine loop.
  • Log failed actions and continue with other actions and rules.

Out of scope

  • Mobile apps and cloud sync.
  • Real device protocols and persistent rule storage.

Design walkthrough

Entities and responsibilities

TypeResponsibility
EventCarry the device and event kind.
Device and DeviceAdapterExpose safe operations while hiding vendor APIs.
ConditionAnswer whether a rule may run.
ActionExecute a change and remember how to undo it.
RuleCombine trigger, condition and action constructors.
EngineRead events and isolate action errors.
SceneKeep successful commands for reverse-order undo.

Start with fake lights. The same boundaries can later support other devices through smaller capability interfaces.

Class diagram

Rules use Condition and Action; TimeAfter, DeviceState, And, Or and Not implement Condition; actions use DeviceAdapter.

Condition wrappers share one interface.

Rules use Condition and Action; TimeAfter, DeviceState, And, Or and Not implement Condition; actions use DeviceAdapter.

And and Or contain lists of Conditions. Not wraps one Condition. Vendor adapters expose a narrow interface without leaking brand-specific methods.

Action has Execute and Undo methods. A scene contains actions and records the successful executions; the build shows both interfaces.

Core flow: motion to light

A motion event passes trigger and condition checks, then each action runs; failures are logged while processing continues.

An action failure does not stop later work.

A motion event passes trigger and condition checks, then each action runs; failures are logged while processing continues.

Choose one engine goroutine to own rule execution and command history. Device adapters still lock because other callers can control devices concurrently.

Type skeleton

event.go — Inject the current time and occupancy view.
Go
package home

import "time"

type Event struct{ DeviceID, Kind string }
type Clock interface{ Now() time.Time }
type Context struct {
	Clock    Clock
	Occupied func() bool
}

Conditions ask questions. They do not change devices, so wrappers can combine them without adding side effects.

condition.go — Small condition values compose through one method.
Go
package home

type Condition interface{ Match(Context) bool }
type TimeAfter struct{ Hour, Minute int }
type DeviceState struct {
	Device Light
	Level  int
}
type And []Condition
type Or []Condition
type Not struct{ Inner Condition }

Commands and rule structure

Scene holds Actions; SetLevel implements Execute and Undo through Light, implemented by two vendor adapters.

Scene commands share a vendor-independent capability.

Scene holds Actions; SetLevel implements Execute and Undo through Light, implemented by two vendor adapters.

action.go — A light reports the previous value during a change.
Go
package home

type Light interface {
	Level() int
	SetLevel(int) (int, error)
}
type Action interface {
	Execute() error
	Undo() error
}
type SetLevel struct {
	Device           Light
	Target, Previous int
	Done             bool
}
type Scene struct {
	Actions []Action
	History []Action
}

Create a fresh command for each rule execution. Sharing one mutable Undo record across executions would overwrite its history.

rule.go — Factories provide fresh action instances.
Go
package home

type Rule struct {
	DeviceID, Trigger string
	When              Condition
	Actions           []func() Action
}
type Engine struct {
	Events  <-chan Event
	Rules   []Rule
	Context Context
}

Design decisions

How do vendor devices fit one interface?

Our choice

Create an Adapter per vendor behind a narrow Light capability.

Why not the alternatives

  • Put vendor switches in every actionEvery action would need edits for a new brand.

How do users combine conditions?

Our choice

Compose And, Or and Not through Condition.

Why not the alternatives

  • One giant condition struct with flagsFlag combinations become hard to validate and extend.

How are actions represented?

Our choice

Use Commands with Execute and Undo; scenes retain their successful commands.

Why not the alternatives

  • Keep only the final target levelThe scene could not restore the level before its action.
Builds onCommand

How do events reach the engine?

Our choice

Use a buffered channel and one engine goroutine; lock each adapter.

Why not the alternatives

  • Let every caller mutate vendor state directlyConcurrent reads and writes would race.

How are rules built from JSON?

Our choice

Use constructor maps keyed by type names.

Why not the alternatives

  • Decode into one hard-coded condition switchNew types would repeatedly change the decoder.
Builds onFactory

Trade-offs

Pros

  • New types plug into existing boundaries.
  • Users can compose checks.
  • Successful scene actions can be undone.

Cons

  • Many small types need names.
  • JSON needs validation.
  • Conflicting rules require an explicit policy.

Use when

  • User-configurable behaviour.
  • Multiple vendors with different APIs.

Avoid when

  • A small fixed set of behaviours.
  • Rules needing transactional rollback across real devices.

Quick check

Which pattern lets AND/OR/NOT combine any conditions, including future ones?
Why model actions as commands with Undo?

Takeaways

  • Adapters hide vendors; conditions compose; actions are undoable commands.
  • A factory registry turns JSON into rules.
  • Keep the engine loop independent of new types.

Try the quick check above whenever you feel ready.

Previous: Hospital ER Triage & Bed Allocation — Part B: Build