Design a Consent-Aware Distributed Load-Shedding System
System DesignModel answerLast updated
Design a distributed controller that sheds megawatts of electrical load across millions of smart devices within seconds while honoring user preferences, device safety rules, and fairness.
Context
Power grids are increasingly made up of edge-connected devices — home batteries, EV chargers, heat pumps, and solar inverters. When generation falls short of demand, operators must shed load within seconds to prevent cascading failures. Traditional approaches cut entire neighborhoods without discrimination. Your task is to design a smarter system.
Problem
Design a distributed controller that can reduce electricity consumption by a requested number of megawatts, within a specific geographic zone, within 15 seconds — across a fleet of 10 million connected endpoints — while satisfying a set of hard constraints.
Constraints You Must Respect
User preferences and consent
- Each household has a contractual policy: acceptable temperature swing, minimum EV battery level by a given deadline, and the right to opt out (at a financial penalty).
Protected loads
- Certain circuits must never be curtailed under any circumstances: home medical equipment, refrigeration, and municipal infrastructure like water pumps.
Device physics
- Devices have ramp-down times. HVAC compressors have minimum-off durations that must be respected to avoid hardware damage. Solar and wind output fluctuates.
Fairness
- No household should bear a disproportionate share of curtailment events over time. Disruption must be distributed equitably.
Local autonomy
- Edge gateways must behave safely during internet outages using cached policies, without needing a round-trip to the cloud.
Scale and Performance
- 10 million endpoints, each reporting telemetry every 10 seconds — roughly 1 million events per second at ingestion.
- Commands must reach devices within 5 seconds of a trigger.
- The system must achieve at least 95% of the requested load reduction even when some devices are unreachable or non-responsive.
- No single point of failure anywhere in the stack.
- All curtailment decisions must be logged in a tamper-evident way for billing adjustments and regulatory audits.
What to Cover
- Architecture — How data flows from device to dispatch, what the regional control topology looks like, and how you avoid global bottlenecks.
- Data model and API — Schema for device capabilities, user policies, and the dispatch interface.
- Allocation engine — The algorithm and data structures that select devices under the latency budget.
- Failure handling and trade-offs — Non-responsive devices, network splits, malicious or stale telemetry, and over- or under-shedding.
Hints
Hint 1
You can't run an optimizer over millions of devices at emergency time — think about what work can be done continuously in the background so that dispatch is just a fast read from precomputed state.
Hint 2
Devices that must never be shed (medical, critical infrastructure) are best excluded from the selectable pool by construction, not filtered at runtime. How does that simplify your allocation logic?
Hint 3
Achieving 95% of a target when some devices won't respond is a statistics problem. If each device has a known historical compliance rate, how much do you need to overbook to hit the confidence bound?
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Establish Scale and Constraints First
Ground the design in numbers before touching architecture.
- Ingestion: 10M devices × 1 event/10 s = 1M events/s. At ~200 bytes each, that's ~200 MB/s, or roughly 17 TB/day raw. Roll up to 1-minute aggregates for history.
- Topology: Assume ~2,000 substation zones, ~5,000 homes each. Zone is the natural dispatch and sharding unit.
- Available flex: Roughly 1–3 kW sheddable per home, so ~5–15 GW fleet-wide. A typical event targets 10–200 MW in one zone — meaning 5k–100k devices.
- Latency budget (5 s trigger-to-edge):
- ~0.5 s: detect event, look up zone state
- ~1 s: run selection algorithm
- ~2.5 s: fan out signed commands
- Remaining: network jitter and edge processing
The central insight to state early: the combinatorial work must be done continuously in the background. At dispatch time you do a single greedy sweep of precomputed state. If you try to run a fresh optimizer in the critical path, you lose.
2. Architecture
Devices
└─ Edge Gateway (per home, local policy cache)
└─ MQTT/TLS ──► Regional Broker Cluster
│
Kafka (partitioned by zone_id)
│ │
Flex Aggregator (streaming) TSDB (telemetry history)
│
Zone Flex Index (in-memory, replicated per zone)
│
Grid Operator ──► Dispatch API
└─ Regional Control Plane (active-active, 2 AZs)
│ │
Command fan-out Audit log (hash-chained)
│
Substation SCADA ──► Verification loop (closed-loop top-up)
Regional control planes. Each region owns a shard of zones. A Raft-elected leader per zone shard holds the in-memory flex index; a hot follower replicates it. If a region fails, a standby can reconstruct state from Kafka replay. No global coordinator exists.
Edge protocol. Gateways hold persistent mTLS MQTT 5 connections to regional brokers — long-lived so there's zero connection setup latency at dispatch time. Commands are signed with Ed25519 and carry event_id, kw_target, lease_expiry, and a monotonic sequence number for replay protection. QoS 1 with idempotent processing gives safe at-least-once delivery.
Pre-arming. During forecast stress periods, push fully-specified commands to devices ahead of time. The actual trigger is a tiny per-zone broadcast: FIRE event_id. This is the most reliable way to consistently beat the 5-second budget.
Local fallback. Edge gateways cache the latest signed policy snapshot. During a WAN partition, they apply safe defaults: protect critical and medical circuits absolutely, apply the last-known user preferences, and refuse curtailment beyond the cache's max_tier. The cached policy carries a TTL; expired policies default to critical-only protection.
3. Data Model and API
Device(device_id, home_id, zone_id, feeder_id, type, rated_kw,
ramp_down_s, min_off_s, min_on_s, last_state_change_ts,
critical: bool, attest_key)
UserPolicy(home_id, tier, max_temp_delta_c, ev_min_soc, ev_deadline,
opt_out_until, penalty_rate, medical_flag, version, signed_at)
FlexSlot(device_id, available_kw, available_until, tier,
priority_key, p_comply) -- materialized, in-memory only
FairnessLedger(home_id, decayed_score, last_curtailed_ts, credits)
-- decayed_score = Σ kWh_i · exp(-(now - t_i) / τ), τ ≈ 14 days
CurtailmentEvent(event_id, zone_id, target_mw, requested_by,
authority_ref, tiers_used, status)
DispatchRecord(event_id, device_id, kw_expected, cmd_ts, ack_ts,
kw_verified, hash_prev, hash_self)
Dispatch API — idempotent on event_id:
POST /v1/zones/{zone_id}/curtailments
{ event_id, target_mw, start_at, duration_s, max_tier, authority_ref }
→ 202 { event_id, planned_mw, expected_mw, devices_selected }
GET /v1/curtailments/{event_id} → achieved_mw vs target (live)
POST /v1/curtailments/{event_id}/release → begin staged release
4. Allocation Engine
Background: continuously maintain the flex index
The streaming Flex Aggregator consumes telemetry and recomputes each device's FlexSlot incrementally:
- HVAC: available kW = current draw minus comfort floor, subject to thermal model. Device is ineligible if it's inside its
min_on_swindow. - EV: available kW = headroom above the minimum charge needed to hit the user's deadline.
- Critical, medical, or opted-out devices: excluded from the index by construction. They cannot be selected because they don't exist in the selectable pool.
Zone-level per-tier running totals make "can we serve X MW from tier T?" an O(1) check. Each tier pool is sorted by:
priority_key = (tier, fairness_decayed_score, -p_comply, -available_kw)
Lower fairness score sorts first — recently burdened homes appear last, so the selection naturally rotates disruption across households.
At dispatch: greedy fill with statistical overbooking
def select_devices(zone, target_kw, max_tier, confidence=0.95):
z = 1.65 # ~95th percentile of normal distribution
chosen, mean, var = [], 0.0, 0.0
for tier in range(max_tier + 1):
for slot in zone.pools[tier]: # pre-sorted heap
chosen.append(slot)
p, kw = slot.p_comply, slot.available_kw
mean += p * kw
var += p * (1 - p) * kw * kw
# stop when 95th-pct of expected delivery exceeds 95% of target
if mean - z * (var ** 0.5) >= 0.95 * target_kw:
return chosen
# shortfall: escalate to operator or request adjacent zone assistance
return chosen
p_comply is learned per device from its historical delivery rate. The stopping condition overbooks just enough that the 5th-percentile outcome still meets the 95% reliability target — this absorbs packet loss and non-compliance without blindly over-shedding. Selection cost is O(k) where k is devices chosen; 100k devices runs in single-digit milliseconds.
Apply a per-feeder cap during selection to prevent dropping one feeder's load so abruptly it causes voltage instability downstream.
Why greedy is acceptable
This is a variant of the fractional knapsack problem. When individual items are small relative to the total target (a home's 2 kW against a 50 MW target), greedy is near-optimal. All expensive constraint reasoning — device physics, user policy, fairness — was folded into available_kw and priority_key before dispatch time. The dispatch path only reads.
Closed-loop correction
30–60 seconds after dispatch, compare the expected drop against what substation SCADA actually measures. If there's a shortfall, pull more devices from the pre-sorted queue. If you've overshot, release devices in reverse-priority order (least burdened households first). Stagger releases with ramp-up delays to avoid a sudden load surge that destabilizes the grid in the opposite direction.
5. Failure Modes and Trade-offs
| Failure | Response |
|---|---|
| Device doesn't acknowledge | p_comply decay; closed-loop top-up selects replacements |
| Regional control plane crash | Hot follower takes over; Kafka replay reconstructs flex index |
| WAN partition at edge | Gateway applies cached policy; critical loads always protected |
| Stale or malicious telemetry | Attestation key validates telemetry source; anomaly detection flags outliers; over-reporting flexibility triggers a compliance audit |
| Insufficient zone flex | Escalate to adjacent zones or higher-tier devices; notify operator of shortfall |
Key trade-offs to call out explicitly:
- Pre-arming vs. precision: pre-armed commands use a forecast, so the actual need at trigger time may differ. Closed-loop correction handles this, but adds 30–60 s of lag.
- Overbooking vs. consumer impact: higher confidence targets overbook more devices, increasing disruption to users who end up released. Tune the confidence parameter per tier.
- Fairness vs. efficiency: strict fairness rotation may reach less-flexible devices before more-flexible ones. A small per-tier fairness relaxation (e.g., allow 10% deviation for efficiency) can recover significant MW.
Common mistakes to avoid:
- Running any per-device constraint check in the dispatch hot path.
- Assuming acknowledgment equals compliance — measure at the meter.
- Forgetting device physics: dispatching an HVAC unit that's 30 seconds into a
min_on_scycle can destroy the compressor. - Treating the audit log as best-effort — it must be hash-chained and replicated before the event is considered committed, since it drives billing and regulatory filings.