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
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
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.
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.
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.
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.
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
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.
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.
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.
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
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.
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.
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.
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.
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
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.
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.
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.
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.
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.
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.
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.
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.
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.