Experience
Projects
My Stack
Case studies
Contact me
Open my CV

·11 min read

Chiti: Replacing 11 Sockets With One Typed Real-Time Layer

Chiti is a delivery, taxi and classifieds super-app that ships as one Expo binary for six user roles: guest, customer, merchant, courier, taxi driver and ads-only user. I am the tech lead on the team that rebuilt it. This post is about one part, the real-time layer, because it was where the legacy app hurt the most and where a good share of my own commits went after the first version worked.

The code is private, so this covers the architecture and the incidents, not a code dump.

Role
Tech lead
Period
Aug 2026 to Nov 2026
Status
Public site live, app releases up to 2.5.0
Stack
React Native, Expo, TypeScript, Socket.IO, TanStack Query

The challenge

The legacy client opened eleven independent Socket.IO connections, from six screens and two components inside list items. None authenticated at the handshake. Some were created inside effects that depended on a text input's state, so a socket was rebuilt on every keystroke, and two were never closed at all. The merchant order queue had no socket and polled on a ten second timer.

Every screen parsed raw payloads on its own. Coordinates arrived as numbers over the socket and as strings from REST, so parseFloat sat beside every map marker and two screens could disagree about the same order.

The real difficulty came after the clean design: a courier's phone is a hostile environment. It backgrounds, loses signal, wakes with an expired token, and the backend is a legacy server that replays nothing and fails quietly.

Legacy app

0connections

Rewrite

0connections
Figure 1. The legacy client opened eleven Socket.IO connections, the rewrite opens one per session.

My responsibility

I led the team and the architecture. What the repository history shows under my own commits, from September 2026 on:

  • the production behavior of the socket: handshake budget, acknowledged position reports, reconnect after a token refresh, and a small script to watch courier frames against the real server
  • courier shift, offer feed and live tracking, then the taxi driver's ride feed
  • shared map, address and route work across customer, courier and taxi screens
  • partner onboarding, earnings and withdrawals, and the QA fixes that followed

The first commits of the repository, including the original socket module and its architecture decision record, were made under team accounts on 20 August 2026. I will not claim those commits as mine. What I can show is the evidence from my own commits below.

How I approached it

One connection, one cache writer

One connection per session, owned by one module. A socket event either patches the query cache or is published on a typed bus, and screens read from the cache. The stack is Expo SDK 57, strict TypeScript, TanStack Query for server state and Socket.IO behind a typed facade.

Legacy appRewrite
ConnectionsEleven, opened by screens and list itemsOne per session, owned by one module
Handshake authNoneA function that sends the current token on every attempt
Payload parsingPer screen, parseFloat near each markerOne Zod schema per frame
wire eventscanonical eventsinvalidate or patchpublishesreadssubscribesLegacy serversnake_case eventsSocket modulevalidates, translatesCache bridgethe only cache writerQuery cacheTanStack QueryTyped event busoffers, chatScreenshooks, no sockets
Figure 2. A socket frame is validated and translated once, then either patches the query cache or goes on the typed bus, and screens only read from those two places.

Two contracts, one translation point

The backend is a legacy Express server with snake_case event names and thin payloads. I did not want that dialect inside the app, and I did not want the rewrite to wait on a server rename. So there are two typed contracts: a wire contract that describes events exactly as the server emits them, and a canonical one with names the app uses, such as order:status and courier:position.

A single WIRE_TO_CANONICAL map is the only translation point. It is declared with satisfies Record<keyof WireServerEvents, keyof ServerEvents>, so a wire event with no decided meaning is a compile error. Branded ids stop the two different things the wire calls orderId from being swapped, and references are never coerced to numbers.

A socket frame is untrusted input

Every listener payload is typed unknown and crosses a Zod schema before anything reads a field. One schema accepts coordinates as number or string and rejects out-of-range values instead of putting a marker in the ocean.

One rule I like: a status ping carries optional extras. If an extra is garbled I do not want a throw, because a thrown ping never reaches the cache invalidation that is the point of the event. So optional fields degrade to null, scoped to that field. Required fields still fail loudly.

ts
// optional and wrong both degrade to null, required fields still throw
const optionalOrNull = <S extends z.ZodType>(schema: S) =>
  schema.nullish().transform((v) => v ?? null).catch(null);

The cache bridge

One file is the only place a socket event touches the cache.

  • Status pings invalidate. The backend derives status from a whole row, so a ping cannot carry it reliably. Invalidate and refetch the truth.
  • Positions patch. A courier or driver location frame is written with setQueryData into the tracking key being watched. No refetch, no polling.
  • Everything else goes on the bus. Offer lists and chat are canonical events that screens subscribe to with a hook.

Handlers are wrapped so one broken listener cannot stop dispatch, and a reconnect invalidates orders, rides, chat and pending ratings. The cost is real: a new event means editing the contract, the bridge and a test. I recorded that trade in an architecture decision.

Connection lifecycle

  1. 01

    Session starts

    the provider opens the socket

  2. 02

    Handshake

    auth function sends the current token

  3. 03

    Rooms

    tracked rooms are rejoined on every connect

  4. 04

    Connection drops

    backoff from 1 to 30 seconds, plus jitter

  5. 05

    Reconnect

    orders, rides, chat and ratings are invalidated

Figure 3. The life of the connection, from login to a reconnect after a drop.

The handshake auth is a function, so each attempt sends the current token. Reconnection is unlimited with backoff and jitter, and tracked rooms are rejoined on every connect. Imports only point inward across the layers (app, features, entities, shared, design-system, core), enforced by ESLint boundary rules, not review.

appimports point inward
featuresimports point inward
entitiesimports point inward
sharedimports point inward
design-systemimports point inward
coremay not import the order entity
Figure 4. Imports only point inward, and ESLint boundary rules enforce it instead of review.

The handshake that took 11.3 seconds

On 12 Sep 2026 I changed one number. The socket's connect timeout was ten seconds, which looks generous. Measured against the real server, a handshake took 11.3 seconds, and a second attempt from the same machine connected at once. So on slow mobile links the first attempt failed with a timeout on exactly the connections that needed patience, and every failed attempt cost a full reconnect cycle in which the device received no frames. The server replays nothing, so whatever moved in that window was gone.

I raised the budget to 25 seconds, above both the observed handshake and the server's own 20 second ping timeout. The reasoning went into the code comment: a dead link should be declared dead by the ping cycle, which can tell a stalled link from a slow one, not by a timer racing it. The commit is 05f3837 (Sep 2026).

A position the server accepted and never stored

The same evening I moved position reporting onto the socket (d4e80a9, Sep 2026): every fix gated by distance moved, HTTP kept only as the fallback for a headless relaunch. The risk I saw in the server is that it persists a position only for a socket whose handshake proved an identity. A connection opened with a stale token would broadcast the courier's marker while quietly never storing it, and a courier whose stored position never moves is a courier the dispatcher stops offering work to. Nothing on the phone shows that.

So a position is sent with an acknowledgement, and the client tracks whether the server says it stored it:

ts
// ack timeout, then remember whether the server stores our fixes
socket.timeout(10_000).emit("update_location", frame, (err, res) => {
  stores = !err && res?.stored === true;
});

When storing stops, the client falls back to HTTP. It also never lets a position sit in Socket.IO's offline buffer, because positions are last write wins and would land out of order after a long outage.

The socket that stayed anonymous

In Nov 2026 two commits closed the loop. The auth callback only runs on a connect, so a socket opened with a token that expired while the app was in the background stays anonymous for the rest of the trip. 6331d17 (Nov 2026) reconnects once when an ack says stored: false, rate limited so a truly signed-out session cannot spin. 844fa5f (Nov 2026) fixed the cause: the token store now notifies listeners on every write, and the socket cycles after a short debounce so a burst of writes reconnects once. I also added a transport notice, auth_required, so a refused room join triggers the same remedy. The same background commit cleans up stale location tasks left by the legacy build, which kept delivering fixes to a task that no longer existed.

The courier who stood still

On 12 Sep 2026 a chain of small commits chased one symptom: a courier waiting for work stopped seeing fresh offers. The offer feed is ranked by the courier's last stored position, and three separate causes stacked up. Shift tracking was gated at 250 metres of movement, so a waiting courier never reported (afd49c8). The balanced accuracy setting resolved to network location, which a device without one never answers, so I asked the GPS provider while on shift (c25f92c). And the shift screen said "sharing location" when the foreground watcher had refused to start and the failure was only logged (80a3e6a). A related fix tied the offer feed to the shift and the position, because a disabled query still served its persisted cache and the first fetch outran the position write (11ddfb6).

Each is a small diff. What mattered was following the symptom through app state, OS settings and server ranking until the feed moved with the courier.

Project journey

  1. Aug 2026

    Rewrite scaffolded

    one socket module, ADR for cache patching, legacy events typed as wire

  2. Sep 2026

    Staging and first field fixes

    courier shift, offers, tracking and maps on real devices

  3. Sep 2026

    Handshake and positions

    25 second budget, acknowledged position reports over the socket

  4. Oct 2026

    Releases 2.4.0 and 2.5.0

    partner onboarding, two native modules, required-update gate

  5. Nov 2026

    Token and background fixes

    reconnect after refresh, stored:false recovery, offers one at a time

Figure 5. Real-time layer and its production hardening, from first commit to the latest.

Beyond the launch

After the first working version, the history is mostly fixes found on devices, and several are not mine. A teammate made a dead socket visible in the UI on 7 Sep 2026 (ffd7320), after finding that the staging proxy had no route for the socket path and every handshake had failed since the host came up with no symptom in the app. Releases 2.4.0 and 2.5.0 followed in October (6f05b4f, 31fb4b6), and I continued with offers one at a time, server-side decline and no-courier states.

Open limits: the backend still does not replay missed frames, so reconnect leans on invalidation. And testing is thinner than it was. The handoff notes recorded 1,775 tests in 175 suites on 20 Aug 2026, but a later commit removed that suite and the CI workflows on 3 Sep 2026 (cdc6b68). About 40 test files remain in the source tree. I did not rerun them for this write-up.

The outcome

The public site chiti.com.ge is online and the app code has one connection per session instead of eleven. The courier and taxi flows depend on the position path described above, and the repository's latest commit is from 10 Nov 2026. I do not have user counts or order volumes I can verify, so I am not quoting any.

Evidence

Not verified: the eleven socket count is from the repository's own notes, and I did not rerun or recount the old test totals. I did not measure the 11.3 second handshake again, it is the figure recorded in the commit.

#react-native#socket-io#typescript#tanstack-query

Keep reading

Have a project in mind?