Nearby Drivers API
An Uber-style driver discovery system exploring geospatial search, Top-K selection, and practical backend engineering.

Nearby Drivers API
An Uber-style driver discovery system exploring geospatial search, Top-K selection, and practical backend engineering.
Tech stack: TypeScript · Node.js · Express · React/Next.js (interactive case-study demo) · Postman · Newman
Source code: Nearby Drivers API on GitHub
Postman collection: API collection and environment
Demo note: The interactive visualization below runs entirely in the browser using simulated driver data. It demonstrates the same selection concepts as the Express backend, but it does not make live API requests.
Overview
A ride-hailing service needs to locate drivers near a passenger's pickup point. The problem becomes more interesting when the system must return several nearby candidates while excluding drivers who are offline, blocked, or already contacted.
I built a REST API to explore these requirements and compare two Top-K selection approaches: sorting every eligible candidate and retaining only the best K candidates in a bounded max-heap.
The project prioritizes clear algorithm boundaries, input validation, deterministic results, and reproducible tests.
The problem
Given a passenger's pickup coordinates and a set of drivers, the system should:
- Ignore unavailable drivers.
- Exclude blocked and previously contacted driver IDs.
- Calculate geographic distances from the pickup location.
- Optionally restrict candidates to a search radius.
- Return either the single nearest driver or the K nearest eligible drivers.
- Break equal-distance ties consistently using driver IDs.
The backend uses the Haversine formula to estimate great-circle distances on Earth. These distances are geographic estimates, not road-network driving distances or pickup ETAs.
Interactive algorithm playground
Change the algorithm, number of drivers, search radius, and exclusions to see how the selected candidates change.
Driver selection playground
Browser simulation — not a live API
Selected drivers (3)
Distances use Haversine calculations. The diagram is schematic, not a road map.
Architecture
The backend is organized into four layers:
| Layer | Responsibility |
|---|---|
| Routes | Receive HTTP requests and return consistent JSON responses. |
| Services | Validate inputs and coordinate the repository and algorithms. |
| Algorithms | Perform Haversine distance calculations, linear scanning, sorting, and heap-based selection. |
| Repository | Store drivers in an in-memory Map<string, Driver> for fast ID-based lookup. |
The application factory supports dependency injection: tests can create a fresh repository for each Express app, preventing state from leaking between integration tests.
Data flow
Client request
|
v
Express route
|
v
Service (validation + orchestration)
|
+----> Driver repository (in-memory Map)
|
v
Pure selection algorithm
|
v
Ranked JSON response
The backend lives in its own repository. This Next.js page is documentation and a self-contained browser simulation, not a second API implementation or a deployed backend client.
Core algorithms
1. Nearest available driver — linear scan
For a single nearest driver, a linear scan is enough. Visit each driver once, skip unavailable drivers, calculate the Haversine distance, and retain the closest eligible candidate.
- Time: O(n)
- Algorithmic extra space: O(1)
- Use case: Find one closest available driver without sorting the entire dataset.
2. Top-K drivers — sorting
Filter eligible drivers, calculate their distances, sort them from nearest to farthest, and take the first K.
- Time: O(n + r log r), where r is the number of eligible candidates, excluding the cost of constructing exclusion sets.
- Candidate storage: O(r)
- Use case: A straightforward baseline that is easy to inspect and verify.
3. Top-K drivers — bounded max-heap
Maintain a max-heap of at most K candidates. The root represents the worst retained candidate (farthest away, with deterministic ID tie-breaking). When a better driver appears, replace the root. Finally, sort the retained K candidates for the API response.
- Time: O(n + r log k + k log k), excluding the cost of constructing exclusion sets.
- Heap storage: O(k)
- Use case: Find a small number of nearest drivers from a large candidate pool.
Both Top-K strategies use JavaScript Set objects for blocked and contacted driver IDs, enabling average-case O(1) membership checks. Constructing those sets costs time and space proportional to their input sizes.
Complexity comparison
| Approach | Time complexity | Selection storage | Best for |
|---|---|---|---|
| Linear scan | O(n) | O(1) | One nearest driver |
| Full sorting | O(n + r log r) | O(r) | Simplicity and baseline verification |
| Bounded max-heap | O(n + r log k + k log k) | O(k) | Small K relative to candidate count |
Memory caveat: The current backend repository returns a materialized array through findAll(), which uses O(n) additional memory for the complete request. The heap's O(k) bound applies to its retained candidate selection structure, not the entire HTTP request. A streaming repository interface would better preserve that memory advantage.
REST API
| Method | Endpoint | Description |
|---|---|---|
GET | /health | Health check |
POST | /api/drivers | Register a driver |
GET | /api/drivers | List drivers |
GET | /api/drivers/:id | Retrieve a driver |
PATCH | /api/drivers/:id | Update location or availability |
GET | /api/drivers/nearest | Find the nearest available driver |
GET | /api/drivers/nearby | Find Top-K eligible drivers |
Example: Top-K request
GET /api/drivers/nearby?lat=26.1445&lng=91.7362&limit=3&strategy=heap&blockedIds=D2&contactedIds=D5
The API returns the selected drivers in ascending distance order, with distances in kilometers. The strategy parameter accepts sort or heap; an optional radiusKm parameter restricts the search area.
Error handling
The API validates coordinate ranges, numeric limits, driver IDs, request bodies, and supported strategies. It uses consistent JSON errors, including:
- 400 for invalid input or malformed JSON.
- 404 when a requested driver does not exist.
- 409 when registering a duplicate driver ID.
When no drivers qualify for a nearby search, the API returns a successful response with an empty drivers array rather than treating the result as a server error.
Testing and reliability
I used multiple testing layers:
- Unit tests: Haversine distance, nearest-driver selection, availability filtering, radius behavior, and deterministic tie-breaking.
- Algorithm equivalence tests: Compare sorting and heap results across reproducibly generated datasets.
- Isolated integration tests: Create a fresh in-memory repository for each Express app to prevent test-order dependencies.
- Postman and Newman: Exercise API success and failure scenarios using reusable environment variables and automated response assertions.
The Postman collection includes 15 requests covering driver management, nearest and Top-K searches, exclusions, and invalid inputs.
Benchmark methodology
A benchmark script generates datasets with 100, 1,000, 10,000, and 100,000 drivers and compares sorting against heap selection for K = 5 and K = 50.
The benchmark uses seeded data, warm-up runs, and median timings. Results depend on the Node.js version, hardware, JavaScript engine optimization, and runtime conditions; I avoid claiming a fixed speedup without measured evidence.
To reproduce the benchmark in the backend repository:
npm run benchmark
Engineering decisions and tradeoffs
Why Map for driver storage? It supports average-case O(1) lookup and updates by driver ID. However, finding nearby drivers still requires geographic candidate evaluation.
Why Set for exclusions? It avoids repeated linear scans through blocked or contacted ID lists.
Why keep both sorting and heap implementations? Sorting is a readable correctness baseline. The bounded heap offers better asymptotic selection performance when K is small relative to the candidate pool.
Why use dependency injection? Independent repositories make integration tests reproducible and reduce accidental coupling.
Why use an in-memory store? It keeps the project focused on DSA and API design. The tradeoff is that data does not survive server restarts.
What I would improve next
- Persistent storage: Replace the in-memory
Mapwith a database while preserving the repository interface. - Geospatial indexing: Reduce the candidate set before computing precise distances.
- Road-network routing: Use graph algorithms and real road distances instead of straight-line geographic distance.
- Traffic-aware ETA: Rank candidates by expected pickup time rather than distance alone.
- Streaming selection: Avoid materializing every driver when using the bounded heap.
- Deployment and observability: Add production configuration, structured logging, metrics, and API monitoring.
Key takeaways
This project connected familiar data structures to a realistic backend workflow:
- A linear scan is sufficient for a single nearest candidate.
- A max-heap can retain only the K best candidates without sorting all eligible drivers.
- Maps and Sets solve different lookup and filtering problems.
- Deterministic ordering and algorithm equivalence tests improve correctness.
- Dependency injection makes integration tests independent and reliable.
- Benchmarks help evaluate real runtime tradeoffs beyond Big O notation.
Explore the implementation: Backend repository · Postman collection