Live Order Tracking System Design: Pings, ETAs and SSE

Live Order Tracking System Design: Pings, ETAs and SSE

17 min read

"Your order is 8 minutes away." That line changes while you watch a little scooter crawl across the map, and it is one of my favourite system design questions for Indian candidates, because everyone has stared at that screen at 9 PM. This post is the live order tracking system design I would draw in an interview: how a rider's GPS ping becomes a moving dot and an honest ETA on your phone. It describes how I would design a system like this, not how any particular company does it.

TL;DR

  • Rider phones send GPS pings over HTTPS to a stateless ingest API, which writes them to Kafka, partitioned by rider id.

  • A consumer drops bad pings (poor accuracy, out of order, impossible speed) and keeps only the latest position per order in Redis, with a TTL.

  • The ETA is prep time left plus road time, recomputed on a timer or when the rider leaves the route, then smoothed before anyone sees it.

  • The customer app gets updates over SSE, with polling as the fallback. WebSocket only if you already need two-way traffic.

  • Keep the latest position hot, raw pings briefly, and a thinned trail for disputes. Stop tracking at delivery.

How does live order tracking work in a food delivery app?

Live order tracking is a pipeline. The rider's phone sends a GPS ping every few seconds, the backend filters out bad points and keeps only the latest position for each order, an ETA service turns that position into minutes using road distance and preparation time, and the customer's app receives each update over a push connection such as SSE.

The rest of this post is that paragraph, one box at a time.

Architecture of live order tracking, from the rider's phone through Kafka and Redis to the customer's app
The whole pipeline on one page. Writes go left to right; nothing on the hot path touches Postgres.

Requirements first, then numbers

What the system must do:

  1. The customer sees the rider on a map and an ETA, updated within a few seconds.

  2. The restaurant sees the rider approaching, so the food is packed on time.

  3. Support can replay a trip when there is a dispute ("the rider never came").

What it must survive: the dinner peak, riders in basements and underpasses with no signal, budget Android phones on low battery, and the fact that GPS lies.

Now the numbers. These are an example for the interview, not anyone's real traffic:

Quantity

Example value

Working

Orders out for delivery at peak

1,00,000

assumption

Ping interval while moving

4 seconds

assumption

Pings per second

25,000

1,00,000 / 4

Size of one ping

about 200 bytes

ids, lat, lng, accuracy, time

Inbound data

5 MB/s, about 18 GB an hour

25,000 x 200 bytes

Polling load if every app asks every 5 s

20,000 requests/s

1,00,000 / 5

Writes dominate, so the write path must be cheap. And each write is useful for a few seconds at most, so storing every ping in a relational database is the wrong default.

Step 1: getting pings off the phone

The rider app reads a location fix from the OS (on Android, the fused location provider). Each fix carries a latitude, a longitude, an accuracy radius in metres and a timestamp. I'd add a sequence number that goes up by one on the phone for every fix. That one field solves most ordering problems later.

How the phone sends it matters more than people expect:

  • HTTPS from the rider, not a WebSocket. Mobile networks drop constantly. A plain POST with retries is simple, stateless and easy to scale. When the network is down, the app buffers fixes and sends them as one batch later.

  • An adaptive interval. Every 3-5 seconds while moving on an active order, much slower while waiting at the restaurant, nothing when offline. Battery is a feature: a rider whose phone dies at 7 PM is a tracking outage.

  • An ingest API that does almost nothing. It checks that the rider is authenticated and on an active order, then writes to Kafka. No database calls on this path.

The topic is partitioned by rider id. Kafka keeps order within a partition, so one consumer reads all of a rider's pings in order, which is also what makes an in-memory "last good ping per rider" cache safe.

Step 2: filtering pings you should not believe

GPS is noisy. In a dense city you will see fixes with an accuracy radius of hundreds of metres, pings that jump a neighbourhood and back, and old pings arriving after new ones. Draw every ping and the customer watches the scooter teleport.

Three checks catch most of it:

  1. Accuracy. Drop fixes whose accuracy radius is worse than, say, 50 metres.

  2. Order. Drop anything whose sequence number is not newer than the last one you accepted.

  3. Physics. Divide the distance from the last good fix by the time between them. A two-wheeler in city traffic is not doing 200 km/h.

One subtlety: if the last accepted ping was itself the bad one, every correct ping after it looks like a jump. Add a reset rule: if three rejected pings in a row agree with each other, believe them.

Here is the difference in the Kafka consumer. Imports are left out of all the snippets to keep them short.

Open in PlaygroundOpen in Playground
NaivePingListener.javaJava
@Componentpublic class NaivePingListener {    private final ObjectMapper json;    private final StringRedisTemplate redis;    public NaivePingListener(ObjectMapper json, StringRedisTemplate redis) {        this.json = json;        this.redis = redis;    }    @KafkaListener(topics = "rider-pings", groupId = "order-tracking")    public void onPing(String payload) throws JsonProcessingException {        RiderPing ping = json.readValue(payload, RiderPing.class);        String orderId = redis.opsForValue().get("rider:" + ping.riderId() + ":order");        // Trusts every ping, lets an old ping overwrite a newer one, never expires.        redis.opsForHash().putAll("track:" + orderId, Map.of(                "lat", String.valueOf(ping.lat()),                "lng", String.valueOf(ping.lng())));        redis.convertAndSend("track-updates:" + orderId, payload);    }}
RiderPingListener.javaJava
@Componentpublic class RiderPingListener {    // Kafka gives each rider's partition to one consumer, so a local cache of the last good ping works.    private final Map<String, RiderPing> lastAccepted = new ConcurrentHashMap<>();    private final ObjectMapper json;    private final TrackingWriter writer;    public RiderPingListener(ObjectMapper json, TrackingWriter writer) {        this.json = json;        this.writer = writer;    }    @KafkaListener(topics = "rider-pings", groupId = "order-tracking")    public void onPing(String payload) throws JsonProcessingException {        RiderPing ping = json.readValue(payload, RiderPing.class);        if (PingFilter.check(lastAccepted.get(ping.riderId()), ping) != PingFilter.Verdict.ACCEPT) {            return;   // the raw ping is still in Kafka for the trip trail        }        lastAccepted.put(ping.riderId(), ping);        writer.write(ping);    }}

The filter is plain Java, so it is easy to unit test:

RiderPing.javaJava
public record RiderPing(        String riderId,        long seq,                 // +1 on the phone for every GPS fix        double lat,        double lng,        float accuracyMeters,     // radius the OS reports for this fix        long deviceTimeMillis) {}
PingFilter.javaJava
public final class PingFilter {    static final float MAX_ACCURACY_METERS = 50f;    static final double MAX_SPEED_MPS = 120 / 3.6;   // 120 km/h: generous for a city two-wheeler    public enum Verdict { ACCEPT, INACCURATE, OUT_OF_ORDER, IMPOSSIBLE_JUMP }    private PingFilter() {    }    public static Verdict check(RiderPing last, RiderPing next) {        if (next.accuracyMeters() > MAX_ACCURACY_METERS) return Verdict.INACCURATE;        if (last == null) return Verdict.ACCEPT;        if (next.seq() <= last.seq()) return Verdict.OUT_OF_ORDER;        double seconds = (next.deviceTimeMillis() - last.deviceTimeMillis()) / 1000.0;        double meters = Geo.distanceMeters(last.lat(), last.lng(), next.lat(), next.lng());        if (seconds <= 0 || meters / seconds > MAX_SPEED_MPS) return Verdict.IMPOSSIBLE_JUMP;        return Verdict.ACCEPT;    }}
Geo.javaJava
public final class Geo {    private static final double EARTH_RADIUS_METERS = 6_371_000;    private Geo() {    }    // Haversine: straight-line distance on a sphere. Good enough for filtering, not for ETAs.    public static double distanceMeters(double lat1, double lng1, double lat2, double lng2) {        double dLat = Math.toRadians(lat2 - lat1);        double dLng = Math.toRadians(lng2 - lng1);        double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)                + Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2))                * Math.sin(dLng / 2) * Math.sin(dLng / 2);        return 2 * EARTH_RADIUS_METERS * Math.asin(Math.sqrt(a));    }}

The reset rule is left out to keep the filter readable; it is a small counter per rider.

A rider's trail on a street map with three rejected GPS pings: a low-accuracy fix, an out-of-order fix and an impossible jump
Three checks catch most bad GPS: accuracy, sequence order and physics.

Step 3: Redis holds the latest position, nothing more

The customer only needs where the rider is now. So the hot store keeps one small hash per active order, track:{orderId}, holding seq, lat, lng and ts, with a 2-minute TTL. If the rider's phone goes silent, the key expires and the app can say "location unavailable" instead of showing a scooter frozen in place for ten minutes.

Why per order and not per rider? Reads come from customers, by order id. A rider sometimes carries two orders, so the writer looks up rider:{riderId}:orders and writes the same position into each order's hash. Two tiny writes beat an extra lookup on every read.

The write must be "only if newer", and it must be atomic, so it lives in a Lua script:

TrackingWriter.javaJava
@Componentpublic class TrackingWriter {    // Write only if this ping is newer than what is stored. One key, so it is safe on Redis Cluster.    private static final RedisScript<Long> WRITE_IF_NEWER = new DefaultRedisScript<>("""            local current = tonumber(redis.call('HGET', KEYS[1], 'seq') or '-1')            if tonumber(ARGV[1]) <= current then              return 0            end            redis.call('HSET', KEYS[1], 'seq', ARGV[1], 'lat', ARGV[2], 'lng', ARGV[3], 'ts', ARGV[4])            redis.call('PEXPIRE', KEYS[1], ARGV[5])            return 1            """, Long.class);    private static final Duration TTL = Duration.ofMinutes(2);    private final StringRedisTemplate redis;    private final ObjectMapper json;    public TrackingWriter(StringRedisTemplate redis, ObjectMapper json) {        this.redis = redis;        this.json = json;    }    public void write(RiderPing ping) throws JsonProcessingException {        // Usually one order, sometimes two when the rider carries a batched pickup.        Set<String> orderIds = redis.opsForSet().members("rider:" + ping.riderId() + ":orders");        if (orderIds == null || orderIds.isEmpty()) {            return;   // rider is online but not on a delivery        }        for (String orderId : orderIds) {            Long written = redis.execute(WRITE_IF_NEWER, List.of("track:" + orderId),                    String.valueOf(ping.seq()),                    String.valueOf(ping.lat()),                    String.valueOf(ping.lng()),                    String.valueOf(ping.deviceTimeMillis()),                    String.valueOf(TTL.toMillis()));            if (Long.valueOf(1L).equals(written)) {                String update = json.writeValueAsString(Map.of(                        "lat", ping.lat(), "lng", ping.lng(), "ts", ping.deviceTimeMillis()));                redis.convertAndSend("track-updates:" + orderId, update);            }        }    }}

The script touches a single key on purpose. On Redis Cluster, a script that wrote the order hash and a city-wide key together would fail with a CROSSSLOT error whenever the two keys live in different hash slots.

Redis GEO answers a different question. Dispatch needs "which free riders are within 3 km of this restaurant?", and that is what a GEO set per city is for:

redis-cli
GEOADD riders:geo:blr 77.6245 12.9352 R1GEOSEARCH riders:geo:blr FROMLONLAT 77.6101 12.9279 BYRADIUS 3 km ASC COUNT 10 WITHDIST

Longitude comes first, then latitude. A GEO set is a sorted set underneath, so members never expire on their own: remove a rider with ZREM when they go offline, or their last position keeps attracting orders.

GEOADD
Adds one or more members to a geospatial index. The key is created if it doesn't exist.
Docs

Why not Postgres? Every UPDATE writes a new row version, so 25,000 updates a second means a pile of dead tuples for vacuum, all for data that is stale in 4 seconds. Postgres is where the order lives, not where the dot lives.

Step 4: the ETA, without the jumps

The ETA is a sum:

  • Prep time left, if the food is not ready: from the restaurant's "food ready" signal if it sends one, otherwise an average for that restaurant at that hour.

  • Road time to the restaurant, if the rider has not picked up yet.

  • Road time to the customer, plus a small handover buffer for the gate, the guard and the lift.

"Road time" means a routing engine (a self-hosted open-source one such as OSRM or GraphHopper, or a maps API), not straight-line distance. Haversine is fine for spotting a teleport, but a rider 1.5 km away across a flyover can be 4 km away by road.

Routing calls cost money or CPU, so don't route on every ping. Recompute every 30 seconds, or at once when the rider drifts about 100 metres off the planned route, and count down in between.

Then smooth what you show. My rules:

  • Round up to whole minutes.

  • Change the number on screen only when two computations in a row disagree with it by a minute or more.

  • When the rider is parked at the restaurant, say "Your order is being packed" instead of a number that freezes.

In my view an honest ETA beats an optimistic one. An order that said 12 minutes and arrived in 10 feels better than one that said 8 and took 12.

The ETA shown as a stacked bar of prep time left, road time to the restaurant and road time to the customer
ETA is a sum of three parts, and only two of them come from the map.

Step 5: pushing updates to the customer

Polling

SSE

WebSocket

Direction

client asks every N seconds

server to client

both ways

Transport

plain HTTP requests

one long-lived HTTP response

upgraded connection

Reconnect

nothing to do

built into the browser's EventSource

you write it

Cost with 1 lakh viewers

20,000 requests/s at 5 s, mostly "no change"

1 lakh open connections, messages only on change

same, plus per-connection state

When I'd use it

fallback, or tiny scale

the tracking screen

rider chat, or an app that already keeps a socket

For a one-way feed I'd pick SSE. It is plain HTTP, proxies and load balancers already understand it, and browsers reconnect on their own. Native apps need a small SSE client library, which is a fair trade. If the app already keeps a WebSocket open for chat, reuse it rather than opening a second connection just for location.

In Spring Boot, SseEmitter does the job:

OrderEmitters.javaJava
@Componentpublic class OrderEmitters {    private final Map<String, Set<SseEmitter>> byOrder = new ConcurrentHashMap<>();    public SseEmitter open(String orderId) {        SseEmitter emitter = new SseEmitter(Duration.ofMinutes(30).toMillis());        byOrder.computeIfAbsent(orderId, id -> ConcurrentHashMap.newKeySet()).add(emitter);        Runnable remove = () -> remove(orderId, emitter);        emitter.onCompletion(remove);        emitter.onTimeout(remove);        emitter.onError(e -> remove.run());        return emitter;    }    public void push(String orderId, String updateJson) {        for (SseEmitter emitter : byOrder.getOrDefault(orderId, Set.of())) {            try {                emitter.send(SseEmitter.event().name("location").data(updateJson, MediaType.APPLICATION_JSON));            } catch (IOException | IllegalStateException e) {                remove(orderId, emitter);   // the app went away; EventSource will reconnect if it can            }        }    }    private void remove(String orderId, SseEmitter emitter) {        byOrder.computeIfPresent(orderId, (id, set) -> {            set.remove(emitter);            return set.isEmpty() ? null : set;        });    }}
TrackingController.javaJava
@RestControllerpublic class TrackingController {    private final OrderEmitters emitters;    private final StringRedisTemplate redis;    public TrackingController(OrderEmitters emitters, StringRedisTemplate redis) {        this.emitters = emitters;        this.redis = redis;    }    @GetMapping(path = "/api/orders/{orderId}/track", produces = MediaType.TEXT_EVENT_STREAM_VALUE)    public SseEmitter track(@PathVariable String orderId) throws IOException {        // Check here that the signed-in customer owns this order (omitted for brevity).        SseEmitter emitter = emitters.open(orderId);        // Send the current position at once, so a reconnect never shows an empty map.        Map<Object, Object> latest = redis.opsForHash().entries("track:" + orderId);        if (!latest.isEmpty()) {            emitter.send(SseEmitter.event().name("location").data(latest));        }        return emitter;    }}

Sending the current position the moment the stream opens matters: a customer who switches apps and comes back should see the rider straight away, not after the next ping. Spring buffers a send made before the handler returns.

Fan-out across app nodes

Each SSE connection lives on one app node, but the consumer that accepted the ping can be on any node. Redis pub/sub bridges the gap: the writer publishes to track-updates:{orderId}, every node subscribes to the pattern, and each node pushes only to the connections it holds. I wrote about the same pattern for notifications in How a notification reaches you instantly, on every device.

TrackingFanoutConfig.javaJava
@Configurationclass TrackingFanoutConfig {    private static final String PREFIX = "track-updates:";    // Every app node hears every update and pushes it to the SSE connections it holds.    @Bean    RedisMessageListenerContainer trackingListener(RedisConnectionFactory factory, OrderEmitters emitters) {        RedisMessageListenerContainer container = new RedisMessageListenerContainer();        container.setConnectionFactory(factory);        container.addMessageListener((message, pattern) -> {            String channel = new String(message.getChannel(), StandardCharsets.UTF_8);            String orderId = channel.substring(PREFIX.length());            emitters.push(orderId, new String(message.getBody(), StandardCharsets.UTF_8));        }, PatternTopic.of(PREFIX + "*"));        return container;    }}

The cost: every node hears every update, even for orders it holds no connection for. Two levers, in the order I'd pull them. First, publish at most once every few seconds per order, and only when the rider has moved more than about 20 metres. Second, route each order's connections to a fixed group of nodes by hashing the order id, so each node subscribes only to its share.

An update published to Redis pub/sub reaches three app nodes, and only the node holding the customer's SSE connection pushes it
Every node hears every update; only the node holding the customer's connection sends it.

Step 6: what to keep and what to throw away

  • Latest position: Redis, minutes, TTL.

  • Raw pings: Kafka, retained for a few days, for debugging and replays.

  • A thinned trip trail: one point every 20-30 seconds plus the turns, written to cheap storage when the trip ends, for disputes and for rider pay if it depends on distance.

  • Nothing else. Rider location is personal data. Show it only to the customer of an active order, stop tracking at delivery, and give the trail a retention period instead of keeping it forever.

What I listen for in the live order tracking system design round

  • Stated the numbers before drawing boxes

  • Separated the rider write path from the customer read path

  • Kept each rider's pings in order (partition key plus sequence number)

  • Filtered bad GPS instead of drawing it

  • Kept only the latest position hot, with a TTL

  • Built the ETA from road time and smoothed it

  • Chose a push channel and named the fallback

  • Handled fan-out across app nodes

  • Said what happens when the rider's phone goes offline

  • Mentioned retention and privacy

The classic miss: a WebSocket in minute one, then the whole hour on connection handling, while GPS noise and the ETA never come up.

The 60-second interview answer

Rider phones send a GPS fix every few seconds, with a sequence number and an accuracy radius, to a stateless ingest API that writes to Kafka, partitioned by rider id. A consumer drops fixes with poor accuracy, old sequence numbers or impossible speed, and a Lua script writes the latest position per order into a Redis hash with a short TTL. An ETA service adds prep time to road time from a routing engine, recomputes every 30 seconds or when the rider goes off route, and smooths the number. The customer app holds an SSE connection, fed through Redis pub/sub, with polling as the fallback. At 1 lakh active orders that is 25,000 writes a second, so nothing on the hot path touches Postgres. Raw pings stay in Kafka for a few days, a thinned trail is kept for disputes, and tracking stops at delivery.

Try it yourself

1. A rider goes through an underpass, loses signal for two minutes, then uploads 30 buffered pings at once. What does your system do?

Answer 1

The pings arrive in sequence order on the rider's partition. Each one passes or fails the filter, and the live hash ends at the newest accepted one, so the dot jumps once to the current position. Don't animate through all 30 points on the customer's screen; push only the latest. All 30 are still in Kafka, so the trip trail is complete. Recompute the ETA once after the batch, not 30 times.

2. One rider carries two orders, and customer A's drop comes first. What changes for customer B?

Answer 2

The writer puts the same position into both order hashes, but the ETAs differ: B's ETA must include the time to finish A's drop. B must never see A's address or route, only the rider's position and their own ETA. One more reason to key the read model by order.

3. If you send event ids, the browser's EventSource reconnects with a Last-Event-ID header. Should you replay the events it missed?

Answer 3

No. Only the latest position matters, so replaying missed points just makes the dot crawl through the past. On reconnect, send the current snapshot from Redis straight away (the controller above already does) and carry on from there.

© 2026 Rohit Parihar. All rights reserved.

RP

Discussion

?