
Edge-Fog-Cloud Architecture for IoT Stream Analytics
Keep time-sensitive checks on devices or nearby gateways - not on the cloud connection. Use gateways for rolling calculations and outage buffering, and send historical storage, fleet-wide analysis, and model training to the cloud.
For a 20-asset facility sending readings every 5 seconds, that means planning for 4 events per second, local alerts within 1 second of receipt, and 30 minutes of cloud outage buffering. These are design targets to test, not service guarantees.
This guide covers how to:
- Split work across devices, fog gateways, and AWS cloud services.
- Route telemetry, alerts, configuration, and replay traffic.
- Protect stored data and recover from outages without losing acknowledged records.
- Build a Python, MQTT, and AWS IoT Greengrass demo with local state, S3 storage, Athena queries, and dashboards.
- Test latency, duplicates, late data, security, and recovery while targeting less than $25 per month in development costs.
The goal: a system that keeps local checks running offline and can show where each event went, how recovery worked, and what the cloud services cost.
Edge–Fog–Cloud IoT Architecture and Recovery Flow
Edge vs Fog: Cloud Computing Layers Explained
sbb-itb-61a6e59
2. Place Workloads Across Devices, Gateways, and Cloud
Use a placement contract to decide where each workload runs: on a device, gateway, or cloud service. Record its latency target, data scope, CPU and memory budget, outage behavior, retention period, and security classification. Include bandwidth costs and power use. A machine-level check and a fleet-wide comparison call for different placement.
Assign each workload to the narrowest layer that meets its latency, state, and outage requirements.
Assign Validation, Aggregation, and Analytics
Run validation, unit normalization, deduplication, and simple feature extraction on the device. Run urgent inference locally only if it fits the device’s memory, compute, and power limits. Keep threshold checks off the cloud path.
Use gateways for protocol translation, authentication, rolling-window aggregation, cross-sensor correlation, buffering, and local dashboards. These functions should keep working during WAN outages.
Use the cloud for durable ingestion, history, fleet-wide analysis, model training, governance, and deployments as part of your data engineering career path. Cache the last valid configuration locally so a lost connection doesn’t stop site processing. The table below provides a quick placement check.
Compare Placement Options with AWS IoT Greengrass
Compare the contract fields below. Latency targets are illustrative, not guarantees. Measure latency on your hardware, including serialization, queueing, and network delays.
| Layer | Illustrative latency target | Connectivity | Capacity | Data scope | Suitable workloads |
|---|---|---|---|---|---|
| Device | Milliseconds to tens of milliseconds | Can operate disconnected | Limited CPU, memory, storage, and power | Sensor or machine | Validation, deduplication, feature extraction, threshold checks, lightweight inference |
| Fog gateway | Tens to hundreds of milliseconds | Local network; intermittent WAN | More CPU, memory, and storage than devices | Room, line, or facility | Protocol translation, authentication, aggregation, correlation, buffering, dashboards |
| Cloud | Hundreds of milliseconds or longer | WAN required for live ingestion | Elastic and scalable | Fleet and history | Durable ingestion, historical analysis, model training, governance, cross-site analytics |
Greengrass applies the same placement split in a concrete deployment model. On AWS IoT Greengrass, implement these placements with components for filtering, rolling-window aggregation, and local inference. Use Stream Manager to retain and export selected streams to Amazon S3 or Amazon Kinesis Data Streams. Export summaries and anomaly-window raw samples with explicit retention and discard rules.
3. Route Messages, Store State, and Recover from Failures
Route Telemetry, Alerts, and Backfill
After placement, define how each event path routes, stores data, and recovers across the gateway boundary. In the small-facility portfolio system, the gateway controls local delivery, outage buffering, and cloud replay.
Use a gateway-local MQTT broker with separate paths for alerts, telemetry, and backfill. Put alerts and control actions in a high-priority queue and telemetry in a normal queue. Protocol adapters should normalize readings before forwarding them. Gateway validation should check schema versions, timestamps, and payload size.
Give each device its own X.509 certificate. Allow it to publish only to its own telemetry and state topics and subscribe only to its own command topics. Only the authorized control service should publish desired configuration.
MQTT QoS controls delivery - not business priority or correctness. Use retained MQTT messages only for the latest configuration; they don't preserve telemetry history. Backfill needs durable exports, such as Amazon S3 objects or Kinesis replay records, rather than MQTT alone.
These rules turn placement into a working design for routing, buffering, replay, and recovery. The retention periods below are project policies, not MQTT guarantees. Here, + is a subscription wildcard; publishers use actual IDs.
| Event type | Topic or stream | Route | Retention policy | Priority | Destination |
|---|---|---|---|---|---|
| Raw telemetry | facility/+/device/+/telemetry |
Device → gateway → local stream; sample or batch export | 24 hours locally; 30 days in cloud | Normal | Kinesis Data Streams for real-time analytics; S3 for archive |
| Five-minute aggregates | facility/+/aggregate/5m |
Gateway processor → cloud stream | 7 days in stream; 13 months in warehouse | Normal | Kinesis Data Streams and analytical database |
| Alerts | facility/+/alerts |
Device or gateway → alert processor → notification service | 90 days | Critical | Local actuator, operations dashboard, and notification service |
| Desired configuration | facility/+/device/+/config/desired |
Cloud control plane → gateway → device | Until acknowledged or superseded | Critical | Device and device-shadow service |
| Configuration acknowledgment | facility/+/device/+/config/reported |
Device → gateway → cloud | 90 days | High | Device registry and audit store |
| Backfill | facility/+/backfill or manifest in S3 |
Gateway buffer → rate-limited cloud ingestion | 7 days locally; long-term archive in S3 | Low | S3 replay pipeline and historical analytics |
Configure separate Greengrass Stream Manager streams. For each stream, set file persistence, size limits, retention, export priority, and full-buffer behavior. Export aggregates to Amazon Kinesis Data Streams and selected raw batches to Amazon S3.
Base size quotas on event rate, average payload size, and expected outage duration. Protect the stream directory with OS permissions and disk encryption. Changing persistence requires recreating the stream; it can't be changed in place.
Manage Device, Gateway, and Cloud State
With routing defined, assign each state type to the smallest layer that can recover it safely. Keep urgent state on devices, bounded recovery state on gateways, and durable history in cloud databases.
Device memory is fast but volatile. Persist sequence counters and the last applied configuration where supported. Use gateway disk for connectivity records, windows, watermarks, deduplication keys, and checkpoints. Store configuration, audits, and model versions in the cloud, and synchronize history asynchronously.
Use shadows for desired/reported state, telemetry stores for observations, and checkpoints for progress. Cloud configuration should include its version, effective time, expiration, and origin. Reject stale versions, acknowledge applied versions, and refetch on shadow conflicts.
Handle Outages, Replay, and Late Data
Define delivery, ordering, deduplication, and late-data rules before failures occur.
Specify delivery separately for device→gateway, gateway→cloud, and cloud→consumer. Use QoS 1 only when duplicates are acceptable, and require application acknowledgment after a durable write. Include a stable event_id, device and gateway IDs, sequence number, schema version, event time, and ingestion time. Retain source positions with checkpoints.
Don't assume ordering across topics or partitions. Use bounded retries with exponential backoff and jitter, followed by a dead-letter path that carries the payload and failure reason. Coordinate durable state, output, and source-position checkpoints. Make repeated processing idempotent.
Set disk quotas and high-water marks. Preserve alerts, and drop only approved low-value telemetry - never critical records.
Keep local analytics running offline. During recovery, rate-limit traffic below available spare capacity. Replay records with their original timestamps and a replay flag. Disable historical notifications and simulated actions, and deduplicate by event or action ID.
Quarantine records whose clock skew exceeds the threshold, such as 5 minutes for routine telemetry, and record the reason. Define event-time watermarks and allowed lateness, such as 2 minutes for connected sensors. Route later arrivals to revised aggregates or correction processing. Mark missing readings missing, stale, or estimated; never interpolate missing safety measurements.
Test a 15-minute disconnection, restart, full disk, duplicate event, reordered sequence numbers, stale configuration, a record delayed beyond the watermark, and repeated backfill. Record recovery time and duplicate-alert count.
4. Build and Test a Smart-Facility Portfolio Project
Define the Architecture and Event Schema
Apply the placement and routing rules above to one small facility first. Use one gateway and 20 Python sensor simulators, each sending one reading per second. Cycle each simulator through temperature, power, and vibration readings. Before adding another site, make sure you can trace an event from generation to storage.
Telemetry:
Python sensors → local MQTT broker → Greengrass components
├→ SQLite state/outbox
└→ Stream Manager → Kinesis → cloud consumer
└→ S3 raw/curated
└→ Athena
└→ cloud dashboard
Alerts: gateway rules → local dashboard + optional cloud copy
Backfill: persisted outbox → Stream Manager → Kinesis and S3
Configuration: versioned cloud configuration → Greengrass → sensors
Document each component’s boundaries using the table below. Start with S3 and Athena.
| Component | Responsibility and state | Inputs → outputs | Failure behavior |
|---|---|---|---|
| Python simulators | Generate repeatable readings; persist sequence counters | Test configuration → telemetry | Reconnect using original event IDs |
| MQTT broker | Deliver local publish/subscribe messages | Device topics → gateway subscribers | Surface disconnects only |
| Greengrass components | Validate, window, evaluate rules, and route | Telemetry/configuration → aggregates, alerts, exports | Quarantine invalid events; keep local rules running offline |
| SQLite | Store restart-safe local state, pending events, configuration versions, and deduplication keys | Accepted events → pending records | Recover committed transactions |
| Stream Manager | Maintain bounded, persistent export streams | Gateway records → Kinesis/S3 | Buffer and retry within disk limits |
| Kinesis Data Streams | Ingest cloud data with retention | Exported records → consumer | Allow catch-up within retention |
| Cloud consumer | Validate, deduplicate, curate, and persist processing status | Stream records → S3 datasets and dead-letter records | Retry without duplicating curated results |
| Amazon S3 | Store raw history and curated files | Consumer writes → durable objects | Preserve committed objects; retry failed writes |
| Amazon Athena | Run SQL over curated files | SQL + S3 → analytical results | Report failed queries; ingestion continues |
| Local dashboard | Show current alerts and gateway health | Local metrics → facility view | Mark stale data explicitly |
| Cloud dashboard | Show historical trends and KPIs | Query results → historical view | Display last refresh and delayed-data status |
Add model_version, schema_version, and quality_flags to the earlier event envelope. Generate event_id deterministically from gateway, device, and sequence information - or persist a UUID before transmission. Retries must not create logically new events.
Store timestamps in UTC ISO 8601 format, keeping observation time separate from gateway receipt time. Display local U.S. time with its time zone. Store source readings in °C, mm/s, and kW, and convert to U.S. display units only in dashboards. Document flags such as simulated, missing, estimated, late, and replayed.
Build the Pipeline in Testable Stages
Start with schema tests for identifiers, units, timestamps, and sequence continuity. Then verify MQTT delivery and reconnects. Add one-minute gateway windows, SQLite persistence, and a deterministic rule:
Temperature above 85 °F for three consecutive readings.
Keep trained inference optional and separate. Before adding cloud analytics, prove that local alerting, buffering, restart recovery, and replay work.
Next, add raw and curated S3 datasets, Athena queries, and dashboards.
Build security into these stages. Require TLS, protect gateway storage and S3, scope component permissions, and test certificate rotation. Version configuration and model artifacts, then demonstrate rollback.
Add an outbound-field allowlist. Approved measurements may leave the facility; occupant identifiers, badge data, and precise room labels must stay local or undergo an approved transformation. The redaction test should fail whenever a prohibited field reaches an export payload.
Test Reliability, Performance, and Cost
Run repeatable normal-load and failure tests. Record test duration, payload bytes, and clock skew. Measure p50/p95 latency separately for generation-to-local-alert and generation-to-cloud-visibility.
Report throughput, bandwidth reduction, accepted/rejected/lost records, duplicates, late arrivals, restart time, buffer-drain time, and peak disk use. Deliberately test disk exhaustion, too.
For a monthly USD estimate, name the AWS Region and verified pricing date. Calculate ingestion, retrieval, retention, S3 storage, Athena bytes scanned, compute, monitoring, and transfer. Keep assumptions clearly separate from measured charges.
Publish a secrets-free repo with setup, test, and teardown commands, spending safeguards, design notes, routing and state guarantees, results, and an outage demo.
5. Conclusion: Architecture and Delivery Checklist
Use this checklist to review the smart-facility portfolio project before shipping.
- Architecture and placement: Diagram the device → gateway → cloud → replay flow. Include the placement matrix, deployment assumptions, trust boundaries, component ownership, and failure-domain map.
- Events and routing: Check that events include a stable event ID, device and gateway IDs, event type, schema version, timestamps, sequence number, units, quality flags, correlation ID, and firmware or software version. Verify routes, partitioning, ordering, idempotency, retries, dead-letter handling, and retention.
- State and recovery: Check device configuration, gateway buffers and checkpoints, and cloud history and processing state. Document recovery time objectives and recovery point objectives (RPOs). Test gateway restarts, disk exhaustion, cloud outages, duplicates, out-of-order events, delayed backfill, corrupted messages, and checkpoint replay.
- Security: Verify device identities, credential rotation, encryption, least privilege, authorized commands, replay protection, signed updates where supported, and audit logs. Map each control and its owner to the trust boundaries.
- Evidence and cost: Attach reproducible benchmarks and results from outage, replay, late-data, and buffer-limit tests. Report latency, throughput, CPU and memory use, buffer capacity, loss and duplicate rates, recovery time, and replay duration. Compare raw-to-cloud delivery against gateway aggregation and selective raw-data retention. State costs in U.S. dollars and spell out the assumptions behind each estimate.
Document known limits, and make offline operation, recovery, and cost visible in the final evidence. The design is not ready unless a reviewer can trace one event, one recovery path, and one cost estimate from end to end.
FAQs
How do I size gateway storage for outages?
Multiply your average ingestion rate by the longest expected outage, then add a buffer for operational overhead. Source retention must cover the full replay period.
Gateways buffer data in persistent local state stores when they can’t reach the cloud. Track how much those stores grow, and make sure gateway storage capacity supports your Recovery Point Objective (RPO).
When should I move analytics from devices to gateways?
Move analytics from devices to gateways when you need more than on-device filtering: stateful aggregations, joins, or correct event-time window processing. Gateways also make sense when data must be current within seconds, so you need to push updates rather than wait for slower pull or batch cycles.
For real-time tasks involving late or out-of-order events, gateways support watermarks, window triggers, and state management built for recovery. If an hourly batch report meets your needs, keep it in batch.
How can I prevent duplicate alerts during recovery?
Make your sink safe from duplicates with idempotent writes or exactly-once delivery semantics. This prevents replayed events from causing double-counting. Deduplicating identifiers alone isn’t enough: repeated aggregate updates can still produce incorrect results.
Test failures between a sink write and a commit to check that recovery causes no data loss or duplication. For stateful frameworks, use checkpoints to save both progress and state to durable storage so processing can resume consistently.