All work

Case study

Sendero Home

Opening a real gate from a phone: IoT access control and live video for gated communities

Sendero Home lets residents of a gated community open vehicle and pedestrian gates from their phone, watch live cameras and send guests expiring access links. Administrators run houses, residents, areas, devices and cameras from a web dashboard. It is in production in two gated communities, and the app is in the App Store and Google Play.

Role
Sole engineer: firmware, cloud, edge, API, dashboard and mobile app
Timeline
October 2025 to present
Status
In production in two gated communities, with a third of nearly 100 homes in negotiation. App 1.2.0 in the App Store and Google Play.
2
gated communities in production
1
engineer, from the firmware to the app
5
runtimes: ESP32 firmware, AWS IoT, edge Worker, API and web, mobile
iOS + Android
resident app in the App Store and Google Play

Context

The problem

Gated communities in Mexico control entry with gates, guards and intercoms. I built a system where a resident's phone is the key: it opens the gates their house has access to, shows the cameras of those areas, and creates guest links that expire.

The hard part is that a button in an app moves a physical gate. A command that runs twice, runs late or never stops is a safety problem, not a UI bug. The controllers sit on site behind consumer internet, so they go offline, reboot and reconnect.

Video has its own constraint. Cameras on site speak RTSP on a private network. Residents watch from anywhere, and the video must not pass through the API server or open ports at the community.

The system is multi-tenant: one database holds every community, and a person can be an administrator in one community and a resident in another.

System design

How it fits together

The API and the admin dashboard run on a VPS and share one domain core of Prisma-backed services. Postgres, authentication and file storage are managed by Supabase. Background work runs on Inngest, which calls functions served by the API.

Gates are driven by custom ESP32 controllers. Each one has its own X.509 certificate and talks to AWS IoT Core over MQTT with mutual TLS. The API never holds an MQTT connection: it writes device shadows over HTTPS with IAM credentials.

Video goes from the cameras to go2rtc on site, out through a Cloudflare Tunnel, and to a Cloudflare Worker that checks a signed URL before the app's player gets the stream.

System design

Sendero Home system designThe resident app calls a Hono API on a VPS, which reads and writes Postgres, runs background jobs through Inngest and opens gates by writing AWS IoT device shadows that ESP32 controllers on site follow over MQTT. Video never crosses the VPS: cameras on site go through go2rtc and a Cloudflare Tunnel to a Worker that checks a signed URL before the app's player gets HLS.PhonesVPSAWSCloudflareOn sitepush · APNs, FCMHTTPS · JWTjobs · HTTPSSQL · Prismashadow write · HTTPSMQTT · mTLSHLS · outboundHLS · signed URLResident appExpo · React NativeAPIHono · Node · shared coreAdmin dashboardNext.js · tRPCInngest + Expo Push17 jobs, notificationsPostgresmanaged · Supabase AuthAWS IoT Coredevice shadowsStream Workerverifies signed URLCloudflare Tunnelno open ports on siteCameras + go2rtcRTSP to HLSGate controllersESP32 · ESP-IDF CGatesrelays, timed pulseX.509 per device
Two paths leave the VPS: commands go to AWS IoT and reach the gates as shadow deltas, and video never touches the VPS at all. The API only signs the URL the Worker checks.
ComponentResponsibilityTechnologyRuns on
Resident appGates, cameras, guest links, notificationsExpo, React Native, EAS Update for OTAiOS and Android
APIVersioned REST for the app, devices and public guest pages; serves the Inngest functionsHono 4 on Node, PM2, Caddy for TLSVPS
Domain coreAll business logic: devices, houses, areas, cameras, guests, notifications, plans, stream signingTypeScript, Prisma servicesImported by the API and the dashboard
Admin dashboardCommunity administration and a superadmin view over every tenantNext.js 16, tRPC 11, Supabase sessionsVPS
Database and authTenants, users, devices, audit logs; passwordless email codesPostgreSQL, Supabase Auth and StorageSupabase
Background jobsNotification dispatch, offline-device checks, audit archiving, remindersInngest, 17 functionsInngest Cloud calling the VPS
IoT brokerOne device shadow per controller; desired and reported stateAWS IoT Core, MQTT over mTLSAWS
Gate controllerFour relays with timed pulses, shadow sync, heartbeat, watchdog, setup portalESP32, ESP-IDF C, FreeRTOSOn site
Camera originTurns RTSP into HLSgo2rtcA small box on site
Stream WorkerVerifies the signed URL, proxies through the tunnel, sets a cookie for segmentsCloudflare Worker and TunnelCloudflare edge

Stack

Mobile
Expo, React Native, Expo Router, TanStack Query, Jotai, expo-video, EAS Build and Update, Expo Push
Web
Next.js 16, React 19, Tailwind 4, shadcn, tRPC 11
API
Hono 4 on Node, Zod, PM2, Caddy
Data
PostgreSQL on Supabase, Prisma 7, Supabase Auth and Storage
Async
Inngest, Resend
IoT
AWS IoT Core (MQTT over mTLS, device shadows), ESP32, ESP-IDF, FreeRTOS, PlatformIO
Video
RTSP cameras, go2rtc, Cloudflare Tunnel, Cloudflare Workers
Tooling
pnpm workspaces, Turborepo, TypeScript, ESLint, Vitest

Flows

The paths that matter

01 A resident opens a gate

The API cannot know whether a gate physically moved. It can only make sure the command is authorized, runs once and stops on its own.

Flow · opening a gate

Opening a gate from the appThe app calls the API, which authenticates the user, checks that the house has access to the gate's area, and writes the desired state to the controller's device shadow. The 200 means AWS accepted the write. The controller receives the delta over MQTT, pulses the relay for a bounded time, then clears the desired state so the command cannot replay.Resident appExpoAPIHonoSupabase AuthAWS IoT Coredevice shadowGate controllerESP32POST .../channels/:id/activateBearer token, X-App-Versionverify tokenuserresidency + area accesssuspended house: 403UpdateThingShadowdesired: on, pulseMs, timestampaccepted200: accepted, not confirmedaccess log and push run apartOn the device, after the 200shadow deltaMQTT over mTLS; relay on, timer setdesired: null + reportedafter the pulse: relay off, no replay
The 200 means AWS accepted the shadow write. The physical action happens later on the controller, which also clears the command.
  1. Authenticate

    The app sends the request with the user's access token and its app version. The API verifies the token with Supabase Auth and loads the user.

  2. Authorize by area

    Access is granted per house to an area, not per device. The API checks that the user is a current resident of the house and that the house has an active grant to the gate's area. A suspended house gets a 403 for that door.

  3. Write desired state

    The API calls UpdateThingShadow with the channel number as the key, the pulse length (3 seconds by default) and a timestamp. The timestamp makes a second open of the same gate a new change, so AWS sends a new delta. If AWS fails, the app gets a 503.

  4. Answer the app

    The response means AWS accepted the write, not that the gate opened. The access log is written in its own try/catch so a logging failure cannot hide a successful open, and the push to the other residents runs separately.

  5. Pulse on the device

    The controller gets the delta over MQTT, turns the relay on and starts a timer. When the timer fires it turns the relay off, reports its state and writes desired back to null. Clearing desired is what stops the same command from being delivered again.

02 A resident watches a live camera

The cameras are on a private network at the community, and the video should reach phones without passing through the API or opening ports on site.

Flow · live video

Watching a live cameraThe app asks the API for a stream URL; the API checks access and signs a short-lived URL. A Cloudflare Worker verifies the signature and expiry, proxies the request through a tunnel to go2rtc on site, and sets an HttpOnly cookie so the HLS segment requests that follow are authorized. Video never passes through the API.Resident appvideo playerAPIHonoStream WorkerCloudflarego2rtcon site, via tunnelask for a stream URLarea access, plan, payment scopeURL signed with HMAC-SHA256expires in 20 min; app reuses it 5 minGET playlist + signaturecheck signature + expiryproxy, auth params strippedCloudflare Tunnel, no open portsHLS playlistRTSP to HLS on siteplaylist + HttpOnly cookieGET segmentsthe cookie authorizes each one
The API decides who may watch and signs a short-lived URL. The Worker enforces it at the edge, so the video bytes never touch the VPS.
  1. Ask for a URL

    The app asks the API for a stream URL. The API checks that the resident's house has access to the camera's area, that the plan includes cameras, and any payment restriction.

  2. Sign it

    The API signs the source and an expiry with HMAC-SHA256. The URL lives 20 minutes by default, and the app reuses one for 5 minutes instead of asking again on every open.

  3. Verify at the edge

    The player requests the HLS playlist from the Worker. The Worker checks the signature and expiry, strips the auth parameters and proxies the request through the Cloudflare Tunnel to go2rtc, which converts RTSP to HLS on site.

  4. Authorize the segments

    HLS fetches many segment files after the playlist. The Worker sets an HttpOnly, Secure cookie on the first response so those requests pass. On Android the player does not send cookies with segment requests, so the app makes a request first to set it.

03 Moving the API and dashboard to a VPS

The project started on Vercel's Hobby plan and was close to its compute limit. Installed apps had the old host built in and could not all be updated, so every phase had to keep them working.

Flow · routing after the move

Routing after the move to the VPSNew app builds call the API host on the VPS directly. Older builds still call the original host on Vercel, where an external rewrite at the CDN forwards the request to the VPS without running a function.PhonesVercelVPSHTTPS · new API hostold hostexternal rewriteApp 1.2.0 and latercalls the VPSOlder app buildscannot be force-updatedVercel CDNrewrite, no function runAPI + dashboardHono · Next.js · PM2
New builds call the VPS directly. Old builds still reach the original host, and Vercel forwards those paths at the CDN without running a function.
  1. Extract the core

    I moved 136 files into a shared core package with git mv, without changing behaviour, and kept the existing test suite passing (22 of 22) before anything else moved.

  2. Rebuild the API at parity

    I rebuilt the API as a Hono service on Node with the same routes, and copied the dashboard rather than moving it, so the old copy stayed available as a fallback.

  3. Route the traffic

    Cloudflare Origin Rules could not rewrite paths or hosts outside the Enterprise plan, so I dropped that phase. Vercel external rewrites, resolved at the CDN before any function, forward the old API paths to the VPS instead.

  4. Move the rest

    After the cutover the Inngest endpoint was most of the remaining Vercel CPU, so it moved too. Guest pages stayed on Vercel on purpose so the rate limit sees the guest's real IP.

  5. Release safely

    Release scripts fail closed: they require the main branch and a clean tree, build before reloading so a failed build leaves the running process alone, never run migrations, and finish with a health check. Rollback is a revert and a re-release.

Decisions

What I chose, and what it cost

  1. 01

    Chose Device shadows over direct MQTT commands over the backend publishing commands over its own MQTT connection

    Why
    The API writes desired state over HTTPS with IAM and never holds a broker connection. A controller that was offline picks up its state on boot.
    Cost
    No physical acknowledgement, and a command sent while a controller is offline can run late when it reconnects. Whether it should is still an open policy question.
  2. 02

    Chose The firmware clears desired state after each pulse over leaving desired set and letting the device compare values

    Why
    Leaving desired true made the relay fire again on every redelivery, and repeating the same value produced no delta at all. Clearing it, plus a timestamp on every write, fixes both.
    Cost
    The firmware and backend now share a protocol that has to change together.
  3. 03

    Chose Custom ESP-IDF C firmware over the earlier ESPHome configuration

    Why
    ESPHome's default MQTT behaviour had to be turned off because AWS IoT rejects unauthorized publishes. Writing the firmware myself gave me control of the setup portal, the watchdog and reconnects.
    Cost
    I own about 1,600 lines of C with no automated tests.
  4. 04

    Chose A VPS for the API and dashboard over staying on Vercel and its compute-based pricing

    Why
    The Hobby plan was near its active CPU limit. I kept Inngest Cloud and only moved the URL it calls, instead of self-hosting it too.
    Cost
    One server is now in the path of every gate open, and it is a single point of failure.
  5. 05

    Chose Additive-only contracts for the mobile API over versioning by breaking changes and forcing updates

    Why
    Old app builds cannot be force-updated, and some older Android devices cannot install 1.2.0. The app sends version headers, the API can answer 426 below a minimum version or 403 to apps without headers, and outdated users get a targeted push. OTA updates go to a preview channel before production.
    Cost
    Old fields and routes stay alive for a long time, and every change to the client API needs a compatibility check.
  6. 06

    Chose tRPC for the dashboard, versioned REST for everything else over one API for all clients

    Why
    Typed RPC is fast to build against for an internal UI. Phones, devices and public pages need a stable contract that does not move with the dashboard.
    Cost
    Two API surfaces, plus a legacy admin API kept for compatibility.
  7. 07

    Chose Signed URLs checked by a Cloudflare Worker over exposing the camera origin or proxying video through the API

    Why
    Video never crosses the VPS, and the site needs no open ports.
    Cost
    A second secret and another component at the edge, and the cookie behaviour on Android needed a workaround.
  8. 08

    Chose Plain Prisma domain services over the earlier dependency-injected use-case and adapter layers

    Why
    Less ceremony for one engineer. I kept injection only where it already existed.
    Cost
    Services are harder to isolate in unit tests.
  9. 09

    Chose Two-step migrations and per-tenant flags over shipping destructive schema changes and features to everyone at once

    Why
    A migration first adds and copies; the drop ships only after new code is live. New modules turn on per community through override-only flags.
    Cost
    More migrations and more flag states to reason about.

What broke

Incidents and what changed

A relay that kept firing

What happened
With desired left set to on, the shadow kept producing deltas and the relay re-fired. Opening the same gate twice in a row produced no delta at all.
What changed
The firmware clears desired with null after the pulse, and every write carries a timestamp.

The wrong key in the app

What happened
The app's optimistic update used the database id of the channel instead of its number, which is the key in the shadow.
What changed
The channel number is the protocol key everywhere, so the database and the shadow line up.

A logging failure that looked like a failed open

What happened
When writing the access log failed, the request reported an error even though the gate had been commanded.
What changed
The log write runs in its own try/catch after the activation.

Video that would not play on Android

What happened
Android playback failed twice over: the FLAC audio track hit a decoder error, and the player did not send the auth cookie with HLS segment requests, so the Worker answered 403.
What changed
I dropped the audio track and made the app send a first request that sets the cookie.

Controllers in the field

What happened
Controllers on site lost their connection and did not always recover.
What changed
A watchdog restarts the ESP32 when MQTT is down for 5 minutes or free memory falls under 20 KB, plus a preventive restart every 24 hours. The setup portal restarts after 10 minutes.

A rewrite path that did not exist

What happened
The plan was to move traffic with Cloudflare Origin Rules. They cannot change paths or hosts outside the Enterprise plan.
What changed
I dropped that phase and used Vercel external rewrites at the CDN instead.

Errors reported as 500

What happened
Domain errors in the dashboard's tRPC routers surfaced as server errors.
What changed
They map to the matching 4xx codes across the routers.

Quality

Tests, operations, security, cost

What exists today. Verification is manual: type checks, tests and lint before each release.

Tests
About 872 test cases in 70 files, mostly Vitest suites for the API, including four that run against a real database.
Device identity
Each controller has its own X.509 certificate, and one IoT policy scoped to the thing name means a device can only touch its own topics.
Video access
Short-lived HMAC-signed stream URLs verified at the edge.
Background jobs
Inngest functions use concurrency keys and idempotency keys, for example one broadcast per id and serialized work per community. Audit logs are archived before they are deleted.
Audit trail
Gate, camera and guest access each have a log table, and event tables are append-only and written in the same transaction as the change they record.
Mobile compatibility
Additive-only API changes, version headers, minimum-version gates and OTA channels.
Operations
The health endpoint fails when the database is unreachable, every request is logged as JSON with a request id, and the process manager restarts on memory limits.
Security backlog
A hardening backlog for the device provisioning and stream authorization paths is tracked and prioritized.

Method

How I built it

I write plans as checklists in the repo and keep a current-status document separate from the roadmap, including the known gaps. Coding agents do much of the implementation; I review and integrate every change.

Safety rules for the physical side (bounded pulses, clearing desired state, treating a shadow write as acceptance) are written down and checked in review.

Hindsight

What I'd do differently

  • I would set up CI on day one. Every release is verified by hand today, and nothing catches a skipped check.
  • I would put tests where the risk is: the gate-open path, the firmware, the edge Worker and the mobile app have none, while most tests cover the API's business modules.
  • I would not let one VPS sit in the path of every gate open without alerting. Health alerts and log shipping are the next step, and they should have come with the move.
  • I would design physical acknowledgement into the shadow protocol from the start, so the app can tell a resident that the gate moved, not only that the command was accepted.