Software beside a store camera or in a haul truck cab lives with a network that vanishes for minutes, a clock nobody checks, power that can cut out mid-write and nobody on site to restart it. The usual failure is not the model. It is an event detected correctly and then lost, sent twice or delivered out of order, or an agent that has quietly stalled while the dashboard shows green.
Our position: an edge agent is a small distributed system and deserves the same discipline. Decide locally. Commit every outgoing event to a durable local outbox in the same transaction as the state that produced it. Deliver at least once with idempotency keys so the server stores each event exactly once, and make health signals precise enough to say which part broke. Anything that must happen within seconds, such as an alarm for a driver falling asleep, must not depend on the network.
We draw on two prototypes: Store & Workforce Vision, a per-store edge box for camera analytics, and Mining Fatigue Guard, a cab agent for open-pit haul trucks. Both run on synthetic data and neither has had a field pilot, so we say where they stop. A runnable SQLite outbox is tested against a fault-injecting fake server.
Decide locally and send events, not video
The bandwidth budget settles most debates early. An illustrative 1080p H.264 stream at 4 Mbit/s is 4 × 86,400 / 8 = 43,200 MB, about 43 GB a day per camera, or roughly 346 GB a day for an eight-camera store. A thousand 2 KB events a day (also illustrative) come to 2 MB, five orders of magnitude less.
Both prototypes follow that arithmetic. On the store box, raw recordings stay local under MediaMTX with 14-day retention, and only events, metrics and blurred 20-second clips leave; privacy masks are filled black before any model sees a frame. In the cab no frame leaves at all: an event carries measurements and a 12-second trace of eye closure and head angles at 5 Hz, and a snapshot travels only when site policy allows it. The default policy is off.
Where the alarm lives matters more than bandwidth. The cab agent sets its alarm output on the same frame an alarm-level condition appears, before anything is written to disk; delivery runs on a separate thread that shares only the SQLite file and two single-value slots with the frame path. A pit network outage delays the control room, never the cab alarm. The store system sends alerts from the backend through Telegram, WhatsApp, e-mail or webhooks, which suits a long queue but not a safety alarm. Our rule: if the person who must act is next to the device, the device sounds the alarm.
The store outbox ranks what it carries, and the ranking decides what survives a full disk.
| Message | Path when offline | Store priority | Under disk pressure |
|---|---|---|---|
| Events and their media | Outbox | 0 | Dropped last; kept seven times longer than the age limit |
| Device and camera health | Outbox (store); direct, latest only (cab heartbeat) | 1 | Dropped before events |
| Metrics, visits, crossings, tables | Outbox | 2 | Dropped before health |
| Heatmaps | Outbox | 3 | Dropped first |
| Live view and live state | Never queued | n/a | Lost while offline, by design |
Commit the event in the same transaction as the state
The transactional outbox exists because sending after a commit loses the event if the process dies in between, and sending before the commit announces something that may roll back. A device has the same gap between local state (an episode that just opened) and the uplink, and the same fix: write the outgoing message in the transaction that changes the state, and let a separate loop deliver it.
import json
import random
import sqlite3
import uuid
SCHEMA = """
CREATE TABLE IF NOT EXISTS episode (id TEXT PRIMARY KEY, kind TEXT, state TEXT, occurrences INTEGER);
CREATE TABLE IF NOT EXISTS outbox (
seq INTEGER PRIMARY KEY AUTOINCREMENT, -- never reused, so it doubles as the event sequence
idem_key TEXT NOT NULL UNIQUE, -- minted once, sent on every retry
ordering_key TEXT, -- the episode: its events leave in seq order
priority INTEGER NOT NULL, -- 0 = critical, drained first
payload TEXT NOT NULL,
attempts INTEGER NOT NULL DEFAULT 0,
next_attempt_at REAL NOT NULL);
CREATE TABLE IF NOT EXISTS dead_letter (seq INTEGER PRIMARY KEY, idem_key TEXT, payload TEXT);
"""
def open_db(path: str) -> sqlite3.Connection:
db = sqlite3.connect(path, isolation_level=None) # autocommit; we issue BEGIN ourselves
db.execute("PRAGMA journal_mode=WAL")
db.execute("PRAGMA synchronous=FULL") # sync the WAL on every commit: power can go at any time
db.executescript(SCHEMA)
return db
def record_episode(db: sqlite3.Connection, episode_id: str, kind: str, state: str, now: float) -> None:
"""The local state change and the event announcing it commit together, or not at all."""
db.execute("BEGIN IMMEDIATE")
try:
db.execute(
"INSERT INTO episode VALUES (?, ?, ?, 1) ON CONFLICT(id) DO UPDATE "
"SET state = excluded.state, occurrences = occurrences + 1",
(episode_id, kind, state),
)
payload = json.dumps({"episode_id": episode_id, "kind": kind, "state": state, "occurred_at": now})
db.execute(
"INSERT INTO outbox (idem_key, ordering_key, priority, payload, next_attempt_at)"
" VALUES (?, ?, ?, ?, ?)",
(str(uuid.uuid4()), episode_id, 0 if kind == "microsleep" else 1, payload, now),
)
db.execute("COMMIT")
except BaseException:
db.execute("ROLLBACK")
raise
Four details carry most of the weight.
- Mint the idempotency key at enqueue, not at send. A key generated per attempt makes every retry look new. Both prototypes store the key with the row and reuse it on every retry
synchronousis a durability decision. In WAL mode withNORMAL, SQLite skips the sync on commit, so the newest transactions can roll back after a power loss. The cab usesFULLbecause a truck can lose power at any moment; the store box usesNORMALand accepts that small windowAUTOINCREMENTkeeps the sequence monotonic. A plainINTEGER PRIMARY KEYmay reuse a deleted row's id, so an outbox that drains to empty could restart its numbering. The cab keeps a separate counter table for the same reasonBEGIN IMMEDIATEtakes the write lock up front, so neither thread discovers a lock conflict halfway through a transaction
The store box adds two defences we recommend everywhere. It runs PRAGMA quick_check on open and moves a corrupt database aside instead of crash-looping, and a full disk triggers an emergency retention pass. Its outbox is bounded by default to 24 hours and 2,048 MB, so a long outage sheds the least important data first.
Drain at least once and settle only on a definite answer
The delivery loop sends due rows with their keys and settles each row by the answer for that row. A timeout is not a "no": the server may have stored the batch and lost the response, so the only safe reaction is to retry with the same keys.
BASE_S, CAP_S = 1.0, 300.0
def backoff(attempts: int, rng: random.Random) -> float:
ceiling = min(CAP_S, BASE_S * 2 ** (attempts - 1))
return ceiling / 2 + rng.uniform(0, ceiling / 2) # equal jitter: never an instant retry
DUE = """
SELECT o.seq, o.idem_key, o.payload, o.attempts FROM outbox o
WHERE (o.next_attempt_at <= :now OR o.next_attempt_at > :now + :cap) -- clock stepped back
AND NOT EXISTS (SELECT 1 FROM outbox p WHERE p.ordering_key = o.ordering_key AND p.seq < o.seq)
ORDER BY o.priority, o.seq LIMIT :limit
"""
def drain_once(db: sqlite3.Connection, send, now: float, rng: random.Random, limit: int = 50) -> int:
batch = db.execute(DUE, {"now": now, "cap": CAP_S, "limit": limit}).fetchall()
if not batch:
return 0
envelopes = [{"key": key, "seq": seq, **json.loads(p)} for seq, key, p, _ in batch]
try:
results = send(envelopes) # {idem_key: "accepted" | "duplicate" | "rejected"}
except (ConnectionError, TimeoutError):
results = {} # no answer is not a "no": the server may have stored the batch
db.execute("BEGIN IMMEDIATE")
for seq, key, payload, attempts in batch:
status = results.get(key)
if status == "rejected":
db.execute("INSERT INTO dead_letter VALUES (?, ?, ?)", (seq, key, payload))
if status in ("accepted", "duplicate", "rejected"):
db.execute("DELETE FROM outbox WHERE seq = ?", (seq,))
else:
next_at = now + backoff(attempts + 1, rng)
db.execute(
"UPDATE outbox SET attempts = ?, next_attempt_at = ? WHERE seq = ?", (attempts + 1, next_at, seq)
)
db.execute("COMMIT")
return len(batch)
The backoff mirrors the cab agent: equal jitter, half of each exponential step fixed and half random, capped at five minutes. With a 1-second base the cap applies from the tenth attempt. Without jitter, a fleet that regains coverage together retries in lockstep and hits the server as one burst.
Settlement in the cab is deliberately conservative. accepted and duplicate settle an event; rejected moves it to a dead letter kept on the device. Timeouts, 5xx, 408 and 429 keep the batch for a retry, and so do 401 and 403, because a provisioning mistake must not cost events. A 400, 413 or 422 halves the batch, and only a single event still refused is dead-lettered.
Two ways to keep order
An event's opened, updated and closed messages must not be applied out of order. The prototypes solve this at opposite ends.
| Hold back at the sender (store box) | Sequence numbers, order-insensitive server (cab) | |
|---|---|---|
| Mechanism | A row waits while an older row with the same ordering key is queued | The server rebuilds each alert from all its events in the cab's sequence order |
| Guarantee | Messages leave strictly in order per event | Duplicates and reordered arrivals give the same alert |
| Cost | Head-of-line blocking per event | The server stores every event and recomputes on arrival |
| Server guard | A closed event never regresses | A unique constraint stores each key once |
Whichever you choose, do not rely on the broker alone. The store box publishes to NATS JetStream with the message id as Nats-Msg-Id, but its de-duplication window is two hours while the outbox holds data for 24 hours and events longer. After a long outage, duplicates outside the window reach the backend, and only its idempotent upsert by event id keeps them harmless. Broker de-duplication is an optimisation; consumer idempotency is the guarantee.
Three clocks, three jobs
Edge code that uses one clock for everything eventually produces nonsense. We use three.
- Monotonic time for durations and staleness. It cannot go backwards and ignores clock updates. The store box's
/healthzmeasures time since the last pipeline tick withtime.monotonic(), so an NTP correction cannot fake or hide a stall - Device wall time for when something happened. Each cab event keeps its own time, and the server marks it late when it arrives more than 60 seconds after it happened. Order comes from sequence numbers, never timestamps
- Server receipt time for liveness. The site server classifies each truck's link by when it received the last heartbeat: online within 30 seconds, delayed within 120, offline beyond. Liveness from device time would let a cab whose clock runs five minutes fast look alive for five minutes after going silent. Storing
sent_atbesidereceived_atmakes clock offset measurable
Persisted retry schedules are the awkward case: next_attempt_at must survive a reboot, so it is wall time. The DUE query therefore treats any row scheduled more than one cap ahead as due now, which bounds the damage when the clock steps backwards.
Health that names the broken part
"Device offline" is the least useful edge alert, because a dead camera, a dead process and a dead uplink each send a different person to a different place. These signals tell them apart.
| What broke | What the edge sees | What the server sees | Separating signal |
|---|---|---|---|
| A camera | No frame for 10 s (store box) | Health arrives; that camera reports offline | Per-camera status in a healthy heartbeat |
| The pipeline | No tick for 30 s | A heartbeat thread may still say "fine" | /healthz returns 503 |
| The agent process | Nothing | Heartbeats stop; uptime restarts at zero | uptime_s reset |
| The network | Outbox depth and age grow | Heartbeats stop; uptime continues and a backlog drains | outbox_depth, oldest_pending_s |
The cab heartbeat, every 10 seconds by default, bypasses the outbox because only the latest matters; it carries the backlog, uptime, face visibility and the configuration and agent versions. A silent truck shows as unknown, never normal. The store backend is blunter: after 90 seconds of silence it marks the edge device offline and, unless another box in that store is reporting, flips the store's cameras to offline. We would show those cameras as unknown, since "camera offline" means check the cable and "edge offline" means check the box or the uplink. Paging on such signals without noise is covered in SLO burn-rate alerting for AI services.
Watchdogs that actually restart something
A watchdog has three layers: something notices the stall, something restarts the process and something restarts the machine when the kernel hangs. The store box does the first well. /healthz returns 503 once the loop has not ticked for 30 seconds, but 200 with waiting_for_config before the first configuration arrives, so waiting is not mistaken for broken. Docker Compose probes it every 15 seconds with five retries, under restart: unless-stopped.
The gap: Docker's restart policies act when a container exits, and under plain Docker an unhealthy container keeps running, so a healthcheck alone yields a red status, not a restart. We recommend letting the agent's stall detector exit with a non-zero code so the restart policy fires, plus a hardware watchdog for hangs below the process. The fatigue prototype lists a cab computer with a watchdog as not built, which is the honest state of both systems.
A restart must also be cheap and lossless. The outbox is on disk, and the store box loads its last valid configuration from an atomically written cache, so it enforces its rules after a reboot without a network. Mind warm-up: ONNX Runtime builds TensorRT engines on first use, which can take minutes, and a shorter grace period turns a slow start into a restart loop.
Model rollouts and configuration drift
Configuration is where both prototypes are strongest. The cab's thresholds are versioned, bounded and cross-checked on the server, so a typo cannot switch a detector off. Cabs poll with the version as an ETag, apply new values without losing detector state and report the version in every heartbeat. The store box polls with If-None-Match, and when it receives an invalid document it keeps the previous one and reports the reason as config_error. Drift detection is then a comparison: the version the server wants against the version each device reports.
Neither prototype has staged model rollouts: models are plain files on disk, with fallbacks on the store box when one is missing. For a pilot we would add:
- A content hash per model, reported in the heartbeat beside the configuration version
- Shadow mode: the new model runs on the same frames, its events tagged so they never alert, compared against reviewed outcomes; on hardware sized for one model it may need a reduced rate
- A few named canary devices chosen for hard conditions such as night shifts or dusty lenses, not a random sample
- Promotion thresholds agreed before the rollout, as with evaluation gates in CI
- The previous model and its prebuilt engine kept on disk, so rollback works while the uplink is down
Break it on purpose
Retries and de-duplication only earn trust under deliberate failure. The fatigue prototype's end-to-end test drops a quarter of the requests before they reach the server and a fifth of the responses after it has stored the batch, then checks that every event is stored exactly once. This harness applies the same rates to the outbox above and closes and reopens the database every five rounds.
class FlakyServer:
"""Loses 25% of requests before storing them and 20% of responses after storing them."""
def __init__(self, rng: random.Random) -> None:
self.rng, self.stored, self.order = rng, {}, {}
def __call__(self, envelopes: list[dict]) -> dict[str, str]:
if self.rng.random() < 0.25:
raise ConnectionError("request lost")
results = {}
for env in envelopes:
duplicate = env["key"] in self.stored # a UNIQUE constraint in a real server
if not duplicate:
self.stored[env["key"]] = env
self.order.setdefault(env["episode_id"], []).append(env["seq"])
results[env["key"]] = "duplicate" if duplicate else "accepted"
if self.rng.random() < 0.2:
raise TimeoutError("response lost") # stored, but the device never hears it
return results
rng, path, now = random.Random(7), "outbox-demo.db", 0.0
server, db = FlakyServer(rng), open_db(path)
for i in range(300):
record_episode(db, f"ep-{i % 40}", rng.choice(["microsleep", "overspeed"]), "updated", now)
for tick in range(10_000):
if tick % 5 == 0: # crude crash: drop the connection and reopen the file
db.close()
db = open_db(path)
drain_once(db, server, now, rng)
now += 2.0
if db.execute("SELECT COUNT(*) FROM outbox").fetchone()[0] == 0:
break
assert len(server.stored) == 300
assert all(seqs == sorted(seqs) for seqs in server.order.values())
print(f"{len(server.stored)} events stored exactly once, episode order kept, {now:.0f} s simulated")
With the standard library only, the three snippets print 300 events stored exactly once, episode order kept, 28 s simulated. Closing a connection is not a power cut, though; durability claims need a pull-the-plug test on the target hardware. Other faults worth injecting: a clock stepped back an hour, a full disk, a corrupt database, an unplugged camera and responses slower than the client timeout. Each should leave a trace in health or logs and lose no committed event.
Checklist
- Make safety decisions and alarms on the device; the network only informs people further away
- Send events and measurements, and keep raw video on site with a stated retention
- Write each outgoing event in the same SQLite transaction as its state, with a deliberate
synchronoussetting - Mint idempotency keys at enqueue and enforce them with a unique constraint on the server
- Retry with capped, jittered backoff and treat a timeout as unknown, not as failure
- Use monotonic time for staleness, device time for occurrence and server receipt time for liveness
- Report camera, pipeline, agent and network health separately, and show silence as unknown
- Let the stall detector exit the process, with a grace period longer than model warm-up
- Report configuration and model versions in every heartbeat and keep the previous model on disk
Primary references
- SQLite: Write-Ahead Logging
- SQLite: Autoincrement
- Microservices.io: Transactional outbox pattern
- Amazon Builders' Library: Timeouts, retries and backoff with jitter
- Docker: Start containers automatically
Related reading
- Edge AI for Computer Vision: Where Processing Should Run
- Camera Analytics Pilot: Measure Real Operational Quality
These patterns come from the Mining Fatigue Guard and Store & Workforce Vision prototypes, and they are how we approach edge work in our computer vision service.
