Late, Twice or Never: Building Real-Time Trips on Unreliable Networks

A Twende trip is a live conversation between two moving phones and a server, over networks that drop without warning. Here's how we built the real-time layer behind every ride, and why we design every event as if it might arrive late, twice or never.

9 min read

A passenger requests a ride. A driver two streets away accepts it. For the next twenty minutes, two phones and a server hold a continuous conversation: where the driver is, when they've arrived, whether the trip has started, whether it's finished, who cancelled and why.

On a whiteboard, that conversation is clean. Arrows go from one box to another, and every message arrives exactly once, in order, on time.

On the road, the driver goes under a bridge. The passenger's phone switches from 4G to 3G and back. Someone's battery saver kills the app in the background. A message sent at 14:02:07 arrives after one sent at 14:02:09. Another arrives twice. Another never arrives at all.

This essay, part of our engineering series, is about the layer that holds every Twende trip together: the real-time connection between passengers, drivers and our servers. The principle we built it on is the one we'd tattoo on every mobility engineer if we could: in ride-hailing, the network is the unreliable part. Design every event as if it might arrive late, twice or never.

One trip, three parties

Before talking about sockets, it helps to see what we're actually keeping in sync.

Every Twende trip moves through a small, strict set of states:

DRIVER_ASSIGNED → ARRIVED → IN_TRIP → COMPLETED

with CANCELLED possible along the way.

Three parties care about that state: the passenger, the driver and the server. The single most important decision in our real-time design is about who's in charge of it. The answer is: the server is the source of truth. The apps ask for changes, and the server announces them.

When a driver taps "I've arrived", the driver app doesn't simply mark the trip as arrived. It sends a request (trip:update-status), and only when the server broadcasts the result (trip:status-updated) do both apps update their screens. It's one extra hop, and it's worth every millisecond: two phones with flaky connections can never disagree about what's happening for long, because neither of them gets to decide alone.

One socket per app, many listeners

Each Twende app keeps exactly one real-time connection to our servers, using Socket.IO over WebSockets on a dedicated namespace for trips. No screen opens its own connection. No component talks to the socket directly.

Instead, a single provider at the top of the app owns the connection, and screens subscribe to the events they care about through a hook:

// Any screen can listen without ever touching the socket.
useRideSocketEffect({
  onRideRequestAccepted: (trip) => showDriverFound(trip),
  onTripStatusUpdated: (trip) => syncTripState(trip),
  onDriverLocationUpdate: ({ lat, lng, heading }) => moveDriverMarker(lat, lng, heading),
  onDriverDisconnected: () => warnPassenger(),
});

Behind that hook is a small registry: each event has a map of listeners, keyed by a unique ID for each mounted component. When the socket receives an event, the provider fans it out to everyone registered for it. When a screen unmounts, its listeners are removed.

This sounds like plumbing, and it is, but it solved a whole class of bugs for us. With one connection, there's one place to handle authentication, one place to handle reconnection, and one place to log what's happening. Screens come and go as people navigate the app. The connection, and the trip it's carrying, doesn't care.

Reconnecting is the normal case

Here's the mindset shift that took us longest: a dropped connection isn't an error. It's Tuesday.

In the cities we build for, phones lose signal in traffic, between buildings and on the edges of town. So the connection is configured to expect that, and to recover on its own:

io(`${BACKEND_BASE_URL}/taxi`, {
  transports: ["websocket"],
  // Function form: a fresh token on every reconnect attempt.
  auth: (cb) => cb({ token: getCachedAuthToken() }),
  reconnectionAttempts: 10,
  reconnectionDelay: 1000,
  reconnectionDelayMax: 30000,
});

Two details in there are worth explaining, because each one came from a real bug.

The token is read on every reconnect, not once. Our sessions use tokens that expire. If a connection drops and the app keeps retrying with the token it had at the start, it can end up stuck in a loop: retrying forever with a token the server will never accept again. Passing a function instead of a value means every reconnection attempt picks up the current token.

The delay between retries grows. The first retry happens after a second, and later ones back off to as much as thirty seconds apart. When a whole neighbourhood loses signal at once and then gets it back, thousands of phones reconnecting at the same instant would hit the server like a wave. Backing off spreads that wave out.

The socket is disposable. The trip is not.

The most important part of reconnecting isn't the connection itself. It's what happens right after.

When an app reconnects, it's a brand new connection, and the server knows nothing about which trip it was following. So the first thing each app does on connect is look at its own stored state and rejoin its trip:

socket.on("connect", () => {
  const trip = useTripStore.getState().currentTrip;
  if (trip?.id) socket.emit("joinTrip", { tripId: trip.id });
});

The trip lives in the app's state store, not in the socket. The socket is just the pipe. You can throw it away, open a new one, and carry on exactly where you left off. Never keep anything in a connection that you can't afford to lose with it.

Two rhythms of location

Location is the busiest traffic on the connection, and we send it in two very different rhythms depending on what a driver is doing.

While a driver is online and waiting for a ride, their app reports its position as the GPS updates. That stream feeds our real-time driver matching engine: it's what keeps the hexagon index up to date, so the right driver is found when a request comes in.

During an active trip, the driver app sends its position, with its heading, to the trip itself every two seconds. The server relays it to the passenger, whose map moves the driver's marker and rotates it in the direction of travel.

Why two rhythms? Because they answer different questions. The matching index needs to know roughly where every available driver is. A passenger watching their driver approach needs smooth, frequent updates about one specific car. Sending trip-level detail for every idle driver would waste battery and mobile data for no benefit, and in markets where people buy data in small amounts, that waste is paid for by our drivers.

Every offer needs an ending

The moments before a trip starts are the most crowded, because several drivers may be looking at the same request at once. The rule we follow is that every offer must end in a way the driver can see. A request that silently disappears from one phone while another driver accepts it is confusing at best, and at worst leaves a driver heading to a pickup that's no longer theirs.

So the vocabulary of our real-time layer has an explicit ending for every way an offer can finish:

  • ride-request:accepted: you got it.
  • ride-request:claimed: another driver accepted it first.
  • ride-request:expired: nobody accepted it in time.
  • ride-request:cancelled: the passenger changed their mind.

Each one clears the request from the driver's screen with a clear reason. Behind the scenes, the atomic claim we described in our matching essay makes sure only one driver can win. The events make sure everyone else finds out.

The handshake that makes a trip safe

One part of our real-time flow isn't about speed at all. It's about safety, and it's the part we're proudest of.

A trip doesn't start just because a driver says so. When the driver is ready to go, their app sends a start request. On the passenger's phone, a short two-step check appears:

  1. Verify the plate. Does the number plate on the vehicle in front of you match the one shown in the app?
  2. Confirm the start. Only then does the passenger approve, and only then does the server move the trip to IN_TRIP.

If the passenger reports that the plate doesn't match, the trip is cancelled immediately. A mismatched plate is one of the clearest warning signs that something is wrong, and we'd rather end a trip in a second than ask a passenger to get into the wrong vehicle.

This is what real-time infrastructure is for. It isn't only about watching a car move on a map. It's about putting the passenger in control at the moment it matters most. As we wrote in Safety First, safety is something we design into every step of the ride, and this handshake is that idea turned into a protocol.

When things go quiet

The hardest failures in a real-time system aren't the loud ones. They're the silent ones.

If a driver's connection drops in the middle of a trip, the passenger shouldn't just watch a frozen marker and wonder. The server tells them: a driver-disconnected event reaches the passenger's app, which explains what happened and offers clear options instead of leaving them guessing.

We learned how sneaky silence can be the hard way, on our own desks. During development, a test phone pointed at the wrong network address for our server. It connected to nothing, raised no error and simply never sent a ride request. On the other side, our driver simulation tools sat waiting for requests that were never coming. Nothing was broken, exactly. Nothing was happening either. It took longer than we'd like to admit to realise the problem was a single outdated IP address.

That's the lesson: in real-time systems, "nothing happened" is a symptom, not an all-clear. Make silence visible: log connections, surface disconnections, and give people a next step when the other side goes quiet.

Be strict in what you send, forgiving in what you accept

One last detail, because engineers will recognise it.

As our backend evolved, some events started wrapping the trip inside an object, while others sent it directly. Rather than breaking the apps every time the shape shifted, the passenger app quietly accepts both:

socket.on("trip:status-updated", (data) => {
  const trip = data?.trip ?? data;
  notifyListeners(trip);
});

It's a one-line idea borrowed from the early days of the internet: be strict in what you send, and forgiving in what you accept. When your apps live on phones you can't update instantly, tolerance at the edges buys you time to change the middle safely.

Our opinion, stated plainly

If you're building anything real-time that runs on phones in the real world, here's what we'd tell you:

  1. Late, twice or never. Design every event assuming it might arrive late, more than once, or not at all.
  2. One source of truth. Let the server decide the state. Apps request changes; the server announces them.
  3. The socket is disposable. Keep state outside the connection, so a reconnect is a non-event.
  4. Reconnect like you mean it. Fresh credentials on every attempt, and back off so recovery doesn't become an outage.
  5. Every offer needs an ending. Accepted, claimed, expired or cancelled. Never let something just vanish.
  6. Make silence visible. "Nothing happened" is a symptom. Surface it.
  7. Use real-time for trust, not just tracking. The most valuable message in our system isn't a location update. It's a passenger confirming the plate matches before the trip begins.

A ride is a promise kept over twenty minutes of unreliable networks. The map, the matching engine and the onboarding checks we've written about all matter. But it's the real-time layer that carries that promise from the moment a driver accepts to the moment the passenger arrives.

Ready to ride with Twende?

Join the waitlist and be among the first to experience safer, fairer transport in African cities.

Related posts