Edge-Cloud Video Analysis on Raspberry Pi and Bedrock
Overview
Running continuous video analysis in a private indoor space forces uncomfortable trade-offs. Streaming continuous footage to a cloud vision model costs money and moves raw video off-site; relying solely on a small edge model produces brittle detections whenever a high-back chair or partial occlusion hides key body landmarks.
I built a private edge-cloud video analysis pipeline to track occupancy and visible desk activity across three fixed seats (Desk A near blue chair, Desk B upper-right white chair, and Desk C upper-left mint chair) from a ceiling-mounted 640×360 camera stream. Rather than trusting either a Raspberry Pi 3B or a cloud vision LLM unconditionally, the architecture separates continuous local video retention, fail-open edge gating, source-bound cloud review, and a reporting ledger that caps uploaded excerpt count and size.
Why pure edge detection was not enough
The edge node is a Raspberry Pi 3B reading a 640×360 H.264 RTSP substream. Running a full-frame YOLOv8n person detector alongside YOLO11n-pose320 across three desk crops took a median of 2,412 ms per frame (p95: 2,465 ms, excluding decoding and startup)—consuming nearly half of a five-second sampling budget before capture and decoding overhead.
Accuracy on occluded seats was the bigger failure. Evaluated against 32 model-assisted reference frames (20 frames sampled at fixed 15-minute intervals plus 12 targeted challenge frames from an evening recording), the edge pose/person pipeline broke down on seated subjects:
- Missed occluded occupants: On Desk C (upper-left mint chair), where a high backrest hid the torso and hips, the person-model region check scored 0/5 on fixed-interval seated references (pose region hits: 2/5).
- False positives on nearby motion: The Desk A region fired on both agreed standing-only cases and an empty-chair reference.
- Unreliable posture proxies: A hip-inside-region pose heuristic failed on passersby, standing figures, and seated occupants whose lower bodies were out of view.
The core lesson was epistemic: on a resource-constrained edge camera, "no local detection" cannot mean "empty seat," and "person box overlaps desk" cannot mean "seated and engaged."
Quarantining a lightweight edge classifier in shadow mode
To test whether a view-specific model could help, I trained one linear logistic head per desk (E empty, S seated, P standing/nearby, U uncertain) on frozen MobileNetV3-small ONNX Runtime features using pseudo-labels from verified cloud receipts, recording-level train/validation splits with a 60-second temporal embargo, and fixed score, margin, and cosine-similarity abstention thresholds.
On the Raspberry Pi 3B, three-desk inference dropped to a median of 297 ms (p95: 427 ms, 143 MiB peak RSS including replay decoding). On seen regression frames from the earlier evening, Desk C seated hits rose to 10/12 (11/12 after live quality-90 JPEG round-trip) compared with 6/12 for the pose-region baseline.
However, two problems kept it out of live upload control:
- Over-confident abstention boundaries: Across 24 unseen fixed-interval evaluation frames (72 desk observations: 54 definite, 18 uncertain), the classifier matched 31–33 of the 54 definite references depending on input encoding (33/34 accepted on raw decoded frames vs. 31/31 accepted after live quality-90 JPEG round-trip), while still accepting 7–9 of the 18 uncertain references instead of abstaining as
U. - Encoder sensitivity: Switching from raw decoded frames to the Pi's live quality-90 JPEG spool flipped boundary abstentions, showing that offline raw evaluations did not identically match live spool inputs.
Because those error rates are unsafe for autonomous suppression, the classifier runs strictly in shadow mode inside an isolated systemd unit (cpu quota, memory cgroup limit, and RLIMIT_DATA cap). It reads committed spool JPEGs without opening another camera stream, logs shadow predictions without suppressing uploads, and marks predictions older than 15 seconds stale. Promoting it to live control would require calibrated abstention (near-zero accepted ambiguous frames) across multi-day lighting and clothing changes.
End-to-end architecture
The production pipeline splits responsibilities across the Raspberry Pi, an SSH relay host, a private AWS Lambda reviewer, and a Cloudflare reporting layer:
flowchart LR
C[640x360 RTSP Camera] --> R[Pi Rolling MKV Remux]
C --> E[Pi 5s Frame Sampler]
E --> S[Bounded 120-Frame Spool]
S --> G[Fail-Open Upload Gate]
G -->|Eligible frames| W[Cloud Host SSH Relay]
W --> L[Private IAM Lambda]
L <--> B[Cognito M2M Token Broker]
L <--> M[Bedrock Vision Model]
L -->|Source-bound JSON| W
W --> P[Pi SQLite Ledger]
P -->|Verified empty receipt| G
P --> RW[Report Sync Worker]
R -->|20s H.264 excerpt| RW
RW --> CF[Cloudflare Worker + D1 + R2]
Four boundaries govern data movement and blast radius:
- Continuous video stays on the Pi: A rolling recorder remuxes the H.264 substream directly into 300-second video-only MKV segments at keyframe boundaries—without decoding or re-encoding—under a disk budget (16 GiB cap, 4 GiB minimum free space, 64 MiB write reserve, atomic oldest-first cleanup).
- No AWS credentials or public ports on the Pi: The AWS Lambda function (
Node.js 24,arm64) has no Function URL or API Gateway. An authorized same-account IAM caller on the relay host pulls eligible frames over SSH through a private jump tunnel, keeping AWS credentials and inbound listening ports off the physical Pi. - Lambda-scoped memory handling and short-lived leases: The Lambda fetches a short-lived Bedrock bearer lease from a Cognito M2M token broker rather than holding static API keys, and calls the Responses API with
store: false. Within the Lambda application code, images are processed in memory and omitted from application logs. Selected 640×360 JPEGs still transit the Pi spool, SSH relay, Lambda memory, and Bedrock inference request. - Separate reporting plane: An asynchronous sync worker tails the Pi SQLite ledger, remuxing 20-second H.264 excerpts from MKV to MP4 (no audio, no re-encoding) only for representative intervals or periodic unclear-activity reviews.
Source-bound cloud review
Batching frames to a vision LLM introduces failure modes unrelated to pixel understanding: shifted frame ordering, stale retries arriving after an outage, duplicate JSON keys, or prompt-injection text painted into a scene. The source-binding checks catch missing, reordered, or mismatched identifiers; they cannot verify that a visual judgment actually belongs to the echoed frame or prevent text inside an image from influencing the model.
Every 6-frame request and reply enforces four deterministic checks:
- Digest-bound frame identity: Each frame carries
(id, source_time, session_id, geometry_sha256, image_sha256), wheregeometry_sha256pins the calibrated desk-crop coordinates. On ingress, the Lambda validates JPEG SOF markers, exact 640×360 dimensions, base64 round-trip equality, and SHA-256 digests before calling Bedrock. - Strict schema and duplicate-key rejection: Bedrock's Responses API enforces
json_schemawithstrict: true. Before schema validation runs, a custom token-scanning JSON parser rejects duplicate or escaped-duplicate keys soJSON.parsecannot silently pick a last-wins value. - Exact-order echo and per-frame 45s live-state TTL: The Pi stores a cloud receipt only when every frame's ID, source timestamp, capture session ID, geometry digest, and image SHA-256 match the original spool entry in exact order. Freshness is evaluated per frame from capture
source_time(valid_until = source_time + 45s), not as a shared batch timer: by the time a 6-frame batch (at 5s spacing) finishes sampling, the oldest frame has already spent 25s in the spool, leaving 20s for transit and inference while the newest frame still has 45s. Validated frames arriving pastsource_time + 45sare recorded in the historical ledger for candidate spans, but only a newest frame within 45s of capture can update live desk state. - No fabricated certainty: Seating state (
S,E,P,U), coarse engagement (desk_engaged,other,unknown), and specific activity (writing,reading,computer,play,walking,desk_task,other,unknown) are stored separately. Unclear frames never become positive time, and sample gaps over 8 seconds break candidate spans rather than interpolating across missing frames.
Choosing the cloud vision model
To select the live model, I ran a same-input comparison across five models on 36 original frames (6 batches of 6 frames, 8,000 max output tokens; low reasoning effort where supported) covering 108 desk observations (93 definite references, 24 seated, 15 uncertain):
| Model (API surface) | Definite-label agreement | Seated hits / 24 | Non-seated called seated / 69 | Median latency / 6 frames | Estimated USD / 600 requests |
|---|---|---|---|---|---|
| Grok 4.6 (Mantle) | 89/93 | 22 | 0 | 21.38s | $10.01 |
| Grok 4.7 (Runtime Responses) | 82/93 | 21 | 5 | 20.78s | $9.40 |
| GPT-6 Luna (Runtime Responses) | 89/93 | 21 | 0 | 8.61s | $0.50 |
| GPT-6.1 Terra (Runtime Responses) | 91/93 | 23 | 0 | 7.09s | $3.93 |
| Haiku 5.5 (Converse) | 81/93 | 20 | 4 | 8.52s | $0.60 |
Note: Every reference label here is model-assisted (Claude Opus and Grok independently proposed labels; disagreements stayed U). No human ground truth exists, and Grok's participation introduces shared-model bias. Definite labels cover E, S, and P, so Terra's 23/24 seated plus 0/69 false-seated reflects one E/P or U miss among non-seated observations. Notice also that 0/69 measures non-seated false positives per desk, whereas an error dangerous to the upload gate—calling an occupied room all-empty E with zero scene occupants—was not separately measured in this table. Estimated costs use published AWS Bedrock Standard short-context token rates checked on November 16, 2026 (including observed cache mix, excluding Lambda/logging/network charges) projected to 600 requests—equivalent to a 5-hour window at 120 batches/hour (30s batch cadence). At 4 hours/day over 30 days without gating (14,400 requests), those sample averages extrapolate to roughly $94/month on Terra or $12/month on Luna.
GPT-6.1 Terra matched 91/93 definite labels—within two observations of Grok 4.6 and GPT-6 Luna—and ran 1.52s faster at the median than Luna (7.09s vs. 8.61s), though at roughly 7.9× higher estimated token cost ($3.93 vs. $0.50 per 600 batches). Both medians sit well inside the oldest frame's 20-second remaining live budget, whereas Grok 4.7's slowest batch reached 88.14 seconds—far beyond the 45-second per-frame ceiling (per-batch pass counts were not separately tabulated for every model). I selected Terra for live deployment on agreement plus latency headroom, with GPT-6 Luna as the obvious cost-saving alternative.
The fail-open upload gate
Sending a 6-frame batch every 30 seconds across an active evening adds up when desks sit empty. Yet naive frame-to-frame motion detection is unsafe: gradual lighting shifts or slow movement can slip past consecutive diffs until the baseline silently drifts.
The upload gate addresses this with four invariants:
- Veto-only local signals and dual freshness caps: Suppression is allowed only when the latest source-bound cloud receipt reports all three desks empty (
E) and zero whole-scene occupants, and upstream pose detection reports no recent candidate (pose can only veto suppression, never authorize an empty state). Suppression ends at whichever limit arrives first: the receipt's 45svalid_untilormin(60s, configured audit interval)from the reference frame'ssource_time. An urgent singleton audit fires 5 seconds before that cutoff (at 40s under the 45s receipt TTL) so renewal never waits for a 6-frame batch—though a slow or unanswered audit still hits the 45s cutoff and re-opens the gate. - Anchor to the cloud-reviewed JPEG, never the prior frame: On receipt, the gate caches
64×48per-desk reference arrays (about 126 KiB for the three desks) decoded from the exact JPEG bytes the cloud reviewed. Comparing every new sample against that fixed cloud reference stops slow drift from accumulating. - Luma plus signed 2×2 RGB checks: Grayscale mean-absolute-difference (
<= 1.0) runs alongside signed2×2RGB block differences (<= 6.0pixel threshold,<= 0.001changed fraction) so isoluminant color shifts (such as dark clothing over a similar-luminance chair) still trigger upload. - Validated clock-band masking and fail-open latch: An optional bottom timestamp mask (
<= 40px) is rejected at startup if it intersects any calibrated desk crop or protected person region. Any camera reconnect, receipt expiry, or pixel delta latches the gate open until a fresh empty receipt arrives.
On the Raspberry Pi 3B, the pixel-diff and digest check inside the gate ran in a median of 31 ms (p95: 40 ms), excluding upstream pose inference and cloud latency. In same-encoder Pi replays with pose detections zeroed, the gate retained all 14 samples on a 65-second occupied clip and suppressed 4 of 13 samples in a stable empty window, while falling back to 0% suppression in shifting daytime light. In these limited replays, the gate retained every occupied sample and sacrificed suppression under changing light; this does not establish a measured zero-miss rate, and any cloud E false negative on an occupied frame would temporarily anchor the reference until the next audit.
An authenticated reporting portal on Cloudflare
The Pi only makes outbound connections; the user-facing report runs on Cloudflare Free Workers, Cloudflare D1, and private Cloudflare R2, keeping assets self-contained without external scripts or third-party fonts.

Four design choices keep storage bounded and access controlled:
- Ledger-enforced admission limits: D1
BEFORE INSERTandAFTER INSERTtriggers cap active R2 reservations at 2 GiB total, 256 MiB/day, 120 clips/day, and 20-second / 3 MiB excerpts (7 days × 256 MiB/day = 1.75 GiB, staying inside the 2 GiB ceiling). Admission charges commit when apendingclip row is inserted before the R2 upload, so failed uploads or deletions never refund the daily quota, while hourly cleanup and a 7-day R2 lifecycle rule act as a backstop if cleanup misses an object. - Cognito PKCE with
workerdredirect safety: Browser login uses an Amazon Cognito public Authorization Code + PKCE (RFC 7636) flow. State, nonce, and verifier bind to a__Host-cookie and are consumed atomically in D1 viaDELETE ... RETURNINGbefore token exchange. Because Cloudflare'sworkerdruntime rejectsfetch(..., { redirect: 'error' }), token and JWKS requests explicitly setredirect: 'manual'and fail closed on any non-2xx status (Workers Request API), verified by nativeworkerdtests. - Opaque sessions and group RBAC: Browsers receive only an opaque HttpOnly session cookie (capped at 24 hours) with tokens kept server-side; read routes require a signed viewer group claim while manual overrides require an editor claim and matching
Origin. - Append-only source segments with layered overrides: D1 triggers abort conflicting mutations to existing segment identities, storing human corrections in a separate table so the original cloud evidence remains auditable.

Limitations
- 640×360 ceiling resolution limits fine activity precision: While GPT-6.1 Terra matched 91/93 definite seating labels, I did not benchmark fine-grained
readingvs.writingaccuracy, and live low-resolution checks frequently left detailed activity asunknown. Sending higher-resolution ROI crops only for occupied desks is the next experiment; its effect on activity agreement and token cost remains unmeasured. - Wall-clock jitter on RTSP segments: MKV segment filenames reflect stream arrival time rather than NTP-locked frame timestamps, leaving small boundary jitter across 300-second files.
When to adopt this pattern
This architecture fits when you already own low-power edge hardware, want continuous footage stored locally rather than streamed off-site, need auditable observation receipts rather than black-box alerts, and accept model-assisted states without human ground truth. If your environment allows streaming full video to a managed cloud VMS, or if an angled camera cleanly separates subjects without chair occlusion, an edge-only detector or managed cloud VMS will be far simpler to operate.
Resources
- Amazon Bedrock Responses API documentation
- Amazon Cognito PKCE authorization code documentation
- RFC 7636: Proof Key for Code Exchange (PKCE)
- Cloudflare Workers Request API documentation
- Cloudflare D1 documentation and Cloudflare R2 documentation
- ONNX Runtime documentation