Caution

GopherDispatch has been taken offline. This repository is kept as an archive. See the Retrospective to understand why.

GopherDispatch logo

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.

Python FastAPI PostgreSQL React TypeScript Tailwind Docker AWS ECS Stripe

Every name, address and phone number in this README is seeded demo data.


Contents


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:

  1. find members who are due for a visit,
  2. work out which of them are near where that technician already is,
  3. check that the time actually works once you add the driving, and
  4. 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.

Find Customers results table

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

Search filters

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.

Technician configuration

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.

Recent AI calls

5. Self-serve onboarding, billing and teams

Onboarding First sync
Enter tenant ID Sync progress

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:

Self-hosted routing on the whole US road network

backend/osrm/

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

AI agent that books real jobs

backend/app/endpoints/bland.py · tasks/resend_missed_bland_webhooks.py

Auth built from first principles

backend/app/endpoints/user_auth_providers.py · models/auth_credentials.py

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

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.example to .env and 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

What went well

What I'd do differently


Built by Gabe Millikan · LinkedIn