Scaling Stateful TCP Connections in Node.js: Designing a Horizontally Scalable Connected-Vehicle Gateway

How I approached a connected-mobility backend assignment by prioritizing multi-instance coordination over protocol completeness—decoupling persistent TCP device sockets from stateless HTTP APIs using Redis Pub/Sub and RSMQ.

Share
Scaling Stateful TCP Connections in Node.js: Designing a Horizontally Scalable Connected-Vehicle Gateway

How I approached a connected-mobility backend assignment by prioritizing multi-instance coordination over protocol completeness—decoupling persistent TCP device sockets from stateless HTTP APIs using Redis Pub/Sub and RSMQ.

Executive Summary

Connecting a fleet of IoT vehicles over persistent TCP while exposing a stateless REST API and asynchronous webhooks introduces a classic distributed-systems tension: an HTTP request can land on any server instance, while the target vehicle's TCP socket lives in memory on only one. This case study walks through vehicle-gateway, a plain JavaScript Node.js backend built in 2020—before I had adopted TypeScript in my daily stack—as a take-home technical assignment for 2hire (a connected-mobility platform) to interface with a fleet of electric scooters (ExplodingScooters). Rather than racing to cover every edge case in a monolithic prototype, I agreed with the technical team to prioritize horizontal scalability, process separation, and cross-instance coordination behind round-robin load balancers—laying a modular foundation using Node's net module, Express, Redis Pub/Sub (ioredis), and a Redis-backed message queue (rsmq).

The Challenge & Architectural Priorities

The assignment modeled a realistic connected-mobility gateway for a fleet of electric scooters communicating over persistent, line-based ASCII TCP connections (\n-delimited, case-sensitive). The protocol covers the full device lifecycle:

  • Handshake: HELLO, I'M {{device_id}}! → HI, NICE TO MEET YOU!
  • Heartbeat: PING. → PONG.
  • On-demand polling: HOW'S IT GOING? → FINE. I'M HERE {{lat}} {{lon}}, {{RESTING|RUNNING}} AND CHARGED AT {{charge}}%.
  • Periodic telemetry: KEEP ME POSTED EVERY {{seconds}} SECONDS. → SURE, I WILL! followed by recurring REPORT. I'M HERE ... updates
  • Commands: HEY YOU, RUN! / HEY YOU, REST! → DONE! or I CAN'T, SORRY.
  • Disconnection: GOTTA GO. → SEE YA!
  • Binary error dumps (edge case): WTF! {{#bytes}}\n{{binary_blob}}\n → DAAAMN! ISSUE REPORTED ON JIRA

On the north-bound side, the gateway needed to expose a REST API to inspect vehicle state (connectivity, coordinates, battery, running status), adjust periodic reporting intervals, send RUN/REST commands, and force disconnections—plus forward asynchronous webhook notifications whenever status, location, battery, connectivity, or debug blobs changed.

Why Coordination Came Before Parsing

In a single-process Node.js prototype, bridging HTTP and TCP is trivial: keep a Map<deviceId, Socket> in memory and write directly to the socket from an Express route handler.

That design collapses the moment you scale horizontally behind round-robin load balancers on both the TCP and HTTP tiers:

  1. Scooter A connects through the TCP load balancer and lands on TCP Instance #2.
  2. An operator sends POST /api/device/A/run through the HTTP load balancer and lands on REST Instance #1.
  3. REST Instance #1 has no direct handle to Scooter A's socket—and shouldn't need to know which TCP node owns it.

In explicit alignment with the technical team, I treated horizontal scalability and modularity as the primary goal of the exercise, deliberately investing the available time into a clean multi-instance architecture over 100% completion of every protocol corner case.

System Architecture

The repository splits the gateway into two independently runnable processes—defined as separate entrypoints in package.json (src/tcpserver.js and src/restserver.js)—sharing Redis as both a real-time coordination bus and an asynchronous event queue.

  [Scooter Fleet]                           [API Consumers / Clients]
         │                                              │
   (Persistent TCP)                                (HTTP / REST)
         ▼                                              ▼
  ┌─────────────────┐                            ┌─────────────────┐
  │  TCP LB (RR)    │                            │  HTTP LB (RR)   │
  └────────┬────────┘                            └────────┬────────┘
           │                                              │
           ▼                                              ▼
  ┌─────────────────────────┐                    ┌─────────────────────────┐
  │  tcpserver (N replicas) │                    │ restserver (M replicas) │
  │  • net.createServer     │                    │ • Express /api/device   │
  │  • per-socket session   │                    │ • asyncCatcher + errors │
  │  • expProtocol parser   │                    │ • webHookWorker (RSMQ)  │
  └──────┬───────────┬──────┘                    └───────┬──────────┬──────┘
         │           │                                   │          │
    Presence &    Periodic                          Presence &    Dequeue &
    Pub/Sub       Reports                           Pub/Sub       HTTP POST
         │           │                                   │          │
         ▼           ▼                                   ▼          ▼
  ┌────────────────────────────────────────────────────────┐   ┌──────────┐
  │                         Redis                          │   │ Webhook  │
  │  • KV: vehicle:lastConnected:<deviceId>                │   │ Endpoint │
  │  • Pub/Sub: vehicle:channel:<deviceId>:user2vehicle    │   └──────────┘
  │  • Pub/Sub: vehicle:channel:<deviceId>:vehicle2user    │
  │  • RSMQ Queue: <prefix>:rsmq / webhook                 │
  └────────────────────────────────────────────────────────┘

1. Independent TCP and REST Processes

  • TCP Gateway (src/tcpserver.js → src/services/tcpserver/): Built directly on Node's net.createServer. Each incoming connection gets a lightweight session object attached to the socket (socket._vehicleSession = {}), a socket timeout (800000 ms), and basic write backpressure handling—if socket.write(response) returns false, the socket pauses reading until the drain event fires. When the socket closes, handleCloseConnection cleans up its Redis channel subscription and clears the session.
  • REST API Server (src/restserver.js → src/services/restserver/): An Express application wrapped in http.createServer. Routes are mounted under /api/device via deviceRouter.js, paired with two small helpers in src/helpers/: logRequest.js for debug request logging and asyncCatcher.js to ensure rejected promises from async route handlers forward cleanly to Express's centralized JSON error handler (http-errors for 404s, structured { status: "fail", error: { status, msg } } responses).

The REST surface in src/services/restserver/deviceRouter.js maps directly to vehicle operations:

EndpointVehicle CommandExpected Reply

GET /api/device/:deviceId

HOW'S IT GOING?

status (FINE. I'M HERE ...)

PUT /api/device/:deviceId/update

KEEP ME POSTED EVERY {N} SECONDS. (0 disables)

postedOk (SURE, I WILL!)

POST /api/device/:deviceId/run

HEY YOU, RUN!

runRestOk / runRestKo

POST /api/device/:deviceId/rest

HEY YOU, REST!

runRestOk / runRestKo

DELETE /api/device/:deviceId

GOTTA GO.

leaveAck (SEE YA!)

2. Cross-Instance Coordination via Redis (redis.js & vehicle/index.js)

Because a Redis connection subscribed to Pub/Sub channels cannot execute regular commands (GET, SET, PUBLISH), src/services/redis.js exposes two factories backed by ioredis (with a configurable REDIS_KEYPREFIX):

  • getRedis() for standard key-value and PUBLISH operations.
  • getSubscriptionRedis(type = 'main') for dedicated subscriber connections.

All vehicle orchestration lives in src/services/vehicle/index.js, decoupled from both Express and net.Socket:

  1. Shared Presence: On HELLO, the TCP server stores vehicle:lastConnected:<deviceId> in Redis with a timestamp (setVehicleConnected), refreshes it on every PING., and deletes it on GOTTA GO.. Before dispatching any command, deviceRouter.js checks isVehicleConnected(deviceId) and short-circuits with { offline: true, online: false, deviceId, timestamp } if the scooter isn't online.
  2. Bidirectional Pub/Sub Channels: Once a scooter identifies itself, the TCP server holding that socket subscribes to vehicle:channel:<deviceId>:user2vehicle. When any REST replica receives an HTTP request, sendCommandToDevice() subscribes to the paired reply channel vehicle:channel:<deviceId>:vehicle2user, publishes the formatted command to user2vehicle, and waits for a matching response (with a 20-second timeout) before unsubscribing.

This eliminates sticky-session requirements between the REST and TCP tiers: any REST node can talk to any scooter connected to any TCP node.

3. Decoupled Telemetry & Webhook Worker (messageQueue.js & webHookWorker.js)

Periodic REPORT. messages are fundamentally different from request/response commands: there is no live HTTP caller waiting for them, and fire-and-forget Pub/Sub would drop updates if no consumer were listening.

To decouple ingestion from outbound webhook delivery:

  • src/services/messageQueue.js wraps RSMQ (Redis Simple Message Queue), lazily creating the configured queue (RSMQ_QUEUE) while gracefully handling queueExists across multiple booting instances. It encodes messages as deviceId|type|JSON.stringify(params) and exposes sendMessage, receiveMessage, and deleteMessage.
  • When a TCP instance parses a report message, onSend2QueueResponse pushes it straight into RSMQ.
  • src/services/restserver/webHookWorker.js runs a polling loop (startWorker(5), started from restserver/app.js every 5 seconds via recursive setTimeout). When a message is dequeued, it sends an HTTP request to WEBHOOK_URL using axios (10-second timeout), profiles execution duration via Winston (src/services/logger.js), and removes the message from the queue.

In keeping with the timeboxed scope, webHookWorker.js explicitly documents via FIXME comments what remains unfinished here: persisting the last known position, battery, and running state so webhooks fire only on actual state transitions (as well as wiring online/offline and debug-blob events into the queue).

Handling a Mixed Text/Binary TCP Protocol

The ExplodingScooters protocol is isolated in src/services/vehicle/expProtocol.js. The top-of-file comment states the design intent clearly: other vehicle protocols should be pluggable behind the same interface consumed by src/services/vehicle/index.js.

Modular Handler Hierarchy

Each inbound message type is modeled as a subclass of BaseMessageHandler:

class BaseMessageHandler {
  constructor() {
    this.params = {};
    this.msgRxp = /invalid/;
    this.binary = false;
  }

  parseNew(message) {
    this.params = {};
    if (!message) {
      return false;
    }
    const result = message.match(this.msgRxp);
    if (!result) {
      return false;
    }
    this.params = this._parseParams(result);
    return true;
  }
  // ...
}

Ten concrete handlers inherit from BaseMessageHandler (HelloMessageHandler, PingMessageHandler, StatusMessageHandler, ReportMessageHandler extending StatusMessageHandler to reuse coordinate/status/battery extraction, PostedOkMessageHandler, RunRestOkMessageHandler, RunRestKoMessageHandler, LeaveMessageHandler, LeaveAckMessageHandler, and BugMessageHandler). Outbound commands are centralized in composeCommand(type, params), which also enforces protocol bounds—for example, clamping KEEP ME POSTED EVERY {seconds} SECONDS. between 10 and 3600 seconds (while supporting 0 via NOPOSTED).

The WTF! Mixed Text/Binary Framing Challenge

The most interesting protocol edge case is the firmware crash report:

WTF! {{#bytes}}\n
{{binary_blob}}\n

Followed by the server acknowledgment DAAAMN! ISSUE REPORTED ON JIRA.

Unlike the rest of the protocol, you cannot parse this safely with naive UTF-8 line splitting (data.split('\n')) for two reasons:

  1. Arbitrary binary payloads frequently contain 0x0A (\n) bytes, which would prematurely split the frame.
  2. Decoding raw binary bytes as utf8 replaces invalid byte sequences with U+FFFD, corrupting the payload and distorting byte length calculations.

In expProtocol.js, the protocol contract for this message is already modeled via BugMessageHandler:

class BugMessageHandler extends BaseMessageHandler {
  constructor() {
    super();
    this.msgRxp = /^WTF! ([0-9]+)$/m;
    this.type = 'bugReport';
    this.binary = true;
  }
  _parseParams(regexpResult) {
    return {
      bytes: regexpResult[1]
    };
  }
}

RESPONSES.bugReport also maps to 'DAAAMN! ISSUE REPORTED ON JIRA', and COMMAND_RESPONSE_TYPES.GOT_BUG is defined.

Where the implementation stops today (being transparent): this.binary = true was introduced specifically as the hook for a stream state machine to switch from line-delimited header mode into fixed-length binary accumulation, but that binary framing loop is not yet wired end-to-end. Right now, src/services/tcpserver/app.js still calls socket.setEncoding('utf8') and passes each data event directly into handleVehicleMessage(), and RESPONSE_HANDLERS in src/services/vehicle/index.js does not yet register a handler for bugReport. Completing this requires dropping setEncoding('utf8') in favor of a per-socket Buffer accumulator that scans for 0x0A in text mode and, once handler.binary === true, slices out exactly parseInt(params.bytes, 10) raw bytes (plus trailing delimiter) before switching back to text mode.

Protocol Unit Tests

Unit tests live in test/expProtocol.spec.js, run with Mocha and Node's built-in assert module. They currently cover 9 test cases across HELLO, PING, and STATUS messages—validating parameter extraction (deviceId, latitude, longitude, boolean running, charge), rejecting malformed verbs/punctuation, and rejecting concatenated messages missing a newline boundary (such as PING.PING. or FINE. ...%.PING). Expanding this suite to cover REPORT, WTF!, composeCommand, and chunked TCP stream framing is a clear next step.

Testing & Developer Workflow

I managed the assignment like a real production backlog: breaking the problem into small SCRUM-style user stories on Trello and shipping each increment via a dedicated Pull Request on GitHub rather than a single monolithic commit:

  1. PR #1 (tcp-server-base): Base TCP server, Redis client factory, and Winston logging (error.log, combined.log, colorized dev console).
  2. PR #2 (rest-server-base): Express REST server skeleton and error handling.
  3. PR #4 (github-workflows): GitHub Actions CI pipeline.
  4. PR #3 (tcp-msg-parser): expProtocol.js, Mocha unit tests, TCP integration, and .env-example.
  5. PR #5 (tcp-server-pubsub): Bidirectional Redis Pub/Sub wiring between TCP and REST instances.
  6. PR #6 (device-api): Complete deviceRouter.js endpoints, RSMQ messageQueue.js, initial webHookWorker.js, and the automated device simulator.

Integration Simulators & Local Ergonomics

To test the multi-process flow end-to-end without physical hardware, test-integration/ includes two Node.js TCP device simulators and a set of curl helpers:

  • test-integration/clientDeviceManual.js: An interactive step-by-step client that generates a random UUID v4 deviceId and waits for keypresses to send HELLO, FINE. I'M HERE ..., PING., and GOTTA GO.. Useful when bringing up the TCP server and verifying raw socket lifecycle behavior.
  • test-integration/clientDeviceAuto.js: A stateful automated scooter simulator. On connect, it automatically sends HELLO, starts a 60-second PING. heartbeat, parses incoming server commands (HOW'S IT GOING?, HEY YOU, RUN|REST!, KEEP ME POSTED EVERY N SECONDS., GOTTA GO.), updates its internal RESTING/RUNNING state, dynamically schedules/clears periodic REPORT. timers, and terminates cleanly on keypress or server-initiated leave.
  • test-integration/curl-info.sh, curl-run.sh, curl-updates.sh: Quick shell scripts targeting GET /api/device/$DEVICEID, POST /api/device/$DEVICEID/run, and PUT /api/device/$DEVICEID/update (frequency=10) with pretty-printed JSON output.

For local development, .vscode/tasks.json and .vscode/launch.json define compound tasks and debugger configurations to spin up both tcpserver and restserver side by side (a terminal demo of the full loop is recorded in the repository's README.md).

Continuous Integration

.github/workflows/nodejs.yml runs on every push using ubuntu-latest across a Node.js version matrix (10.x and 12.x, reflecting the LTS versions active when the assignment was written), executing npm install followed by npm test with CI=true.

What I Would Improve Next

Looking at the codebase with production eyes, several concrete gaps stand out—some already flagged with TODO/FIXME comments in the source:

  • TypeScript migration & strict contracts: Migrate the plain JavaScript codebase to strict TypeScript (which wasn't part of my toolkit when I wrote this in 2020) to enforce compile-time types across protocol handlers, Redis Pub/Sub payloads, and RSMQ message envelopes.
  • Byte-level TCP stream framing & binary WTF! support: Remove socket.setEncoding('utf8') in tcpserver/app.js and introduce a per-connection Buffer state machine to handle TCP packet fragmentation, coalesced multi-line chunks, and exact-byte extraction for WTF! debug blobs (plus wiring bugReport and leaveAck into RESPONSE_HANDLERS, and supporting negative GPS coordinates in the status/report regexes).
  • Fix Pub/Sub listener accumulation & concurrency races: Currently, both tcpserver/app.js and deviceRouter.js attach a new redisSubscription.on('message', ...) listener to a shared ioredis subscriber client per socket or per HTTP request without detaching it—which will leak memory and trigger MaxListenersExceededWarning under load. On the TCP side, a single subscriber dispatcher routing via a local Map<deviceId, Socket> fixes this cleanly; on the REST side, correlating commands with a unique request ID (or using Redis Streams / per-request correlation map) avoids races when two HTTP calls target the same scooter concurrently (and fixes a latent bug in the responseTypeKo branch of deviceRouter.js).
  • Presence TTL & abrupt disconnect cleanup: setVehicleConnected currently sets a Redis key with no expiration (TODO in vehicle/index.js), and handleCloseConnection unsubscribes the channel without deleting the presence key. Setting a Redis TTL refreshed by PING. heartbeats—and clearing presence on socket close—prevents ghost "online" vehicles after network drops or node crashes.
  • Production-grade webhook pipeline: Move webHookWorker.js out of the REST process into an independently scalable worker service, replace the hardcoded Redis host/port in messageQueue.js with parsed REDIS_URL config, switch pipe-delimited (|) message envelopes to pure JSON, persist last-known vehicle telemetry in Redis hashes to emit webhooks only on actual changes, and only call deleteMessage after a 2xx response (leveraging RSMQ visibility timeouts, exponential backoff, and a dead-letter queue for failures).
  • HTTP semantics, validation & security: Validate request payloads (e.g., numeric frequency), return proper HTTP status codes (404/503 for offline devices, 504 for command timeouts instead of 200 OK), authenticate REST endpoints and scooter handshakes, and enforce TLS on both TCP and HTTP edges.
  • Observability, graceful shutdown & load testing: Add /healthz and /readyz probes, SIGTERM/SIGINT handlers to drain sockets and close Redis connections cleanly, Prometheus metrics (active TCP sockets, Pub/Sub round-trip latency, RSMQ queue depth, webhook error rates), correlation IDs across logs, upgraded Node.js LTS/dependency versions, and load tests simulating thousands of concurrent persistent sockets across multiple replicas behind HAProxy or NGINX.

Get in Touch

You can explore the complete source code, pull request history, and terminal demo in the GitHub repository:

If you're hiring or looking to collaborate on Senior Full-Stack, Mobile, or Backend engineering roles—especially around distributed systems, Node.js/TypeScript architectures, or connected products—feel free to connect with me on LinkedIn: