Caution
GopherDispatch has been taken offline. This repository is kept as an archive. See the Retrospective to understand why.
GopherDispatch
Fills empty slots in a field-service schedule. When a technician's day has a gap, GopherDispatch ranks every customer in the CRM by how little extra driving it would take to fit them in, then (optionally) calls them with an AI voice agent and books the job.
A B2B SaaS for HVAC and plumbing companies, built on top of a ServiceTitan integration. In production from Jun 2025 to Nov 2026. Served 2 companies with a combined 205 technicians and 113881 customers.
Every name, address and phone number in this README is seeded demo data.
Contents
- The problem
- What it does
- Architecture
- Engineering highlights
- Infrastructure and CI/CD
- Running it locally
- Repository tour
- Retrospective
The problem
Residential HVAC and plumbing companies run on membership plans: a customer pays yearly, and the company owes them a couple of maintenance visits. Those visits are flexible, so they make good filler work, but dispatchers rarely have time to use them that way.
On a typical day, a cancellation opens a two-hour hole in a technician's schedule. To fill it, a dispatcher would have to:
- find members who are due for a visit,
- work out which of them are near where that technician already is,
- check that the time actually works once you add the driving, and
- call people until someone says yes.
Usually nobody does this, and a paid technician sits idle. We discovered this problem while coincidentally while doing other business with these companies.
GopherDispatch turns those four steps into one ranked list. It can also make the calls itself.
What it does
1. Find the best customer for an open slot
Pick a date. GopherDispatch reads every technician's schedule for that day, works out where the gaps are, and then, for each eligible customer, simulates adding a visit into each gap using real road-network drive times. Each customer gets the technician, arrival time and added driving time of their best fit. Results stream into the browser as they're computed.

Every result includes before/after route links, so a dispatcher can check the suggested detour on a map.
2. Saved, composable searches
Dispatchers narrow the pool with stackable filters, then save the combination. Searches can be private or shared with the whole company.
| Filter | Example |
|---|---|
| Customer / location tags | must be Comfort Club, must not be Do Not Call |
| Installed equipment | has equipment installed 10+ years ago; equipment memo matches a regex |
| Recurring maintenance events | has a tune-up that's Not Attempted or Unreachable in a date range |
| Appointment history | no completed appointment in the last N days |
| Call history | no outbound call in the last 30 days; inbound calls by type (booked, abandoned…) |
| Estimates | has an Open estimate from the last 180 days |
| Technicians | only consider these techs |

3. Per-technician rules
Each technician can have a start and end address (home or shop, geocoded with autocomplete) and their own filters. For example, the plumber only gets plumbing-tagged customers, and the installer only gets customers with aging equipment. These rules apply on top of the dispatcher's search.

4. AI outbound calling (feature-flagged)
"Auto Call" hands the customer to a Bland AI voice agent. Mid-conversation, the agent uses tool calls to ask GopherDispatch which days and times are open. It then creates the job directly in ServiceTitan and reports the outcome in a webhook.

5. Self-serve onboarding, billing and teams
- ServiceTitan connection is a guided state machine: tenant ID → app invite → customer enables the integration → OAuth keys → first sync. The first sync shows live progress against a pre-counted total.
- Stripe subscriptions come with a 90-day free trial (paused, not cancelled, if no card is on file), a customer billing portal, and webhook-driven status changes.
- Teams: each company has many users. Invitations go out by email and expire. Sign-in works with email and password or with Google.
| Onboarding | First sync |
|---|---|
![]() |
![]() |
Architecture
flowchart LR
subgraph Browser
SPA["React 18 SPA<br/>Vite · Tailwind · shadcn/ui"]
end
subgraph AWS["AWS ECS task"]
NGINX["nginx<br/>static SPA + /api proxy"]
API["FastAPI (async)<br/>REST + WebSocket"]
JOBS["APScheduler jobs<br/>sync · timeouts · webhook replay"]
API --- JOBS
end
PG[("PostgreSQL<br/>37 tables, 89 migrations")]
OSRM["OSRM<br/>self-hosted routing engine<br/>(OpenStreetMap)"]
ST["ServiceTitan API"]
BLAND["Bland AI<br/>voice agent"]
HERE["HERE<br/>geocoding"]
STRIPE["Stripe"]
MAIL["Maileroo<br/>email"]
GOOGLE["Google OAuth"]
SPA -- HTTPS / WSS --> NGINX --> API
API --> PG
API -- drive times --> OSRM
JOBS -- incremental sync --> ST
API -- create job --> ST
API -- start call --> BLAND
BLAND -- tool calls + webhook --> NGINX
API --> HERE
API --> STRIPE
STRIPE -- webhook --> NGINX
API --> MAIL
API --> GOOGLE
| Layer | Choice | Why |
|---|---|---|
| API | FastAPI, fully async (SQLAlchemy 2 async + asyncpg, aiohttp) | The core request fans out into hundreds of concurrent routing calls. Async keeps that cheap on one small container. |
| Background work | APScheduler, in-process | No separate broker or worker fleet to run. Overlapping runs are prevented with database leases instead (see below). |
| Database | PostgreSQL + Alembic | Array columns and && overlap for tag filtering, partial unique indexes, ON CONFLICT upserts, CITEXT emails. |
| Routing | OSRM, self-hosted | Thousands of route queries per search would be expensive and slow with a per-request API. |
| Frontend | React 18 + TypeScript, Vite, Tailwind 4, shadcn/Radix, react-window |
Virtualized result list; typed API client mirrors the backend's Pydantic models. |
| Hosting | Docker → ECR → ECS | Same images in dev and prod. |
Data model
GopherDispatch keeps a local mirror of about 20 ServiceTitan entities, so searches run as single SQL queries against our own database rather than as fan-outs to a rate-limited third-party API. A simplified view:
erDiagram
COMPANY ||--o| ST_INTEGRATION : has
ST_INTEGRATION ||--o{ ST_SYNCHRONIZATION : runs
COMPANY ||--o{ EMPLOYMENT : employs
USER ||--o{ EMPLOYMENT : has
COMPANY ||--o{ STRIPE_SUBSCRIPTION : pays
COMPANY ||--o{ CUSTOMER_SEARCH : saves
COMPANY ||--o{ TECHNICIAN : mirrors
COMPANY ||--o{ CUSTOMER : mirrors
CUSTOMER ||--o{ LOCATION : "lives at"
CUSTOMER ||--o{ MEMBERSHIP : holds
CUSTOMER ||--o{ CALL : "phoned"
CUSTOMER ||--o{ ESTIMATE : "quoted"
LOCATION ||--o{ INSTALLED_EQUIPMENT : contains
LOCATION ||--o{ RECURRING_SERVICE : schedules
RECURRING_SERVICE ||--o{ RECURRING_SERVICE_EVENT : generates
LOCATION ||--o{ JOB : at
JOB ||--o{ APPOINTMENT : has
APPOINTMENT ||--o{ ASSIGNMENT : "assigned via"
TECHNICIAN ||--o{ ASSIGNMENT : works
CUSTOMER ||--o{ AI_CALL : receives
Engineering highlights
Route-insertion search, streamed over a WebSocket
backend/app/endpoints/call_contenders.py
sequenceDiagram
participant B as Browser
participant A as FastAPI
participant P as Postgres
participant O as OSRM
B->>A: WS connect + {search, date}
A->>P: technicians + that day's appointments
Note over A: compute each tech's free intervals<br/>(business hours − appointments)
loop pages of 100 eligible customers (keyset pagination)
A->>P: one composed SQL query for all filters
par per customer × per tech × per gap
A->>O: route with customer inserted
end
Note over A: keep the cheapest feasible insertion
A-->>B: batch (every ≤1 s or 100 results)
end
B-->>A: heartbeats (server stops work if they stop)
The interesting parts:
- Eligibility is one SQL query. Each filter in the table above compiles to a SQLAlchemy expression (
EXISTSsubqueries, array overlap, regex on equipment memos), and they're combined withAND. Pages use keyset pagination onid, so the work streams instead of loading everything up front. - Availability is set arithmetic. A small generic
IntervalMaskkeeps a sorted list of disjoint intervals with bisect-based insert and remove. Each technician's free time isbusiness hours − appointments. - Cheap pruning before expensive routing. A gap is skipped without calling OSRM if even a straight line at 80 mph plus a one-hour visit wouldn't fit. Surviving candidates are checked again with real arrive and depart times.
- Equivalent technicians are deduplicated. Techs with the same start and end points, the same appointments and the same filter config are tested once.
- Concurrency is bounded. Every (customer × technician × gap) route goes out at once through
asyncio.gather, over a sharedaiohttpsession capped at 32 connections, with retries and jitter. - Streaming UX. Results come back in batches every ≤1 s. The browser sends heartbeats, and if they stop (the tab closed or the user changed the search), the server cancels the work. A built-in
Timerlogs a per-stage latency breakdown for every search.
Self-hosted routing on the whole US road network
Each search can make thousands of route queries, so a commercial routing API would have been both slow and expensive. Instead, OpenStreetMap data from Geofabrik is pre-processed with OSRM's multi-level Dijkstra pipeline (extract → partition → customize). For the full US, that took about an hour and 91 GiB of RAM on a short-lived EC2 instance. The output goes to S3, and the instance is destroyed afterwards. The app then queries OSRM over its internal network at no per-request cost. update.py automates the download, extract and upload steps.
Incremental ServiceTitan sync with crash-safe leases
backend/app/tasks/service_titan_sync.py
- Incremental. Each sync requests only records with
modifiedOnOrAfter= the start of the last successful full sync, paging 5,000 at a time across about 20 endpoints. - Progress you can show a user. Before the first sync, the job sends one
pageSize=1&includeTotal=truerequest per endpoint in parallel to get an exact expected total. That total drives the onboarding progress bar. - Bulk upserts that respect Postgres limits.
INSERT … ON CONFLICT DO UPDATEis chunked so no statement goes over Postgres's 32,767 bind-parameter limit. - Leases instead of locks. A partial unique index allows only one
in_progresssync per integration. Each page pushes atimeout_atlease forward underSELECT … FOR UPDATE. A separate job marks stale syncstimed_out, so a crashed container never blocks an integration for good. - Selective re-syncs. One model can be force-refreshed without disturbing the incremental cursor. Selective syncs are flagged so they never count as a full sync.
AI agent that books real jobs
backend/app/endpoints/bland.py · tasks/resend_missed_bland_webhooks.py
- During a call, the voice agent uses two tools,
check-available-daysandcheck-available-times. Both run the same availability logic as the search, limited to company business hours. book-appointmentcreates the job in ServiceTitan with the right business unit, job type and campaign, then links it back to the call record.- Each call carries its own random secret. Tool requests must present that secret, and the post-call webhook must present it together with the matching call ID. A reconciliation job polls Bland for any call that's 30+ minutes old and still has no webhook, so a dropped webhook doesn't leave a call stuck.
- A global feature flag and a recipient override (to send every test call to one phone number) keep the feature safe in non-production environments.
Auth built from first principles
backend/app/endpoints/user_auth_providers.py · models/auth_credentials.py
- Argon2 password hashing. Sessions are opaque server-side secrets in a
Secure,SameSite=Laxcookie. - Google OAuth with account linking by verified email. Registration handoff payloads are signed with HMAC-SHA256 and checked with a constant-time compare.
- Email verification codes, password reset links, and expiring employee invitations (expired by a scheduled job).
Schema evolution in a live system
89 Alembic migrations over the life of the project. Columns are changed in safe steps: add as nullable → backfill → make NOT NULL (for example the recent estimates change). Indexes are added when real query plans call for them, such as created_at DESC composite indexes for "latest sync" lookups. Postgres enums are managed with alembic-postgresql-enum.
Infrastructure and CI/CD
flowchart LR
PR["Pull request"] --> BUILD1["Build backend image"] & BUILD2["Build nginx + SPA image"]
MAIN["Push to main"] --> PUSH1["Build + push backend → ECR"] & PUSH2["Build + push nginx → ECR"]
PUSH1 & PUSH2 --> MIG["Run Alembic migrations<br/>(one-off migrator container)"]
MIG --> DEP["aws ecs update-service<br/>--force-new-deployment"]
DEP --> WAIT["aws ecs wait services-stable"]
.github/workflows/build-migrate-deploy.yml
- On every PR, both production images are built, so a broken Dockerfile or a frontend type or build error fails the PR.
- On merge to
main: images are pushed to ECR with registry layer caching. Migrations run as a separate gated job before deploy, and deploy only starts if they succeed. ECS then does a rolling deployment, and the workflow waits for the service to stabilize, so a failed rollout shows up as a red build. - Production topology: nginx (serving the built SPA) and the FastAPI backend run as containers in one ECS task and talk over
localhost. OSRM is deployed in a separate ECS task so its can scale separately to the API layer. Postgres hosted on RDS. - Production ops: a
prod-replcontainer usesaws ecs execute-commandto open an IPython shell or run one-off programs in the live task, such as bulk customer import and deactivate, targeted re-syncs, and batch geocoding.
Local development
One docker compose up starts the full stack: Postgres, OSRM, the backend with hot reload, the Vite dev server, nginx, and a Cloudflare Tunnel. The tunnel gives the dev machine a real HTTPS domain, so OAuth callbacks and Stripe and Bland webhooks work locally exactly as they do in production.
Running it locally
The app depends on several third-party accounts (ServiceTitan developer app, Stripe, Bland, HERE, Maileroo, Google OAuth, Cloudflare). Copy
.env.exampleto.envand fill in what you have.
# 1. Routing data (one time). Defaults to California; see backend/osrm/README.md
cd backend/osrm && python update.py update && cd ../..
# 2. Start everything
docker compose up -d --build
# 3. Apply migrations
docker compose --profile migrations run --build --rm migrator upgrade head
# Create a migration after changing models
docker compose --profile migrations run --build --rm migrator revision --autogenerate -m "describe change"
# Run a one-off program against the dev stack
docker compose run --build --rm backend -m app.programs.resync campaigns
Repository tour
backend/
app/
endpoints/ 36 REST + WebSocket routes
call_contenders.py ← the search / route-insertion engine
bland.py ← AI-agent tool endpoints + webhook
tasks/ scheduled jobs (sync, timeouts, invite expiry, webhook replay)
programs/ one-off ops scripts (bulk import, resync, batch geocode)
algo/ IntervalMask, haversine geolocation, HMAC signing
service_titan/ typed async ServiceTitan client + Pydantic models
bland/ typed Bland AI client
models/ SQLAlchemy models (37 tables)
alembic/versions/ 89 migrations
osrm/ routing-data build tooling
frontend/src/
pages/Dashboard/ search, filters, technicians, onboarding, team, billing
api/ typed API client + useCustomerSearch WebSocket hook
.docker/ backend, migrator, nginx (dev/prod), prod-exec images
.github/workflows/ build → migrate → deploy
About 14k lines of Python and 11k lines of TypeScript, across 590+ commits from February 2025 to May 2026.
Retrospective
Why it's going offline
- ServiceTitan released an update to DispatchPro which does about 90% of what GopherDispatch does.
- Our estimates revealed that we couldn't reasonably compete; undercutting the price would not be sufficient.
What went well
- Partnering with existing companies to assist in development. Having guinea pigs was extremely useful and the feedback was paramount.
- Having the development environment be a near 1:1 mirror of production. This made development significantly easier, and it adds a layer of safety for AI assistance.
- Mirroring the CRM locally was the key decision. It turned "search across a rate-limited API" into "one SQL query", and made the routing engine practical.
- Self-hosting OSRM kept routing fast and free per request, at the cost of a one-time heavy preprocessing step.
What I'd do differently
- More closely work with partnered businesses during development. It was extremely useful, and we needed more of it. Next time: fly out and work on-site periodically.
- Add an automated test suite. This was deliberately postponed to get a working product ASAP, but was never re-prioritized.
- Secrets are passed into images as build args. I'd prefer to inject them at runtime from AWS Secrets Manager through the ECS task definition.
- The ECS cluster, task definitions and networking were set up by hand. Terraform or CDK would make the environment reproducible.
- The site works on mobile but does not scale well. Most dispatchers are working on computers so this was not prioritized, but it would be nice to have.

