A backend WebSocket service built with Node.js that securely ingests, processes, and broadcasts live geolocation coordinates for mobile or web-based tracking platforms.
- Overview
- Core Features
- Architecture
- Getting Started
- API / WebSocket Protocol
- Testing
- Project Waves & Issue Tracking
- Contributing
- License
The Real-Time Spatial Tracking Gateway is the central data-plane component of a real-time location system. It accepts persistent WebSocket connections from thousands of concurrent mobile or web clients, validates incoming GPS/GNSS payloads, and intelligently routes location updates to the appropriate subscribers using a room-based broadcasting model.
This service is designed for low-latency, high-throughput telemetry scenarios such as fleet tracking, asset monitoring, geofencing enforcement, and live mapping.
- WebSocket Connection Lifecycle – Full session management from handshake through heartbeat to graceful teardown, with automatic cleanup of orphaned connections.
- Room-Based Broadcasting – Clients join logical rooms (e.g., fleet ID, region, user group); location updates published to a room are fanned out to all members in real time.
- Payload Validation – Incoming coordinate data is validated against strict schemas before any processing or storage; malformed payloads are dropped immediately with a descriptive error response.
- Secure Ingestion – Supports token-based authentication at connection time; all communication runs over
wss://in production. - Graceful Cleanup – Disconnection events trigger full teardown of associated subscriptions, in-memory state, and room membership, ensuring a leak-free runtime.
- Observability – Structured logging for connection events, message throughput, validation failures, and errors, enabling operational dashboards.
- Extensible Storage Adapter – Plug in your preferred database (PostgreSQL, MongoDB, InfluxDB, etc.) for persisting historical tracks.
┌──────────────┐ wss:// ┌─────────────────────────────────────┐
│ Mobile/Web │ ──────────────▶ │ Real-Time Tracking Gateway │
│ Clients │ ◀────────────── │ │
└──────────────┘ │ ┌───────────┐ ┌──────────────┐ │
│ │ Auth │ │ Validator │ │
│ │ Middlewar │ │ (Zod/Joi) │ │
│ └─────┬─────┘ └──────┬───────┘ │
│ │ │ │
│ ┌─────▼─────────────────▼───────┐ │
│ │ Room Manager │ │
│ │ (Map<RoomId, Set<Client>>) │ │
│ └─────────────┬───────────────┘ │
│ │ │
│ ┌─────────────▼───────────────┐ │
│ │ Storage Adapter │ │
│ │ (Postgres / Mongo / etc.) │ │
│ └─────────────────────────────┘ │
└─────────────────────────────────────┘
- Single-process, async I/O – Node.js event loop handles thousands of concurrent connections without thread-per-connection overhead.
- Room map in memory – Subscriptions live in a
Map<RoomId, Set<WebSocket>>for O(1) broadcast dispatch; no external pub/sub dependency required for single-instance deployments. - Pluggable serialization – JSON by default; MessagePack or Protocol Buffers can be substituted for bandwidth-constrained links.
- Backpressure awareness – The broadcaster respects
wsbackpressure signals to avoid overwhelming slow consumers.
- Node.js >= 18.x (LTS recommended)
- npm >= 9.x or yarn >= 1.22
- A running PostgreSQL instance (or other supported database) if persistence is enabled
git clone https://github.com/your-org/real-time-spatial-tracking-gateway.git
cd real-time-spatial-tracking-gateway
npm installCopy the environment template and adjust values:
cp .env.example .env| Variable | Default | Description |
|---|---|---|
PORT |
8080 |
WebSocket server listen port |
WS_HEARTBEAT_MS |
30000 |
Interval for connection pings |
MAX_PAYLOAD_BYTES |
1024 |
Maximum incoming message size |
DATABASE_URL |
— | Connection string for storage adapter |
AUTH_SECRET |
— | Secret for token verification |
# Development (with auto-reload)
npm run dev
# Production
npm startThe server will listen on the configured port and accept WebSocket connections at /.
wss://<host>:<port>/?token=<jwt>
Clients must provide a valid JWT as a query parameter. Connections without a valid token are rejected with a 4001 close code.
GET /health
Returns 200 OK with JSON {"status":"OK"} when the gateway is active. This endpoint is unauthenticated and intended for container health checks and orchestrator liveness probes.
All messages are JSON-encoded. Every message must contain a type field:
{
"type": "location_update",
"payload": {
"latitude": 40.7128,
"longitude": -74.0060,
"altitude": 10.5,
"accuracy": 3.0,
"speed": 0.5,
"timestamp": "2026-06-10T12:00:00Z"
}
}| Type | Description |
|---|---|
join_room |
Subscribe to a room (e.g., fleet-alpha) |
leave_room |
Unsubscribe from a room |
location_update |
Publish current coordinates |
| Type | Description |
|---|---|
location_update |
Broadcast from another room member |
room_joined |
Confirmation of room join |
room_left |
Confirmation of room leave |
error |
Validation error or server error |
# Run all unit tests
npm test
# Run with coverage
npm run test:coverageTests are written with Vitest (or Jest — check package.json). Key test areas:
- Validation – Malformed, missing, and out-of-range coordinate payloads are rejected.
- Room lifecycle – Joining, leaving, and broadcasting respect membership boundaries.
- Cleanup on disconnect – Client teardown releases room subscriptions and in-memory references.
This project is organized into waves that incrementally build toward a production-ready gateway. Each wave corresponds to a vertical slice of functionality.
Architect the WebSocket connection lifecycle to efficiently manage room-based broadcasting for multiple active geolocation streams.
- Define the
RoomManagerservice with thread-safe join/leave/disconnect semantics. - Implement heartbeat ping/pong to detect zombie connections.
- Ensure O(1) broadcast to all members of a room.
- Deliverable: all members of a room receive location updates from any publisher within that room.
Implement strict payload validation to immediately drop malformed coordinate data before it reaches the database.
- Define a validation schema (latitude [-90, 90], longitude [-180, 180], valid ISO 8601 timestamp, etc.).
- Reject messages that violate the schema with a descriptive
errorframe. - Log every validation failure with the reason and client identifier.
- Deliverable: no invalid coordinate is ever persisted or broadcast.
Write unit tests ensuring that client disconnection events properly clean up server memory and log the exit.
- Assert that a client's room subscriptions are removed on disconnect.
- Assert that the
RoomManagerno longer holds a reference to the disconnected client. - Assert that a structured log entry is emitted with the client ID and disconnect reason.
- Fork the repository.
- Create a feature branch from
main. - Commit changes with clear, descriptive messages.
- Run the full test suite before opening a pull request.
- Open a PR and link any related issues.
All contributions must follow the existing code style and include tests where applicable.