How We Built a Sober Driver Booking System in Moldova: Real-time Dispatch with Node.js, Supabase & Vercel

dev.to

How We Built a Sober Driver Booking System in Moldova: Real-time Dispatch with Node.js, Supabase & Vercel
In September 2024, Moldova reclassified drunk driving from an administrative offense into a criminal offense — with prison sentences up to 4 years and fines reaching 150,000 MDL (~3,000 EUR).
This single legal change transformed the local market for designated driver services overnight. As the team behind PlusRent, a car rental and sober driver platform in Chișinău, we suddenly faced 3-5x more booking requests during peak hours (Friday-Saturday nights, 22:00-04:00).
Our existing manual dispatch system — phone calls, WhatsApp messages, Excel spreadsheets — became a bottleneck within weeks. We had to build something better.
This article documents the technical journey of building a real-time sober driver booking system that handles dispatch, GPS tracking, ETA calculation, and payment integration — using a serverless architecture on a startup budget.

Context: If you're curious about the legal side of why this market exploded, I wrote a separate piece on Moldova's 2026 DUI legislation covering all the legal details. This post focuses on the engineering side.

The Problem We Faced
A "sober driver" service has unique constraints that traditional rideshare apps don't address:

The driver drives the customer's car, not their own
Customer is intoxicated — UX must be foolproof
Peak hours are extreme — 80% of bookings happen in 6-hour windows
Geographic precision matters — restaurants, weddings, private addresses
Trust is critical — driver gets keys to expensive vehicles

Existing solutions like Yandex Go or Uber don't offer this service in Moldova. Local competitors used WhatsApp + manual dispatch — slow, error-prone, and unscalable.
We needed:

Real-time booking with under 30-second confirmation
Live driver GPS tracking
Automatic dispatch to nearest available driver
Customer-facing ETA updates
Multi-language UI (Romanian, Russian, English)
Payment options (cash + card)

All on a budget that wouldn't bankrupt a small startup.

Our Stack
After evaluating options, we chose:
Frontend: Next.js 14 (App Router)
Hosting: Vercel (Edge Functions)
Backend: Node.js + Supabase Edge Functions
Database: Supabase (PostgreSQL + Realtime)
Auth: Supabase Auth
Maps: Google Maps Platform
SMS: Twilio
Payments: Stripe + cash handling
Monitoring: Sentry + Vercel Analytics
Why this stack?

Vercel + Next.js: Zero-config deployment, edge functions for sub-100ms response globally
Supabase: PostgreSQL + Realtime WebSockets in one service. Replaces 3-4 separate services we'd otherwise need
Google Maps: No alternative comes close for Moldova's address coverage
Twilio: Reliable SMS for OTP and dispatch notifications

Total monthly infrastructure cost during MVP phase: ~$40/month. After scaling to current volume: ~$180/month.

Database Schema: The Foundation
The data model needed to handle three primary entities and their relationships:
sql-- Core tables (simplified)

CREATE TABLE drivers (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
phone TEXT UNIQUE NOT NULL,
full_name TEXT NOT NULL,
status TEXT CHECK (status IN ('offline', 'available', 'busy')),
current_location GEOGRAPHY(POINT, 4326),
rating NUMERIC(3,2) DEFAULT 5.00,
total_rides INTEGER DEFAULT 0,
created_at TIMESTAMPTZ DEFAULT now()
);

CREATE TABLE bookings (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
customer_phone TEXT NOT NULL,
pickup_location GEOGRAPHY(POINT, 4326) NOT NULL,
pickup_address TEXT NOT NULL,
destination_location GEOGRAPHY(POINT, 4326),
destination_address TEXT,
status TEXT CHECK (status IN (
'pending', 'assigned', 'en_route',
'arrived', 'in_progress', 'completed', 'cancelled'
)),
driver_id UUID REFERENCES drivers(id),
estimated_price NUMERIC(10,2),
final_price NUMERIC(10,2),
payment_method TEXT,
created_at TIMESTAMPTZ DEFAULT now(),
assigned_at TIMESTAMPTZ,
completed_at TIMESTAMPTZ
);

CREATE TABLE driver_locations (
driver_id UUID REFERENCES drivers(id),
location GEOGRAPHY(POINT, 4326) NOT NULL,
heading NUMERIC(5,2),
speed NUMERIC(5,2),
recorded_at TIMESTAMPTZ DEFAULT now()
);

-- Critical index for nearest-driver lookup
CREATE INDEX idx_drivers_location ON drivers
USING GIST(current_location)
WHERE status = 'available';

CREATE INDEX idx_bookings_status ON bookings(status, created_at);
The PostGIS extension on Supabase made geographic queries trivial. Finding the 5 nearest available drivers to a pickup point became a single query:
sqlSELECT
id,
full_name,
ST_Distance(current_location, $1::geography) AS distance_meters
FROM drivers
WHERE status = 'available'
AND ST_DWithin(current_location, $1::geography, 5000) -- 5km radius
ORDER BY current_location <-> $1::geography
LIMIT 5;
This query runs in ~3-8ms even with thousands of bookings in history.

The Dispatch Algorithm
The hardest engineering problem was the dispatch algorithm. Naive "nearest driver" doesn't work because:

A driver 1km away with rating 4.2 is worse than one 1.5km away with rating 4.9
A driver who just finished a ride 2km away might decline; a driver idle for 20 minutes will accept
Some drivers prefer specific zones; Friday-night dispatching to a known difficult area shouldn't go to a new driver

We ended up with a weighted scoring algorithm:
javascript// Simplified scoring logic
function scoreDriver(driver, booking) {
const distanceKm = haversine(driver.location, booking.pickup);

// Distance: closer is better, but with diminishing returns
const distanceScore = Math.max(0, 100 - (distanceKm * 15));

// Rating: higher is better (4.0 = 60pts, 5.0 = 100pts)
const ratingScore = (driver.rating - 4) * 100;

// Idle time: drivers idle 5-20 min are eager
const idleMinutes = (Date.now() - driver.last_active) / 60000;
const idleScore = idleMinutes > 5 && idleMinutes < 20 ? 20 : 0;

// Zone familiarity: bonus for drivers with rides in this area
const zoneScore = driver.zones.includes(booking.pickup_zone) ? 15 : 0;

// Weights
return (
distanceScore * 0.5 +
ratingScore * 0.25 +
idleScore * 0.15 +
zoneScore * 0.10
);
}

async function dispatchBooking(bookingId) {
const booking = await getBooking(bookingId);
const candidates = await getNearbyAvailableDrivers(booking.pickup, 5000);

if (candidates.length === 0) {
return { error: 'no_drivers_available' };
}

const ranked = candidates
.map(d => ({ driver: d, score: scoreDriver(d, booking) }))
.sort((a, b) => b.score - a.score);

// Try top 3 in parallel with race condition handling
for (const { driver } of ranked.slice(0, 3)) {
const accepted = await offerToDriver(driver.id, bookingId, 30_000);
if (accepted) {
return { driver_id: driver.id };
}
}

return { error: 'all_drivers_declined' };
}
The 30-second offer window with sequential fallback proved critical. Customers wouldn't wait longer than 60 seconds for confirmation.

Real-time Updates with Supabase
The customer experience requires live updates: "Your driver is 3 minutes away" → "Your driver has arrived" → "Trip in progress."
Supabase's realtime PostgreSQL subscriptions made this surprisingly simple:
javascript// Customer's frontend subscribes to their booking
const channel = supabase
.channel(booking_${bookingId})
.on(
'postgres_changes',
{
event: 'UPDATE',
schema: 'public',
table: 'bookings',
filter: id=eq.${bookingId}
},
(payload) => {
updateUI(payload.new);
}
)
.subscribe();
For driver location updates, we initially used PostgreSQL realtime as well — sending location every 5 seconds. This crashed our database connections at scale.
The fix: a separate Supabase Edge Function that wrote driver locations to a Redis-like cache (we used Upstash) and only persisted to PostgreSQL every 30 seconds for analytics. Real-time location was streamed via WebSocket directly:
javascript// Driver app sends location to Edge Function
async function broadcastLocation(driverId, lat, lng) {
await fetch('/api/driver-location', {
method: 'POST',
body: JSON.stringify({ driverId, lat, lng, ts: Date.now() })
});
}

// Edge function broadcasts to customer's WebSocket channel
// (only if customer has active booking with this driver)
This reduced database load by 95% while keeping sub-second update latency.

Multi-language Support: The Hidden Challenge
Moldova has 3 active languages: Romanian (official), Russian (widely spoken), and English (for tourists). The naive approach — t('booking.confirm') — falls apart when:

Drivers receive SMS dispatch in Romanian
The same booking shows in admin dashboard in English
Customer sees confirmation in Russian
Receipt PDF is in Romanian

We built a language matrix at the database level:
sqlCREATE TABLE translations (
key TEXT NOT NULL,
language TEXT NOT NULL,
value TEXT NOT NULL,
context TEXT,
PRIMARY KEY (key, language, context)
);
Each user/driver has a preferred_language field. SMS, push notifications, emails, and PDFs all query this table. The customer-facing UI uses Next.js i18n, but server-generated content (notifications, receipts) goes through the database.
A side benefit: we let customer support staff edit translations in real-time without redeploying.

Payment Integration: Card + Cash Reality
Western tutorials assume Stripe-only. In Moldova, 70% of payments are cash. This required dual-flow support:
javascript// Payment options shown to customer
const PAYMENT_METHODS = {
card: {
flow: 'stripe',
capture: 'immediate',
deposit: true,
},
cash: {
flow: 'manual',
capture: 'on_completion',
deposit: false,
},
};

// On booking completion
async function completeBooking(bookingId, paymentMethod) {
const booking = await getBooking(bookingId);

if (paymentMethod === 'card') {
await stripe.paymentIntents.capture(booking.stripe_intent_id);
} else {
// Cash: driver confirms collection in app
await markBookingCashCollected(bookingId);
await scheduleDriverPayout(booking.driver_id);
}

await sendReceipt(booking);
await updateDriverEarnings(booking.driver_id, booking.final_price);
}
Cash handling required additional complexity: driver shift reconciliation, daily settlement, and a "trust score" system to flag drivers with consistent cash discrepancies.

Deployment & Monitoring
Deploying with Vercel + Supabase was almost too easy:
bash# Push to main branch
git push origin main

Vercel automatically:

1. Builds Next.js app

2. Runs migrations on Supabase

3. Deploys edge functions

4. Updates DNS

The catch: edge functions have a 10-second execution limit. Long-running operations (driver payouts, daily reconciliation) had to move to scheduled Supabase functions or external workers.
Sentry caught most production issues, but the most valuable monitoring was custom: a real-time dashboard showing active bookings, average ETA, driver utilization, and dispatch success rate. When dispatch_success_rate dropped below 85%, alerts fired.

What We'd Do Differently
If starting today, we'd consider:

TanStack Query instead of native React state for booking data — we hit cache invalidation issues with manual implementation
Bun instead of Node.js for backend functions — ~3x faster cold starts
PartyKit or Cloudflare Durable Objects for real-time location instead of Upstash + Edge Functions — simpler architecture
PostHog for product analytics from day one — we added it 6 months in and lost valuable behavior data

We don't regret choosing Supabase. The combination of PostgreSQL + Auth + Realtime + Storage + Edge Functions in one service saved us months of integration work.

Results After 12 Months
The numbers (rounded for simplicity):

Average dispatch time: 22 seconds (down from 8+ minutes manual)
Booking-to-pickup time: 18 minutes average
Customer satisfaction: 4.9/5 across 27+ Google reviews
Driver retention: 85% after 3 months (industry avg is ~50%)
Peak concurrent bookings: 40+ on weekend nights
Infrastructure cost per booking: ~$0.12

The system handles current volume comfortably. The next bottleneck will be human (driver capacity) rather than technical.

Closing Thoughts
Building a sober driver platform in a market of 2.5 million people taught us that "small market" doesn't mean "simple problem." The legal context, language complexity, payment culture, and trust dynamics required engineering solutions that wouldn't appear in a typical SaaS playbook.
For technical founders building local services in non-Western markets: don't over-index on Silicon Valley patterns. Cash payments are real. SMS still beats push notifications for older demographics. Local language nuance matters more than you think.
The full stack — Node.js, Supabase, Vercel, Next.js — proved that small teams can ship serious infrastructure without enterprise budgets.
If you're working on similar problems (dispatch systems, real-time tracking, multi-language services in emerging markets), I'm happy to discuss specifics in the comments.

The legal context for this project is covered in detail in our Moldova DUI legislation guide on Medium.
The platform itself runs at plusrent.md.

Source: dev.to

arrow_back Back to News