Deployment
Production deployment for a self-hosted licensee (own server, DB, domain, branded apps — not SaaS, per spec Section 1).
Architecture
┌────────────┐ ┌──────────────────┐
clients → │ reverse │ ───→ │ backend (NestJS) │ ──→ Postgres+PostGIS
(apps, │ proxy/SSL │ │ (1..N instances) │ ──→ Redis (cache,
web) └────────────┘ └──────────────────┘ queues, sockets)
One backend container runs everything: the API, the WebSockets, the scheduled jobs and the queue worker. To grow, run several API containers behind a load balancer and a separate worker — see Scaling out. The Socket.IO Redis adapter fans realtime events across the API containers, and Redis decides which one container runs the scheduled jobs.
Build & run with Docker
install/ runs the whole platform — Postgres+PostGIS, Redis, the API, the
admin and your website — from install/docker-compose.yml, configured by
install/.env:
cd install
./install.sh # first time: secrets, build, migrations, first admin
docker compose up -d --build # after an update, or after changing install/.env
Every port is published on 127.0.0.1 only (Postgres and Redis not at all);
put the reverse proxy below in front of the API, admin and website. On a
server, set PUBLIC_API_URL, PUBLIC_ADMIN_URL and PUBLIC_WEBSITE_URL in
install/.env to your HTTPS addresses before building: the admin and website
have the API address built in, and the API accepts browser calls only from
the other two (CORS_ORIGINS).
The image:
- runs as the non-root
nodeuser, - contains only production dependencies + compiled
dist, - is ~480 MB.
Production checklist
-
NODE_ENV=production(the install kit sets it). -
APP_SECRET_KEYset and backed up — it encrypts the provider keys stored in Admin → Providers (install.shgenerates it). - Strong, unique
JWT_ACCESS_SECRET/JWT_REFRESH_SECRET(32+ chars). Boot fails otherwise. -
CORS_ORIGINSset to your real front-end origins. Boot fails in prod if empty (no reflect-any-origin). -
STORAGE_DRIVER=s3with bucket + keys configured. -
SENTRY_DSNset so 5xx errors are reported. - A real SMS provider (Twilio / MSG91) configured in Admin → Settings.
The default
logprovider only writes to the server log — with it, an SOS records the incident and mints the live-trip link but no trusted contact is ever actually texted. The admin safety queue labels such incidents, but the alert did not leave the server. - TLS terminated at the reverse proxy (Nginx/Caddy/ALB); HTTPS only.
- Database backups + PITR configured.
- Run migrations against the production DB on each release — see below.
- Restrict the DB role: it should not have
TRUNCATE/DROPon ledger tables (immutability is also enforced at the role level).
Running migrations in production
npm run migration:run uses typeorm-ts-node-commonjs, which needs ts-node —
a devDependency. The production image ships only production dependencies and the
compiled dist, so that script fails there with MODULE_NOT_FOUND. Use the
compiled data source instead:
cd install
docker compose exec backend \
node node_modules/typeorm/cli.js migration:run -d dist/database/data-source.js
npm run migration:run remains correct for local development and CI, where dev
dependencies are installed.
CI/CD
/.github/workflows/backend-ci.yml
runs on every push/PR touching backend/:
- lint (zero warnings) → build → run migrations against a real Postgres+PostGIS service → test,
- build the Docker image.
Mobile store builds (rider + driver apps)
Both apps use Expo SDK 54 with dynamic app.config.ts (env-driven) and EAS
build profiles in each app's eas.json (development / preview /
production). White-label vars (APP_NAME, APP_ICON, bundle IDs, API URLs)
are documented in each app's ENV.md and in Installation docs.
Per app (mobile/rider, mobile/driver), from that directory:
Building locally instead of EAS
mobile/scripts/build-store-aab.sh <rider|driver|partner> [--apk] [--version-code N]
produces a signed Android App Bundle (and a universal APK with --apk) from a
freshly generated native project, on any Mac/Linux with the Android SDK and
JDK 17 or 21:
- Signing comes from the environment, never from an edited Gradle file:
RIDEKIT_UPLOAD_STORE_FILE,RIDEKIT_UPLOAD_STORE_PASSWORD,RIDEKIT_UPLOAD_KEY_ALIAS,RIDEKIT_UPLOAD_KEY_PASSWORD(put them in~/.ridekit/upload.env, or export them). The Expo config pluginplugins/withReleaseSigning.jsin each app patches the generatedandroid/app/build.gradleon every prebuild, so the release build type uses your upload keystore when these are set and the debug keystore otherwise. Generate a keystore once (keytool -genkeypair …) and back it up. - Build env comes from the app's
.env.production(EXPO_PUBLIC_API_URL,EXPO_PUBLIC_SOCKET_URL,GOOGLE_MAPS_API_KEY, brand overrides). - Version code:
ANDROID_VERSION_CODE(or--version-code) must increase on every store upload;IOS_BUILD_NUMBERis the iOS equivalent. - The script runs
expo prebuild --clean, then Gradle, copies the outputs tomobile/build/<app>/, and restoresandroid/to the committed state — it fails if git still sees a change there, so a Maps key can never be committed by accident.
# one-time: authenticate + create the EAS project
npx eas login
npx eas init # sets EAS_PROJECT_ID
# config-level validation (no native toolchain needed)
npx expo config --type public # env resolves; prod build throws on localhost URLs
npx expo prebuild --clean # regenerate native projects (picks up new icons)
# Android — produces an .aab for the Play Store
npx eas build -p android --profile production
# iOS — produces an .ipa for App Store Connect
npx eas build -p ios --profile production
# Submit (or upload the artifact manually)
npx eas submit -p android --profile production
npx eas submit -p ios --profile production
Codemagic (configured — codemagic.yaml at the repo root)
Four workflows ship ready: rider-android, rider-ios, driver-android,
driver-ios. Point Codemagic at this repo and they appear automatically.
Create these variable groups in the Codemagic UI, every value marked Secure:
| Group | Variables |
|---|---|
kashvi_api |
EXPO_PUBLIC_API_URL, EXPO_PUBLIC_SOCKET_URL |
maps |
GOOGLE_MAPS_API_KEY |
branding |
APP_NAME, APP_SCHEME, IOS_BUNDLE_ID, ANDROID_PACKAGE (optional — defaults ship) |
google_play |
GCLOUD_SERVICE_ACCOUNT_CREDENTIALS (Play Console → API access → JSON) |
appstore |
App Store Connect API key — attach it as the kashvi_app_store_key integration |
Then upload your Android keystore under Code signing identities and name it
kashvi_keystore.
Two things the workflows do that are easy to get wrong by hand:
expo prebuild --cleanruns on every build. Theios/andandroid/folders are generated output and are not in the repository (they are git-ignored, because a generated manifest is where your Maps key lands). Everything native — the location module, the scene lifecycle on iOS, release signing — is applied byexpo prebuildfrommodules/and the config plugins, so a fresh prebuild is always the complete project.- They assert the result. After prebuild, the Android workflows grep the
generated manifest for the real Maps key (and, for the driver app, for
ACCESS_BACKGROUND_LOCATION/FOREGROUND_SERVICE_LOCATION) and fail the build if it is absent. A missing Maps key otherwise produces a perfectly successful build that renders a blank grey map on every device.
Both store publish steps are intentionally conservative: Play uploads to the
internal track as a draft, and iOS goes to TestFlight but not straight to the
App Store. Promote from each console once you have looked at the build.
Never commit the real Maps key. This product ships as a source zip. A key baked into
android/app/src/main/AndroidManifest.xmlwould reach every buyer and bill you. The committed manifest carries a placeholder on purpose; the real key is injected by CI at prebuild time and never lands in git.
Supplying the build secrets (do this BEFORE your first production build)
A production build fails fast on purpose if the API/socket URLs are missing,
point at localhost or a LAN address, or the Maps key is empty
(app.config.ts). That guard is what stops a store binary shipping pointed at a
dev machine — so the build cannot succeed until you provide real values.
Do NOT put production values in a .env file: every .env* is git-ignored, and
a file on disk is easy to leak. Use EAS secrets, which are injected as env vars
at build time. Run these once per app (mobile/rider, then mobile/driver):
npx eas secret:create --scope project --name EXPO_PUBLIC_API_URL --value "https://api.yourdomain.com/api"
npx eas secret:create --scope project --name EXPO_PUBLIC_SOCKET_URL --value "https://api.yourdomain.com"
npx eas secret:create --scope project --name GOOGLE_MAPS_API_KEY --value "AIza..."
# White-label identity — only if you are rebranding from the defaults
npx eas secret:create --scope project --name APP_NAME --value "Your Brand"
npx eas secret:create --scope project --name IOS_BUNDLE_ID --value "com.yourbrand.rider"
npx eas secret:create --scope project --name ANDROID_PACKAGE --value "com.yourbrand.rider"
npx eas secret:list # verify before building
If you change any identity value you must re-run npx expo prebuild --clean.
The ios/ and android/ folders are committed, and EAS uses an existing native
project as-is rather than regenerating it — so without that step the build keeps
the old app name and bundle id. The same applies to GOOGLE_MAPS_API_KEY: it is
written into android/app/src/main/AndroidManifest.xml at prebuild time, so
setting the secret alone leaves Android maps blank.
What you must obtain yourself
These cannot be generated from this repo — they are accounts and keys tied to you as the publisher:
| What | Where | Needed for |
|---|---|---|
| Expo account | expo.dev | eas login, running any cloud build |
| Apple Developer Program ($99/yr) | developer.apple.com | iOS builds + App Store submission |
| Google Play Developer ($25 one-time) | play.google.com/console | Play Store submission |
| Android upload keystore | eas credentials can generate and store it |
signing the .aab |
| Google Maps API key | console.cloud.google.com | maps in both apps |
| Play service-account JSON | Play Console → API access | eas submit -p android |
Verified locally so far
The following were built and inspected on a developer machine, so the native projects are known-good before you spend a cloud build:
- Driver Android debug APK — builds; the generated manifest carries
ACCESS_BACKGROUND_LOCATION,FOREGROUND_SERVICE_LOCATIONand the Maps key. - Rider iOS simulator build — builds as a universal (arm64 + x86_64) binary.
No signed release artifact has been produced, because that needs the credentials above. The remaining risk is therefore credential/store configuration, not code.
Pre-submission checklist:
- Real, distinct per-app icons/splash (see
BRANDING-ASSETS.md) — the placeholder is shared across both apps and stores reject duplicates. - Production
EXPO_PUBLIC_API_URL/EXPO_PUBLIC_SOCKET_URL(HTTPS, not localhost/LAN — the prod build fails fast otherwise). - Google Maps key restricted to the app's Android package + SHA-1 and iOS bundle id.
- Store listings, privacy policy, and (driver app) background-location justification prepared.
Where personal data lives (Saudi Arabia and other residency markets)
Saudi Arabia's PDPL, and TGA's rules for licensed passenger-transport platforms, expect riders' and drivers' personal data to be kept in the Kingdom. Transfers abroad need a basis (an adequacy decision, SDAIA's standard contractual clauses, consent) and a documented risk assessment. India (MoRTH 2020) has the same in-country rule.
To keep the core data in the country, host these in a data centre inside it:
- The database (Postgres): every account, trip, payment and consent.
- Redis: live locations and sessions.
- Object storage (S3 or local disk): identity documents, selfies and invoices. With S3-compatible storage, choose a bucket region in the country, and record it under Admin → Data protection → Object storage.
- The API and admin servers.
Clouds with Saudi regions include Google Cloud (Dammam), Oracle (Jeddah and Riyadh) and local providers such as STC Cloud. Confirm the region with the provider, because availability changes.
Some integrations send data abroad by their nature, for example map search, push notifications and SMS. Admin → Data protection lists each one, what it receives and where it goes. It flags any transfer that is still missing a recorded safeguard and assessment date. Keep that page complete before launch.
Market config dataResidency.required is on for India and Saudi Arabia.
Health & observability
GET /api/health— readiness (DB + Redis). Returns 503 if either is down — wire this to your load-balancer / k8s readiness probe.- Structured JSON logs (pino) with request-id correlation.
- Sentry captures 5xx + unhandled errors (and they're always logged locally too, even without a DSN).
Scaling out
install/docker-compose.multi.yml runs the platform with the API scaled out:
┌──────┐ ┌────────────┐
HTTPS ──→ │ lb │ ──→ │ api × N │ ──┐
proxy │nginx │ │ (HTTP, WS) │ ├──→ Postgres+PostGIS
└──────┘ └────────────┘ ├──→ Redis (adapter, queues,
┌────────────┐ │ scheduler lease, locks)
│ worker × 1 │ ──┘
│ (cron jobs,│
│ queues) │
└────────────┘
cd install
docker compose down # stop the single-container stack (data stays)
docker compose -f docker-compose.multi.yml up -d --build
API_REPLICAS=4 docker compose -f docker-compose.multi.yml up -d # more API containers
What makes several instances safe:
- Scheduled jobs run once. The instances elect one leader through a Redis
lease (
scheduler:leader, 30 s, renewed every 10 s), and only the leader runs the cron jobs. If it stops, another takes over within about 30 s. The API containers setRUN_SCHEDULER=falseand stay out of the election. - Dispatch has one owner per ride. A Redis lock per ride decides which
instance runs its offer loop. A driver's decline, an accept or a fare raise
that reaches another instance is published on
dispatch:control, and the owner acts at once. - Bulk work runs on the worker. Broadcasts are queued (BullMQ
notifications) and delivered by the worker in chunks. The API containers setRUN_WORKERS=false. - No sticky sessions. Every client uses the WebSocket transport only, so nginx balances round-robin.
- Uploads. The containers share one
storagevolume on one machine. Across machines, switchSTORAGE_DRIVERto S3/R2.
Postgres and Redis are the shared state: size them first. Every GPS fix is a short Postgres transaction, so the database is the first thing a fleet's growth reaches.
Load test
Measured on 2026-11-25 with tools/loadtest
(k6).
Setup. One MacBook ran everything: Docker Desktop with 12 CPUs and 8 GB, holding Postgres, Redis, two API replicas, the worker, the nginx load balancer and the k6 load generator itself.
What each simulated driver did. It went online, held a live Socket.IO WebSocket, and sent a GPS fix every 5 seconds — the same requests the driver app makes.
| Drivers online (held 4 min) | GPS fixes sent | Succeeded | GPS median | p95 | p99 | Socket connect p95 |
|---|---|---|---|---|---|---|
| 2,000 (≈400 fixes/s) | 141,181 | 99.999 % | 5 ms | 119 ms | 272 ms | 9 ms |
| 3,000 (≈600 fixes/s) | 228,360 | 100 % | 17 ms | 140 ms | 1.6 s | 14 ms |
The 2,000-driver row was measured before the change below. At 3,000 drivers every driver went online and every socket connected.
What we changed on the way:
- Postgres was the first ceiling. Every GPS fix ran the ride-only
statements — odometer and path breadcrumb, each in a savepoint — even for
drivers with no ride.
- At 3,000 drivers Postgres used about 450 % CPU, p95 reached about 3 s, and about 0.06 % of fixes failed.
- A fix now looks up the driver's live ride once and skips that work when there is none. Postgres dropped to about 120 % CPU, and the 3,000-driver row above is the result.
- The load balancer opened a new connection per request. That cost it more
CPU (380 %) than the API and reset connections at the peak. It now keeps
connections alive (
keepalive), and its CPU fell to about 20 %.
Where this machine stopped. At 5,000 drivers about 18 % of requests failed, and going to four API replicas did not help. The laptop itself was full: k6, Postgres and the API containers together used about 10 of its 12 CPUs. Real numbers beyond 3,000 need Postgres on its own server and the load generator on another machine; we have not measured that setup yet.
The k6 script reconnects at once when a socket drops, so a saturated run turns into a reconnect storm. The apps back off between attempts, so real clients degrade more gently.